sqlite3.c revision 251886
1/******************************************************************************
2** This file is an amalgamation of many separate C source files from SQLite
3** version 3.7.17.  By combining all the individual C code files into this
4** single large file, the entire code can be compiled as a single translation
5** unit.  This allows many compilers to do optimizations that would not be
6** possible if the files were compiled separately.  Performance improvements
7** of 5% or more are commonly seen when SQLite is compiled as a single
8** translation unit.
9**
10** This file is all you need to compile SQLite.  To use SQLite in other
11** programs, you need this file and the "sqlite3.h" header file that defines
12** the programming interface to the SQLite library.  (If you do not have
13** the "sqlite3.h" header file at hand, you will find a copy embedded within
14** the text of this file.  Search for "Begin file sqlite3.h" to find the start
15** of the embedded sqlite3.h header file.) Additional code files may be needed
16** if you want a wrapper to interface SQLite with your choice of programming
17** language. The code for the "sqlite3" command-line shell is also in a
18** separate file. This file contains only code for the core SQLite library.
19*/
20#define SQLITE_CORE 1
21#define SQLITE_AMALGAMATION 1
22#ifndef SQLITE_PRIVATE
23# define SQLITE_PRIVATE static
24#endif
25#ifndef SQLITE_API
26# define SQLITE_API
27#endif
28/************** Begin file sqliteInt.h ***************************************/
29/*
30** 2001 September 15
31**
32** The author disclaims copyright to this source code.  In place of
33** a legal notice, here is a blessing:
34**
35**    May you do good and not evil.
36**    May you find forgiveness for yourself and forgive others.
37**    May you share freely, never taking more than you give.
38**
39*************************************************************************
40** Internal interface definitions for SQLite.
41**
42*/
43#ifndef _SQLITEINT_H_
44#define _SQLITEINT_H_
45
46/*
47** These #defines should enable >2GB file support on POSIX if the
48** underlying operating system supports it.  If the OS lacks
49** large file support, or if the OS is windows, these should be no-ops.
50**
51** Ticket #2739:  The _LARGEFILE_SOURCE macro must appear before any
52** system #includes.  Hence, this block of code must be the very first
53** code in all source files.
54**
55** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
56** on the compiler command line.  This is necessary if you are compiling
57** on a recent machine (ex: Red Hat 7.2) but you want your code to work
58** on an older machine (ex: Red Hat 6.0).  If you compile on Red Hat 7.2
59** without this option, LFS is enable.  But LFS does not exist in the kernel
60** in Red Hat 6.0, so the code won't work.  Hence, for maximum binary
61** portability you should omit LFS.
62**
63** 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 default number of frames to accumulate in the log file before
195** checkpointing the database in WAL mode.
196*/
197#ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
198# define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT  1000
199#endif
200
201/*
202** The maximum number of attached databases.  This must be between 0
203** and 62.  The upper bound on 62 is because a 64-bit integer bitmap
204** is used internally to track attached databases.
205*/
206#ifndef SQLITE_MAX_ATTACHED
207# define SQLITE_MAX_ATTACHED 10
208#endif
209
210
211/*
212** The maximum value of a ?nnn wildcard that the parser will accept.
213*/
214#ifndef SQLITE_MAX_VARIABLE_NUMBER
215# define SQLITE_MAX_VARIABLE_NUMBER 999
216#endif
217
218/* Maximum page size.  The upper bound on this value is 65536.  This a limit
219** imposed by the use of 16-bit offsets within each page.
220**
221** Earlier versions of SQLite allowed the user to change this value at
222** compile time. This is no longer permitted, on the grounds that it creates
223** a library that is technically incompatible with an SQLite library
224** compiled with a different limit. If a process operating on a database
225** with a page-size of 65536 bytes crashes, then an instance of SQLite
226** compiled with the default page-size limit will not be able to rollback
227** the aborted transaction. This could lead to database corruption.
228*/
229#ifdef SQLITE_MAX_PAGE_SIZE
230# undef SQLITE_MAX_PAGE_SIZE
231#endif
232#define SQLITE_MAX_PAGE_SIZE 65536
233
234
235/*
236** The default size of a database page.
237*/
238#ifndef SQLITE_DEFAULT_PAGE_SIZE
239# define SQLITE_DEFAULT_PAGE_SIZE 1024
240#endif
241#if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
242# undef SQLITE_DEFAULT_PAGE_SIZE
243# define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
244#endif
245
246/*
247** Ordinarily, if no value is explicitly provided, SQLite creates databases
248** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
249** device characteristics (sector-size and atomic write() support),
250** SQLite may choose a larger value. This constant is the maximum value
251** SQLite will choose on its own.
252*/
253#ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
254# define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
255#endif
256#if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
257# undef SQLITE_MAX_DEFAULT_PAGE_SIZE
258# define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
259#endif
260
261
262/*
263** Maximum number of pages in one database file.
264**
265** This is really just the default value for the max_page_count pragma.
266** This value can be lowered (or raised) at run-time using that the
267** max_page_count macro.
268*/
269#ifndef SQLITE_MAX_PAGE_COUNT
270# define SQLITE_MAX_PAGE_COUNT 1073741823
271#endif
272
273/*
274** Maximum length (in bytes) of the pattern in a LIKE or GLOB
275** operator.
276*/
277#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
278# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
279#endif
280
281/*
282** Maximum depth of recursion for triggers.
283**
284** A value of 1 means that a trigger program will not be able to itself
285** fire any triggers. A value of 0 means that no trigger programs at all
286** may be executed.
287*/
288#ifndef SQLITE_MAX_TRIGGER_DEPTH
289# define SQLITE_MAX_TRIGGER_DEPTH 1000
290#endif
291
292/************** End of sqliteLimit.h *****************************************/
293/************** Continuing where we left off in sqliteInt.h ******************/
294
295/* Disable nuisance warnings on Borland compilers */
296#if defined(__BORLANDC__)
297#pragma warn -rch /* unreachable code */
298#pragma warn -ccc /* Condition is always true or false */
299#pragma warn -aus /* Assigned value is never used */
300#pragma warn -csu /* Comparing signed and unsigned */
301#pragma warn -spa /* Suspicious pointer arithmetic */
302#endif
303
304/* Needed for various definitions... */
305#ifndef _GNU_SOURCE
306# define _GNU_SOURCE
307#endif
308
309#if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
310# define _BSD_SOURCE
311#endif
312
313/*
314** Include standard header files as necessary
315*/
316#ifdef HAVE_STDINT_H
317#include <stdint.h>
318#endif
319#ifdef HAVE_INTTYPES_H
320#include <inttypes.h>
321#endif
322
323/*
324** The following macros are used to cast pointers to integers and
325** integers to pointers.  The way you do this varies from one compiler
326** to the next, so we have developed the following set of #if statements
327** to generate appropriate macros for a wide range of compilers.
328**
329** The correct "ANSI" way to do this is to use the intptr_t type.
330** Unfortunately, that typedef is not available on all compilers, or
331** if it is available, it requires an #include of specific headers
332** that vary from one machine to the next.
333**
334** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
335** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
336** So we have to define the macros in different ways depending on the
337** compiler.
338*/
339#if defined(__PTRDIFF_TYPE__)  /* This case should work for GCC */
340# define SQLITE_INT_TO_PTR(X)  ((void*)(__PTRDIFF_TYPE__)(X))
341# define SQLITE_PTR_TO_INT(X)  ((int)(__PTRDIFF_TYPE__)(X))
342#elif !defined(__GNUC__)       /* Works for compilers other than LLVM */
343# define SQLITE_INT_TO_PTR(X)  ((void*)&((char*)0)[X])
344# define SQLITE_PTR_TO_INT(X)  ((int)(((char*)X)-(char*)0))
345#elif defined(HAVE_STDINT_H)   /* Use this case if we have ANSI headers */
346# define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
347# define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))
348#else                          /* Generates a warning - but it always works */
349# define SQLITE_INT_TO_PTR(X)  ((void*)(X))
350# define SQLITE_PTR_TO_INT(X)  ((int)(X))
351#endif
352
353/*
354** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
355** 0 means mutexes are permanently disable and the library is never
356** threadsafe.  1 means the library is serialized which is the highest
357** level of threadsafety.  2 means the libary is multithreaded - multiple
358** threads can use SQLite as long as no two threads try to use the same
359** database connection at the same time.
360**
361** Older versions of SQLite used an optional THREADSAFE macro.
362** We support that for legacy.
363*/
364#if !defined(SQLITE_THREADSAFE)
365# if defined(THREADSAFE)
366#   define SQLITE_THREADSAFE THREADSAFE
367# else
368#   define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
369# endif
370#endif
371
372/*
373** Powersafe overwrite is on by default.  But can be turned off using
374** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
375*/
376#ifndef SQLITE_POWERSAFE_OVERWRITE
377# define SQLITE_POWERSAFE_OVERWRITE 1
378#endif
379
380/*
381** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
382** It determines whether or not the features related to
383** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
384** be overridden at runtime using the sqlite3_config() API.
385*/
386#if !defined(SQLITE_DEFAULT_MEMSTATUS)
387# define SQLITE_DEFAULT_MEMSTATUS 1
388#endif
389
390/*
391** Exactly one of the following macros must be defined in order to
392** specify which memory allocation subsystem to use.
393**
394**     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
395**     SQLITE_WIN32_MALLOC           // Use Win32 native heap API
396**     SQLITE_ZERO_MALLOC            // Use a stub allocator that always fails
397**     SQLITE_MEMDEBUG               // Debugging version of system malloc()
398**
399** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
400** assert() macro is enabled, each call into the Win32 native heap subsystem
401** will cause HeapValidate to be called.  If heap validation should fail, an
402** assertion will be triggered.
403**
404** (Historical note:  There used to be several other options, but we've
405** pared it down to just these three.)
406**
407** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
408** the default.
409*/
410#if defined(SQLITE_SYSTEM_MALLOC) \
411  + defined(SQLITE_WIN32_MALLOC) \
412  + defined(SQLITE_ZERO_MALLOC) \
413  + defined(SQLITE_MEMDEBUG)>1
414# error "Two or more of the following compile-time configuration options\
415 are defined but at most one is allowed:\
416 SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
417 SQLITE_ZERO_MALLOC"
418#endif
419#if defined(SQLITE_SYSTEM_MALLOC) \
420  + defined(SQLITE_WIN32_MALLOC) \
421  + defined(SQLITE_ZERO_MALLOC) \
422  + defined(SQLITE_MEMDEBUG)==0
423# define SQLITE_SYSTEM_MALLOC 1
424#endif
425
426/*
427** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
428** sizes of memory allocations below this value where possible.
429*/
430#if !defined(SQLITE_MALLOC_SOFT_LIMIT)
431# define SQLITE_MALLOC_SOFT_LIMIT 1024
432#endif
433
434/*
435** We need to define _XOPEN_SOURCE as follows in order to enable
436** recursive mutexes on most Unix systems.  But Mac OS X is different.
437** The _XOPEN_SOURCE define causes problems for Mac OS X we are told,
438** so it is omitted there.  See ticket #2673.
439**
440** Later we learn that _XOPEN_SOURCE is poorly or incorrectly
441** implemented on some systems.  So we avoid defining it at all
442** if it is already defined or if it is unneeded because we are
443** not doing a threadsafe build.  Ticket #2681.
444**
445** See also ticket #2741.
446*/
447#if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) \
448 && !defined(__APPLE__) && SQLITE_THREADSAFE
449#  define _XOPEN_SOURCE 500  /* Needed to enable pthread recursive mutexes */
450#endif
451
452/*
453** The TCL headers are only needed when compiling the TCL bindings.
454*/
455#if defined(SQLITE_TCL) || defined(TCLSH)
456# include <tcl.h>
457#endif
458
459/*
460** NDEBUG and SQLITE_DEBUG are opposites.  It should always be true that
461** defined(NDEBUG)==!defined(SQLITE_DEBUG).  If this is not currently true,
462** make it true by defining or undefining NDEBUG.
463**
464** Setting NDEBUG makes the code smaller and run faster by disabling the
465** number assert() statements in the code.  So we want the default action
466** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
467** is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
468** feature.
469*/
470#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
471# define NDEBUG 1
472#endif
473#if defined(NDEBUG) && defined(SQLITE_DEBUG)
474# undef NDEBUG
475#endif
476
477/*
478** The testcase() macro is used to aid in coverage testing.  When
479** doing coverage testing, the condition inside the argument to
480** testcase() must be evaluated both true and false in order to
481** get full branch coverage.  The testcase() macro is inserted
482** to help ensure adequate test coverage in places where simple
483** condition/decision coverage is inadequate.  For example, testcase()
484** can be used to make sure boundary values are tested.  For
485** bitmask tests, testcase() can be used to make sure each bit
486** is significant and used at least once.  On switch statements
487** where multiple cases go to the same block of code, testcase()
488** can insure that all cases are evaluated.
489**
490*/
491#ifdef SQLITE_COVERAGE_TEST
492SQLITE_PRIVATE   void sqlite3Coverage(int);
493# define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
494#else
495# define testcase(X)
496#endif
497
498/*
499** The TESTONLY macro is used to enclose variable declarations or
500** other bits of code that are needed to support the arguments
501** within testcase() and assert() macros.
502*/
503#if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
504# define TESTONLY(X)  X
505#else
506# define TESTONLY(X)
507#endif
508
509/*
510** Sometimes we need a small amount of code such as a variable initialization
511** to setup for a later assert() statement.  We do not want this code to
512** appear when assert() is disabled.  The following macro is therefore
513** used to contain that setup code.  The "VVA" acronym stands for
514** "Verification, Validation, and Accreditation".  In other words, the
515** code within VVA_ONLY() will only run during verification processes.
516*/
517#ifndef NDEBUG
518# define VVA_ONLY(X)  X
519#else
520# define VVA_ONLY(X)
521#endif
522
523/*
524** The ALWAYS and NEVER macros surround boolean expressions which
525** are intended to always be true or false, respectively.  Such
526** expressions could be omitted from the code completely.  But they
527** are included in a few cases in order to enhance the resilience
528** of SQLite to unexpected behavior - to make the code "self-healing"
529** or "ductile" rather than being "brittle" and crashing at the first
530** hint of unplanned behavior.
531**
532** In other words, ALWAYS and NEVER are added for defensive code.
533**
534** When doing coverage testing ALWAYS and NEVER are hard-coded to
535** be true and false so that the unreachable code then specify will
536** not be counted as untested code.
537*/
538#if defined(SQLITE_COVERAGE_TEST)
539# define ALWAYS(X)      (1)
540# define NEVER(X)       (0)
541#elif !defined(NDEBUG)
542# define ALWAYS(X)      ((X)?1:(assert(0),0))
543# define NEVER(X)       ((X)?(assert(0),1):0)
544#else
545# define ALWAYS(X)      (X)
546# define NEVER(X)       (X)
547#endif
548
549/*
550** Return true (non-zero) if the input is a integer that is too large
551** to fit in 32-bits.  This macro is used inside of various testcase()
552** macros to verify that we have tested SQLite for large-file support.
553*/
554#define IS_BIG_INT(X)  (((X)&~(i64)0xffffffff)!=0)
555
556/*
557** The macro unlikely() is a hint that surrounds a boolean
558** expression that is usually false.  Macro likely() surrounds
559** a boolean expression that is usually true.  GCC is able to
560** use these hints to generate better code, sometimes.
561*/
562#if defined(__GNUC__) && 0
563# define likely(X)    __builtin_expect((X),1)
564# define unlikely(X)  __builtin_expect((X),0)
565#else
566# define likely(X)    !!(X)
567# define unlikely(X)  !!(X)
568#endif
569
570/************** Include sqlite3.h in the middle of sqliteInt.h ***************/
571/************** Begin file sqlite3.h *****************************************/
572/*
573** 2001 September 15
574**
575** The author disclaims copyright to this source code.  In place of
576** a legal notice, here is a blessing:
577**
578**    May you do good and not evil.
579**    May you find forgiveness for yourself and forgive others.
580**    May you share freely, never taking more than you give.
581**
582*************************************************************************
583** This header file defines the interface that the SQLite library
584** presents to client programs.  If a C-function, structure, datatype,
585** or constant definition does not appear in this file, then it is
586** not a published API of SQLite, is subject to change without
587** notice, and should not be referenced by programs that use SQLite.
588**
589** Some of the definitions that are in this file are marked as
590** "experimental".  Experimental interfaces are normally new
591** features recently added to SQLite.  We do not anticipate changes
592** to experimental interfaces but reserve the right to make minor changes
593** if experience from use "in the wild" suggest such changes are prudent.
594**
595** The official C-language API documentation for SQLite is derived
596** from comments in this file.  This file is the authoritative source
597** on how SQLite interfaces are suppose to operate.
598**
599** The name of this file under configuration management is "sqlite.h.in".
600** The makefile makes some minor changes to this file (such as inserting
601** the version number) and changes its name to "sqlite3.h" as
602** part of the build process.
603*/
604#ifndef _SQLITE3_H_
605#define _SQLITE3_H_
606#include <stdarg.h>     /* Needed for the definition of va_list */
607
608/*
609** Make sure we can call this stuff from C++.
610*/
611#if 0
612extern "C" {
613#endif
614
615
616/*
617** Add the ability to override 'extern'
618*/
619#ifndef SQLITE_EXTERN
620# define SQLITE_EXTERN extern
621#endif
622
623#ifndef SQLITE_API
624# define SQLITE_API
625#endif
626
627
628/*
629** These no-op macros are used in front of interfaces to mark those
630** interfaces as either deprecated or experimental.  New applications
631** should not use deprecated interfaces - they are support for backwards
632** compatibility only.  Application writers should be aware that
633** experimental interfaces are subject to change in point releases.
634**
635** These macros used to resolve to various kinds of compiler magic that
636** would generate warning messages when they were used.  But that
637** compiler magic ended up generating such a flurry of bug reports
638** that we have taken it all out and gone back to using simple
639** noop macros.
640*/
641#define SQLITE_DEPRECATED
642#define SQLITE_EXPERIMENTAL
643
644/*
645** Ensure these symbols were not defined by some previous header file.
646*/
647#ifdef SQLITE_VERSION
648# undef SQLITE_VERSION
649#endif
650#ifdef SQLITE_VERSION_NUMBER
651# undef SQLITE_VERSION_NUMBER
652#endif
653
654/*
655** CAPI3REF: Compile-Time Library Version Numbers
656**
657** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
658** evaluates to a string literal that is the SQLite version in the
659** format "X.Y.Z" where X is the major version number (always 3 for
660** SQLite3) and Y is the minor version number and Z is the release number.)^
661** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
662** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
663** numbers used in [SQLITE_VERSION].)^
664** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
665** be larger than the release from which it is derived.  Either Y will
666** be held constant and Z will be incremented or else Y will be incremented
667** and Z will be reset to zero.
668**
669** Since version 3.6.18, SQLite source code has been stored in the
670** <a href="http://www.fossil-scm.org/">Fossil configuration management
671** system</a>.  ^The SQLITE_SOURCE_ID macro evaluates to
672** a string which identifies a particular check-in of SQLite
673** within its configuration management system.  ^The SQLITE_SOURCE_ID
674** string contains the date and time of the check-in (UTC) and an SHA1
675** hash of the entire source tree.
676**
677** See also: [sqlite3_libversion()],
678** [sqlite3_libversion_number()], [sqlite3_sourceid()],
679** [sqlite_version()] and [sqlite_source_id()].
680*/
681#define SQLITE_VERSION        "3.7.17"
682#define SQLITE_VERSION_NUMBER 3007017
683#define SQLITE_SOURCE_ID      "2013-05-20 00:56:22 118a3b35693b134d56ebd780123b7fd6f1497668"
684
685/*
686** CAPI3REF: Run-Time Library Version Numbers
687** KEYWORDS: sqlite3_version, sqlite3_sourceid
688**
689** These interfaces provide the same information as the [SQLITE_VERSION],
690** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
691** but are associated with the library instead of the header file.  ^(Cautious
692** programmers might include assert() statements in their application to
693** verify that values returned by these interfaces match the macros in
694** the header, and thus insure that the application is
695** compiled with matching library and header files.
696**
697** <blockquote><pre>
698** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
699** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
700** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
701** </pre></blockquote>)^
702**
703** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
704** macro.  ^The sqlite3_libversion() function returns a pointer to the
705** to the sqlite3_version[] string constant.  The sqlite3_libversion()
706** function is provided for use in DLLs since DLL users usually do not have
707** direct access to string constants within the DLL.  ^The
708** sqlite3_libversion_number() function returns an integer equal to
709** [SQLITE_VERSION_NUMBER].  ^The sqlite3_sourceid() function returns
710** a pointer to a string constant whose value is the same as the
711** [SQLITE_SOURCE_ID] C preprocessor macro.
712**
713** See also: [sqlite_version()] and [sqlite_source_id()].
714*/
715SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
716SQLITE_API const char *sqlite3_libversion(void);
717SQLITE_API const char *sqlite3_sourceid(void);
718SQLITE_API int sqlite3_libversion_number(void);
719
720/*
721** CAPI3REF: Run-Time Library Compilation Options Diagnostics
722**
723** ^The sqlite3_compileoption_used() function returns 0 or 1
724** indicating whether the specified option was defined at
725** compile time.  ^The SQLITE_ prefix may be omitted from the
726** option name passed to sqlite3_compileoption_used().
727**
728** ^The sqlite3_compileoption_get() function allows iterating
729** over the list of options that were defined at compile time by
730** returning the N-th compile time option string.  ^If N is out of range,
731** sqlite3_compileoption_get() returns a NULL pointer.  ^The SQLITE_
732** prefix is omitted from any strings returned by
733** sqlite3_compileoption_get().
734**
735** ^Support for the diagnostic functions sqlite3_compileoption_used()
736** and sqlite3_compileoption_get() may be omitted by specifying the
737** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
738**
739** See also: SQL functions [sqlite_compileoption_used()] and
740** [sqlite_compileoption_get()] and the [compile_options pragma].
741*/
742#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
743SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
744SQLITE_API const char *sqlite3_compileoption_get(int N);
745#endif
746
747/*
748** CAPI3REF: Test To See If The Library Is Threadsafe
749**
750** ^The sqlite3_threadsafe() function returns zero if and only if
751** SQLite was compiled with mutexing code omitted due to the
752** [SQLITE_THREADSAFE] compile-time option being set to 0.
753**
754** SQLite can be compiled with or without mutexes.  When
755** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
756** are enabled and SQLite is threadsafe.  When the
757** [SQLITE_THREADSAFE] macro is 0,
758** the mutexes are omitted.  Without the mutexes, it is not safe
759** to use SQLite concurrently from more than one thread.
760**
761** Enabling mutexes incurs a measurable performance penalty.
762** So if speed is of utmost importance, it makes sense to disable
763** the mutexes.  But for maximum safety, mutexes should be enabled.
764** ^The default behavior is for mutexes to be enabled.
765**
766** This interface can be used by an application to make sure that the
767** version of SQLite that it is linking against was compiled with
768** the desired setting of the [SQLITE_THREADSAFE] macro.
769**
770** This interface only reports on the compile-time mutex setting
771** of the [SQLITE_THREADSAFE] flag.  If SQLite is compiled with
772** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
773** can be fully or partially disabled using a call to [sqlite3_config()]
774** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
775** or [SQLITE_CONFIG_MUTEX].  ^(The return value of the
776** sqlite3_threadsafe() function shows only the compile-time setting of
777** thread safety, not any run-time changes to that setting made by
778** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
779** is unchanged by calls to sqlite3_config().)^
780**
781** See the [threading mode] documentation for additional information.
782*/
783SQLITE_API int sqlite3_threadsafe(void);
784
785/*
786** CAPI3REF: Database Connection Handle
787** KEYWORDS: {database connection} {database connections}
788**
789** Each open SQLite database is represented by a pointer to an instance of
790** the opaque structure named "sqlite3".  It is useful to think of an sqlite3
791** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
792** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
793** and [sqlite3_close_v2()] are its destructors.  There are many other
794** interfaces (such as
795** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
796** [sqlite3_busy_timeout()] to name but three) that are methods on an
797** sqlite3 object.
798*/
799typedef struct sqlite3 sqlite3;
800
801/*
802** CAPI3REF: 64-Bit Integer Types
803** KEYWORDS: sqlite_int64 sqlite_uint64
804**
805** Because there is no cross-platform way to specify 64-bit integer types
806** SQLite includes typedefs for 64-bit signed and unsigned integers.
807**
808** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
809** The sqlite_int64 and sqlite_uint64 types are supported for backwards
810** compatibility only.
811**
812** ^The sqlite3_int64 and sqlite_int64 types can store integer values
813** between -9223372036854775808 and +9223372036854775807 inclusive.  ^The
814** sqlite3_uint64 and sqlite_uint64 types can store integer values
815** between 0 and +18446744073709551615 inclusive.
816*/
817#ifdef SQLITE_INT64_TYPE
818  typedef SQLITE_INT64_TYPE sqlite_int64;
819  typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
820#elif defined(_MSC_VER) || defined(__BORLANDC__)
821  typedef __int64 sqlite_int64;
822  typedef unsigned __int64 sqlite_uint64;
823#else
824  typedef long long int sqlite_int64;
825  typedef unsigned long long int sqlite_uint64;
826#endif
827typedef sqlite_int64 sqlite3_int64;
828typedef sqlite_uint64 sqlite3_uint64;
829
830/*
831** If compiling for a processor that lacks floating point support,
832** substitute integer for floating-point.
833*/
834#ifdef SQLITE_OMIT_FLOATING_POINT
835# define double sqlite3_int64
836#endif
837
838/*
839** CAPI3REF: Closing A Database Connection
840**
841** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
842** for the [sqlite3] object.
843** ^Calls to sqlite3_close() and sqlite3_close_v2() return SQLITE_OK if
844** the [sqlite3] object is successfully destroyed and all associated
845** resources are deallocated.
846**
847** ^If the database connection is associated with unfinalized prepared
848** statements or unfinished sqlite3_backup objects then sqlite3_close()
849** will leave the database connection open and return [SQLITE_BUSY].
850** ^If sqlite3_close_v2() is called with unfinalized prepared statements
851** and unfinished sqlite3_backups, then the database connection becomes
852** an unusable "zombie" which will automatically be deallocated when the
853** last prepared statement is finalized or the last sqlite3_backup is
854** finished.  The sqlite3_close_v2() interface is intended for use with
855** host languages that are garbage collected, and where the order in which
856** destructors are called is arbitrary.
857**
858** Applications should [sqlite3_finalize | finalize] all [prepared statements],
859** [sqlite3_blob_close | close] all [BLOB handles], and
860** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
861** with the [sqlite3] object prior to attempting to close the object.  ^If
862** sqlite3_close_v2() is called on a [database connection] that still has
863** outstanding [prepared statements], [BLOB handles], and/or
864** [sqlite3_backup] objects then it returns SQLITE_OK but the deallocation
865** of resources is deferred until all [prepared statements], [BLOB handles],
866** and [sqlite3_backup] objects are also destroyed.
867**
868** ^If an [sqlite3] object is destroyed while a transaction is open,
869** the transaction is automatically rolled back.
870**
871** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
872** must be either a NULL
873** pointer or an [sqlite3] object pointer obtained
874** from [sqlite3_open()], [sqlite3_open16()], or
875** [sqlite3_open_v2()], and not previously closed.
876** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
877** argument is a harmless no-op.
878*/
879SQLITE_API int sqlite3_close(sqlite3*);
880SQLITE_API int sqlite3_close_v2(sqlite3*);
881
882/*
883** The type for a callback function.
884** This is legacy and deprecated.  It is included for historical
885** compatibility and is not documented.
886*/
887typedef int (*sqlite3_callback)(void*,int,char**, char**);
888
889/*
890** CAPI3REF: One-Step Query Execution Interface
891**
892** The sqlite3_exec() interface is a convenience wrapper around
893** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
894** that allows an application to run multiple statements of SQL
895** without having to use a lot of C code.
896**
897** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
898** semicolon-separate SQL statements passed into its 2nd argument,
899** in the context of the [database connection] passed in as its 1st
900** argument.  ^If the callback function of the 3rd argument to
901** sqlite3_exec() is not NULL, then it is invoked for each result row
902** coming out of the evaluated SQL statements.  ^The 4th argument to
903** sqlite3_exec() is relayed through to the 1st argument of each
904** callback invocation.  ^If the callback pointer to sqlite3_exec()
905** is NULL, then no callback is ever invoked and result rows are
906** ignored.
907**
908** ^If an error occurs while evaluating the SQL statements passed into
909** sqlite3_exec(), then execution of the current statement stops and
910** subsequent statements are skipped.  ^If the 5th parameter to sqlite3_exec()
911** is not NULL then any error message is written into memory obtained
912** from [sqlite3_malloc()] and passed back through the 5th parameter.
913** To avoid memory leaks, the application should invoke [sqlite3_free()]
914** on error message strings returned through the 5th parameter of
915** of sqlite3_exec() after the error message string is no longer needed.
916** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
917** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
918** NULL before returning.
919**
920** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
921** routine returns SQLITE_ABORT without invoking the callback again and
922** without running any subsequent SQL statements.
923**
924** ^The 2nd argument to the sqlite3_exec() callback function is the
925** number of columns in the result.  ^The 3rd argument to the sqlite3_exec()
926** callback is an array of pointers to strings obtained as if from
927** [sqlite3_column_text()], one for each column.  ^If an element of a
928** result row is NULL then the corresponding string pointer for the
929** sqlite3_exec() callback is a NULL pointer.  ^The 4th argument to the
930** sqlite3_exec() callback is an array of pointers to strings where each
931** entry represents the name of corresponding result column as obtained
932** from [sqlite3_column_name()].
933**
934** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
935** to an empty string, or a pointer that contains only whitespace and/or
936** SQL comments, then no SQL statements are evaluated and the database
937** is not changed.
938**
939** Restrictions:
940**
941** <ul>
942** <li> The application must insure that the 1st parameter to sqlite3_exec()
943**      is a valid and open [database connection].
944** <li> The application must not close [database connection] specified by
945**      the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
946** <li> The application must not modify the SQL statement text passed into
947**      the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
948** </ul>
949*/
950SQLITE_API int sqlite3_exec(
951  sqlite3*,                                  /* An open database */
952  const char *sql,                           /* SQL to be evaluated */
953  int (*callback)(void*,int,char**,char**),  /* Callback function */
954  void *,                                    /* 1st argument to callback */
955  char **errmsg                              /* Error msg written here */
956);
957
958/*
959** CAPI3REF: Result Codes
960** KEYWORDS: SQLITE_OK {error code} {error codes}
961** KEYWORDS: {result code} {result codes}
962**
963** Many SQLite functions return an integer result code from the set shown
964** here in order to indicate success or failure.
965**
966** New error codes may be added in future versions of SQLite.
967**
968** See also: [SQLITE_IOERR_READ | extended result codes],
969** [sqlite3_vtab_on_conflict()] [SQLITE_ROLLBACK | result codes].
970*/
971#define SQLITE_OK           0   /* Successful result */
972/* beginning-of-error-codes */
973#define SQLITE_ERROR        1   /* SQL error or missing database */
974#define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
975#define SQLITE_PERM         3   /* Access permission denied */
976#define SQLITE_ABORT        4   /* Callback routine requested an abort */
977#define SQLITE_BUSY         5   /* The database file is locked */
978#define SQLITE_LOCKED       6   /* A table in the database is locked */
979#define SQLITE_NOMEM        7   /* A malloc() failed */
980#define SQLITE_READONLY     8   /* Attempt to write a readonly database */
981#define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
982#define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
983#define SQLITE_CORRUPT     11   /* The database disk image is malformed */
984#define SQLITE_NOTFOUND    12   /* Unknown opcode in sqlite3_file_control() */
985#define SQLITE_FULL        13   /* Insertion failed because database is full */
986#define SQLITE_CANTOPEN    14   /* Unable to open the database file */
987#define SQLITE_PROTOCOL    15   /* Database lock protocol error */
988#define SQLITE_EMPTY       16   /* Database is empty */
989#define SQLITE_SCHEMA      17   /* The database schema changed */
990#define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
991#define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
992#define SQLITE_MISMATCH    20   /* Data type mismatch */
993#define SQLITE_MISUSE      21   /* Library used incorrectly */
994#define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
995#define SQLITE_AUTH        23   /* Authorization denied */
996#define SQLITE_FORMAT      24   /* Auxiliary database format error */
997#define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
998#define SQLITE_NOTADB      26   /* File opened that is not a database file */
999#define SQLITE_NOTICE      27   /* Notifications from sqlite3_log() */
1000#define SQLITE_WARNING     28   /* Warnings from sqlite3_log() */
1001#define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
1002#define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
1003/* end-of-error-codes */
1004
1005/*
1006** CAPI3REF: Extended Result Codes
1007** KEYWORDS: {extended error code} {extended error codes}
1008** KEYWORDS: {extended result code} {extended result codes}
1009**
1010** In its default configuration, SQLite API routines return one of 26 integer
1011** [SQLITE_OK | result codes].  However, experience has shown that many of
1012** these result codes are too coarse-grained.  They do not provide as
1013** much information about problems as programmers might like.  In an effort to
1014** address this, newer versions of SQLite (version 3.3.8 and later) include
1015** support for additional result codes that provide more detailed information
1016** about errors. The extended result codes are enabled or disabled
1017** on a per database connection basis using the
1018** [sqlite3_extended_result_codes()] API.
1019**
1020** Some of the available extended result codes are listed here.
1021** One may expect the number of extended result codes will be expand
1022** over time.  Software that uses extended result codes should expect
1023** to see new result codes in future releases of SQLite.
1024**
1025** The SQLITE_OK result code will never be extended.  It will always
1026** be exactly zero.
1027*/
1028#define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))
1029#define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))
1030#define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))
1031#define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))
1032#define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))
1033#define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))
1034#define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))
1035#define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))
1036#define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))
1037#define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))
1038#define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))
1039#define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))
1040#define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))
1041#define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
1042#define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
1043#define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))
1044#define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))
1045#define SQLITE_IOERR_SHMOPEN           (SQLITE_IOERR | (18<<8))
1046#define SQLITE_IOERR_SHMSIZE           (SQLITE_IOERR | (19<<8))
1047#define SQLITE_IOERR_SHMLOCK           (SQLITE_IOERR | (20<<8))
1048#define SQLITE_IOERR_SHMMAP            (SQLITE_IOERR | (21<<8))
1049#define SQLITE_IOERR_SEEK              (SQLITE_IOERR | (22<<8))
1050#define SQLITE_IOERR_DELETE_NOENT      (SQLITE_IOERR | (23<<8))
1051#define SQLITE_IOERR_MMAP              (SQLITE_IOERR | (24<<8))
1052#define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED |  (1<<8))
1053#define SQLITE_BUSY_RECOVERY           (SQLITE_BUSY   |  (1<<8))
1054#define SQLITE_CANTOPEN_NOTEMPDIR      (SQLITE_CANTOPEN | (1<<8))
1055#define SQLITE_CANTOPEN_ISDIR          (SQLITE_CANTOPEN | (2<<8))
1056#define SQLITE_CANTOPEN_FULLPATH       (SQLITE_CANTOPEN | (3<<8))
1057#define SQLITE_CORRUPT_VTAB            (SQLITE_CORRUPT | (1<<8))
1058#define SQLITE_READONLY_RECOVERY       (SQLITE_READONLY | (1<<8))
1059#define SQLITE_READONLY_CANTLOCK       (SQLITE_READONLY | (2<<8))
1060#define SQLITE_READONLY_ROLLBACK       (SQLITE_READONLY | (3<<8))
1061#define SQLITE_ABORT_ROLLBACK          (SQLITE_ABORT | (2<<8))
1062#define SQLITE_CONSTRAINT_CHECK        (SQLITE_CONSTRAINT | (1<<8))
1063#define SQLITE_CONSTRAINT_COMMITHOOK   (SQLITE_CONSTRAINT | (2<<8))
1064#define SQLITE_CONSTRAINT_FOREIGNKEY   (SQLITE_CONSTRAINT | (3<<8))
1065#define SQLITE_CONSTRAINT_FUNCTION     (SQLITE_CONSTRAINT | (4<<8))
1066#define SQLITE_CONSTRAINT_NOTNULL      (SQLITE_CONSTRAINT | (5<<8))
1067#define SQLITE_CONSTRAINT_PRIMARYKEY   (SQLITE_CONSTRAINT | (6<<8))
1068#define SQLITE_CONSTRAINT_TRIGGER      (SQLITE_CONSTRAINT | (7<<8))
1069#define SQLITE_CONSTRAINT_UNIQUE       (SQLITE_CONSTRAINT | (8<<8))
1070#define SQLITE_CONSTRAINT_VTAB         (SQLITE_CONSTRAINT | (9<<8))
1071#define SQLITE_NOTICE_RECOVER_WAL      (SQLITE_NOTICE | (1<<8))
1072#define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
1073
1074/*
1075** CAPI3REF: Flags For File Open Operations
1076**
1077** These bit values are intended for use in the
1078** 3rd parameter to the [sqlite3_open_v2()] interface and
1079** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
1080*/
1081#define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */
1082#define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */
1083#define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite3_open_v2() */
1084#define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */
1085#define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */
1086#define SQLITE_OPEN_AUTOPROXY        0x00000020  /* VFS only */
1087#define SQLITE_OPEN_URI              0x00000040  /* Ok for sqlite3_open_v2() */
1088#define SQLITE_OPEN_MEMORY           0x00000080  /* Ok for sqlite3_open_v2() */
1089#define SQLITE_OPEN_MAIN_DB          0x00000100  /* VFS only */
1090#define SQLITE_OPEN_TEMP_DB          0x00000200  /* VFS only */
1091#define SQLITE_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */
1092#define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */
1093#define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */
1094#define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */
1095#define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */
1096#define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */
1097#define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */
1098#define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */
1099#define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
1100#define SQLITE_OPEN_WAL              0x00080000  /* VFS only */
1101
1102/* Reserved:                         0x00F00000 */
1103
1104/*
1105** CAPI3REF: Device Characteristics
1106**
1107** The xDeviceCharacteristics method of the [sqlite3_io_methods]
1108** object returns an integer which is a vector of these
1109** bit values expressing I/O characteristics of the mass storage
1110** device that holds the file that the [sqlite3_io_methods]
1111** refers to.
1112**
1113** The SQLITE_IOCAP_ATOMIC property means that all writes of
1114** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1115** mean that writes of blocks that are nnn bytes in size and
1116** are aligned to an address which is an integer multiple of
1117** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1118** that when data is appended to a file, the data is appended
1119** first then the size of the file is extended, never the other
1120** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1121** information is written to disk in the same order as calls
1122** to xWrite().  The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
1123** after reboot following a crash or power loss, the only bytes in a
1124** file that were written at the application level might have changed
1125** and that adjacent bytes, even bytes within the same sector are
1126** guaranteed to be unchanged.
1127*/
1128#define SQLITE_IOCAP_ATOMIC                 0x00000001
1129#define SQLITE_IOCAP_ATOMIC512              0x00000002
1130#define SQLITE_IOCAP_ATOMIC1K               0x00000004
1131#define SQLITE_IOCAP_ATOMIC2K               0x00000008
1132#define SQLITE_IOCAP_ATOMIC4K               0x00000010
1133#define SQLITE_IOCAP_ATOMIC8K               0x00000020
1134#define SQLITE_IOCAP_ATOMIC16K              0x00000040
1135#define SQLITE_IOCAP_ATOMIC32K              0x00000080
1136#define SQLITE_IOCAP_ATOMIC64K              0x00000100
1137#define SQLITE_IOCAP_SAFE_APPEND            0x00000200
1138#define SQLITE_IOCAP_SEQUENTIAL             0x00000400
1139#define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN  0x00000800
1140#define SQLITE_IOCAP_POWERSAFE_OVERWRITE    0x00001000
1141
1142/*
1143** CAPI3REF: File Locking Levels
1144**
1145** SQLite uses one of these integer values as the second
1146** argument to calls it makes to the xLock() and xUnlock() methods
1147** of an [sqlite3_io_methods] object.
1148*/
1149#define SQLITE_LOCK_NONE          0
1150#define SQLITE_LOCK_SHARED        1
1151#define SQLITE_LOCK_RESERVED      2
1152#define SQLITE_LOCK_PENDING       3
1153#define SQLITE_LOCK_EXCLUSIVE     4
1154
1155/*
1156** CAPI3REF: Synchronization Type Flags
1157**
1158** When SQLite invokes the xSync() method of an
1159** [sqlite3_io_methods] object it uses a combination of
1160** these integer values as the second argument.
1161**
1162** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
1163** sync operation only needs to flush data to mass storage.  Inode
1164** information need not be flushed. If the lower four bits of the flag
1165** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
1166** If the lower four bits equal SQLITE_SYNC_FULL, that means
1167** to use Mac OS X style fullsync instead of fsync().
1168**
1169** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
1170** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
1171** settings.  The [synchronous pragma] determines when calls to the
1172** xSync VFS method occur and applies uniformly across all platforms.
1173** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
1174** energetic or rigorous or forceful the sync operations are and
1175** only make a difference on Mac OSX for the default SQLite code.
1176** (Third-party VFS implementations might also make the distinction
1177** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
1178** operating systems natively supported by SQLite, only Mac OSX
1179** cares about the difference.)
1180*/
1181#define SQLITE_SYNC_NORMAL        0x00002
1182#define SQLITE_SYNC_FULL          0x00003
1183#define SQLITE_SYNC_DATAONLY      0x00010
1184
1185/*
1186** CAPI3REF: OS Interface Open File Handle
1187**
1188** An [sqlite3_file] object represents an open file in the
1189** [sqlite3_vfs | OS interface layer].  Individual OS interface
1190** implementations will
1191** want to subclass this object by appending additional fields
1192** for their own use.  The pMethods entry is a pointer to an
1193** [sqlite3_io_methods] object that defines methods for performing
1194** I/O operations on the open file.
1195*/
1196typedef struct sqlite3_file sqlite3_file;
1197struct sqlite3_file {
1198  const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
1199};
1200
1201/*
1202** CAPI3REF: OS Interface File Virtual Methods Object
1203**
1204** Every file opened by the [sqlite3_vfs.xOpen] method populates an
1205** [sqlite3_file] object (or, more commonly, a subclass of the
1206** [sqlite3_file] object) with a pointer to an instance of this object.
1207** This object defines the methods used to perform various operations
1208** against the open file represented by the [sqlite3_file] object.
1209**
1210** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
1211** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
1212** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed.  The
1213** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
1214** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
1215** to NULL.
1216**
1217** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
1218** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
1219** The second choice is a Mac OS X style fullsync.  The [SQLITE_SYNC_DATAONLY]
1220** flag may be ORed in to indicate that only the data of the file
1221** and not its inode needs to be synced.
1222**
1223** The integer values to xLock() and xUnlock() are one of
1224** <ul>
1225** <li> [SQLITE_LOCK_NONE],
1226** <li> [SQLITE_LOCK_SHARED],
1227** <li> [SQLITE_LOCK_RESERVED],
1228** <li> [SQLITE_LOCK_PENDING], or
1229** <li> [SQLITE_LOCK_EXCLUSIVE].
1230** </ul>
1231** xLock() increases the lock. xUnlock() decreases the lock.
1232** The xCheckReservedLock() method checks whether any database connection,
1233** either in this process or in some other process, is holding a RESERVED,
1234** PENDING, or EXCLUSIVE lock on the file.  It returns true
1235** if such a lock exists and false otherwise.
1236**
1237** The xFileControl() method is a generic interface that allows custom
1238** VFS implementations to directly control an open file using the
1239** [sqlite3_file_control()] interface.  The second "op" argument is an
1240** integer opcode.  The third argument is a generic pointer intended to
1241** point to a structure that may contain arguments or space in which to
1242** write return values.  Potential uses for xFileControl() might be
1243** functions to enable blocking locks with timeouts, to change the
1244** locking strategy (for example to use dot-file locks), to inquire
1245** about the status of a lock, or to break stale locks.  The SQLite
1246** core reserves all opcodes less than 100 for its own use.
1247** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
1248** Applications that define a custom xFileControl method should use opcodes
1249** greater than 100 to avoid conflicts.  VFS implementations should
1250** return [SQLITE_NOTFOUND] for file control opcodes that they do not
1251** recognize.
1252**
1253** The xSectorSize() method returns the sector size of the
1254** device that underlies the file.  The sector size is the
1255** minimum write that can be performed without disturbing
1256** other bytes in the file.  The xDeviceCharacteristics()
1257** method returns a bit vector describing behaviors of the
1258** underlying device:
1259**
1260** <ul>
1261** <li> [SQLITE_IOCAP_ATOMIC]
1262** <li> [SQLITE_IOCAP_ATOMIC512]
1263** <li> [SQLITE_IOCAP_ATOMIC1K]
1264** <li> [SQLITE_IOCAP_ATOMIC2K]
1265** <li> [SQLITE_IOCAP_ATOMIC4K]
1266** <li> [SQLITE_IOCAP_ATOMIC8K]
1267** <li> [SQLITE_IOCAP_ATOMIC16K]
1268** <li> [SQLITE_IOCAP_ATOMIC32K]
1269** <li> [SQLITE_IOCAP_ATOMIC64K]
1270** <li> [SQLITE_IOCAP_SAFE_APPEND]
1271** <li> [SQLITE_IOCAP_SEQUENTIAL]
1272** </ul>
1273**
1274** The SQLITE_IOCAP_ATOMIC property means that all writes of
1275** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1276** mean that writes of blocks that are nnn bytes in size and
1277** are aligned to an address which is an integer multiple of
1278** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1279** that when data is appended to a file, the data is appended
1280** first then the size of the file is extended, never the other
1281** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1282** information is written to disk in the same order as calls
1283** to xWrite().
1284**
1285** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
1286** in the unread portions of the buffer with zeros.  A VFS that
1287** fails to zero-fill short reads might seem to work.  However,
1288** failure to zero-fill short reads will eventually lead to
1289** database corruption.
1290*/
1291typedef struct sqlite3_io_methods sqlite3_io_methods;
1292struct sqlite3_io_methods {
1293  int iVersion;
1294  int (*xClose)(sqlite3_file*);
1295  int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
1296  int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
1297  int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
1298  int (*xSync)(sqlite3_file*, int flags);
1299  int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
1300  int (*xLock)(sqlite3_file*, int);
1301  int (*xUnlock)(sqlite3_file*, int);
1302  int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
1303  int (*xFileControl)(sqlite3_file*, int op, void *pArg);
1304  int (*xSectorSize)(sqlite3_file*);
1305  int (*xDeviceCharacteristics)(sqlite3_file*);
1306  /* Methods above are valid for version 1 */
1307  int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
1308  int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
1309  void (*xShmBarrier)(sqlite3_file*);
1310  int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
1311  /* Methods above are valid for version 2 */
1312  int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
1313  int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
1314  /* Methods above are valid for version 3 */
1315  /* Additional methods may be added in future releases */
1316};
1317
1318/*
1319** CAPI3REF: Standard File Control Opcodes
1320**
1321** These integer constants are opcodes for the xFileControl method
1322** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
1323** interface.
1324**
1325** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
1326** opcode causes the xFileControl method to write the current state of
1327** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
1328** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
1329** into an integer that the pArg argument points to. This capability
1330** is used during testing and only needs to be supported when SQLITE_TEST
1331** is defined.
1332** <ul>
1333** <li>[[SQLITE_FCNTL_SIZE_HINT]]
1334** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
1335** layer a hint of how large the database file will grow to be during the
1336** current transaction.  This hint is not guaranteed to be accurate but it
1337** is often close.  The underlying VFS might choose to preallocate database
1338** file space based on this hint in order to help writes to the database
1339** file run faster.
1340**
1341** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
1342** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
1343** extends and truncates the database file in chunks of a size specified
1344** by the user. The fourth argument to [sqlite3_file_control()] should
1345** point to an integer (type int) containing the new chunk-size to use
1346** for the nominated database. Allocating database file space in large
1347** chunks (say 1MB at a time), may reduce file-system fragmentation and
1348** improve performance on some systems.
1349**
1350** <li>[[SQLITE_FCNTL_FILE_POINTER]]
1351** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
1352** to the [sqlite3_file] object associated with a particular database
1353** connection.  See the [sqlite3_file_control()] documentation for
1354** additional information.
1355**
1356** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
1357** ^(The [SQLITE_FCNTL_SYNC_OMITTED] opcode is generated internally by
1358** SQLite and sent to all VFSes in place of a call to the xSync method
1359** when the database connection has [PRAGMA synchronous] set to OFF.)^
1360** Some specialized VFSes need this signal in order to operate correctly
1361** when [PRAGMA synchronous | PRAGMA synchronous=OFF] is set, but most
1362** VFSes do not need this signal and should silently ignore this opcode.
1363** Applications should not call [sqlite3_file_control()] with this
1364** opcode as doing so may disrupt the operation of the specialized VFSes
1365** that do require it.
1366**
1367** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
1368** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
1369** retry counts and intervals for certain disk I/O operations for the
1370** windows [VFS] in order to provide robustness in the presence of
1371** anti-virus programs.  By default, the windows VFS will retry file read,
1372** file write, and file delete operations up to 10 times, with a delay
1373** of 25 milliseconds before the first retry and with the delay increasing
1374** by an additional 25 milliseconds with each subsequent retry.  This
1375** opcode allows these two values (10 retries and 25 milliseconds of delay)
1376** to be adjusted.  The values are changed for all database connections
1377** within the same process.  The argument is a pointer to an array of two
1378** integers where the first integer i the new retry count and the second
1379** integer is the delay.  If either integer is negative, then the setting
1380** is not changed but instead the prior value of that setting is written
1381** into the array entry, allowing the current retry settings to be
1382** interrogated.  The zDbName parameter is ignored.
1383**
1384** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
1385** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
1386** persistent [WAL | Write Ahead Log] setting.  By default, the auxiliary
1387** write ahead log and shared memory files used for transaction control
1388** are automatically deleted when the latest connection to the database
1389** closes.  Setting persistent WAL mode causes those files to persist after
1390** close.  Persisting the files is useful when other processes that do not
1391** have write permission on the directory containing the database file want
1392** to read the database file, as the WAL and shared memory files must exist
1393** in order for the database to be readable.  The fourth parameter to
1394** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1395** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
1396** WAL mode.  If the integer is -1, then it is overwritten with the current
1397** WAL persistence setting.
1398**
1399** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
1400** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
1401** persistent "powersafe-overwrite" or "PSOW" setting.  The PSOW setting
1402** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
1403** xDeviceCharacteristics methods. The fourth parameter to
1404** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1405** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
1406** mode.  If the integer is -1, then it is overwritten with the current
1407** zero-damage mode setting.
1408**
1409** <li>[[SQLITE_FCNTL_OVERWRITE]]
1410** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
1411** a write transaction to indicate that, unless it is rolled back for some
1412** reason, the entire database file will be overwritten by the current
1413** transaction. This is used by VACUUM operations.
1414**
1415** <li>[[SQLITE_FCNTL_VFSNAME]]
1416** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
1417** all [VFSes] in the VFS stack.  The names are of all VFS shims and the
1418** final bottom-level VFS are written into memory obtained from
1419** [sqlite3_malloc()] and the result is stored in the char* variable
1420** that the fourth parameter of [sqlite3_file_control()] points to.
1421** The caller is responsible for freeing the memory when done.  As with
1422** all file-control actions, there is no guarantee that this will actually
1423** do anything.  Callers should initialize the char* variable to a NULL
1424** pointer in case this file-control is not implemented.  This file-control
1425** is intended for diagnostic use only.
1426**
1427** <li>[[SQLITE_FCNTL_PRAGMA]]
1428** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
1429** file control is sent to the open [sqlite3_file] object corresponding
1430** to the database file to which the pragma statement refers. ^The argument
1431** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
1432** pointers to strings (char**) in which the second element of the array
1433** is the name of the pragma and the third element is the argument to the
1434** pragma or NULL if the pragma has no argument.  ^The handler for an
1435** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
1436** of the char** argument point to a string obtained from [sqlite3_mprintf()]
1437** or the equivalent and that string will become the result of the pragma or
1438** the error message if the pragma fails. ^If the
1439** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
1440** [PRAGMA] processing continues.  ^If the [SQLITE_FCNTL_PRAGMA]
1441** file control returns [SQLITE_OK], then the parser assumes that the
1442** VFS has handled the PRAGMA itself and the parser generates a no-op
1443** prepared statement.  ^If the [SQLITE_FCNTL_PRAGMA] file control returns
1444** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
1445** that the VFS encountered an error while handling the [PRAGMA] and the
1446** compilation of the PRAGMA fails with an error.  ^The [SQLITE_FCNTL_PRAGMA]
1447** file control occurs at the beginning of pragma statement analysis and so
1448** it is able to override built-in [PRAGMA] statements.
1449**
1450** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
1451** ^The [SQLITE_FCNTL_BUSYHANDLER]
1452** file-control may be invoked by SQLite on the database file handle
1453** shortly after it is opened in order to provide a custom VFS with access
1454** to the connections busy-handler callback. The argument is of type (void **)
1455** - an array of two (void *) values. The first (void *) actually points
1456** to a function of type (int (*)(void *)). In order to invoke the connections
1457** busy-handler, this function should be invoked with the second (void *) in
1458** the array as the only argument. If it returns non-zero, then the operation
1459** should be retried. If it returns zero, the custom VFS should abandon the
1460** current operation.
1461**
1462** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
1463** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
1464** to have SQLite generate a
1465** temporary filename using the same algorithm that is followed to generate
1466** temporary filenames for TEMP tables and other internal uses.  The
1467** argument should be a char** which will be filled with the filename
1468** written into memory obtained from [sqlite3_malloc()].  The caller should
1469** invoke [sqlite3_free()] on the result to avoid a memory leak.
1470**
1471** <li>[[SQLITE_FCNTL_MMAP_SIZE]]
1472** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
1473** maximum number of bytes that will be used for memory-mapped I/O.
1474** The argument is a pointer to a value of type sqlite3_int64 that
1475** is an advisory maximum number of bytes in the file to memory map.  The
1476** pointer is overwritten with the old value.  The limit is not changed if
1477** the value originally pointed to is negative, and so the current limit
1478** can be queried by passing in a pointer to a negative number.  This
1479** file-control is used internally to implement [PRAGMA mmap_size].
1480**
1481** </ul>
1482*/
1483#define SQLITE_FCNTL_LOCKSTATE               1
1484#define SQLITE_GET_LOCKPROXYFILE             2
1485#define SQLITE_SET_LOCKPROXYFILE             3
1486#define SQLITE_LAST_ERRNO                    4
1487#define SQLITE_FCNTL_SIZE_HINT               5
1488#define SQLITE_FCNTL_CHUNK_SIZE              6
1489#define SQLITE_FCNTL_FILE_POINTER            7
1490#define SQLITE_FCNTL_SYNC_OMITTED            8
1491#define SQLITE_FCNTL_WIN32_AV_RETRY          9
1492#define SQLITE_FCNTL_PERSIST_WAL            10
1493#define SQLITE_FCNTL_OVERWRITE              11
1494#define SQLITE_FCNTL_VFSNAME                12
1495#define SQLITE_FCNTL_POWERSAFE_OVERWRITE    13
1496#define SQLITE_FCNTL_PRAGMA                 14
1497#define SQLITE_FCNTL_BUSYHANDLER            15
1498#define SQLITE_FCNTL_TEMPFILENAME           16
1499#define SQLITE_FCNTL_MMAP_SIZE              18
1500
1501/*
1502** CAPI3REF: Mutex Handle
1503**
1504** The mutex module within SQLite defines [sqlite3_mutex] to be an
1505** abstract type for a mutex object.  The SQLite core never looks
1506** at the internal representation of an [sqlite3_mutex].  It only
1507** deals with pointers to the [sqlite3_mutex] object.
1508**
1509** Mutexes are created using [sqlite3_mutex_alloc()].
1510*/
1511typedef struct sqlite3_mutex sqlite3_mutex;
1512
1513/*
1514** CAPI3REF: OS Interface Object
1515**
1516** An instance of the sqlite3_vfs object defines the interface between
1517** the SQLite core and the underlying operating system.  The "vfs"
1518** in the name of the object stands for "virtual file system".  See
1519** the [VFS | VFS documentation] for further information.
1520**
1521** The value of the iVersion field is initially 1 but may be larger in
1522** future versions of SQLite.  Additional fields may be appended to this
1523** object when the iVersion value is increased.  Note that the structure
1524** of the sqlite3_vfs object changes in the transaction between
1525** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
1526** modified.
1527**
1528** The szOsFile field is the size of the subclassed [sqlite3_file]
1529** structure used by this VFS.  mxPathname is the maximum length of
1530** a pathname in this VFS.
1531**
1532** Registered sqlite3_vfs objects are kept on a linked list formed by
1533** the pNext pointer.  The [sqlite3_vfs_register()]
1534** and [sqlite3_vfs_unregister()] interfaces manage this list
1535** in a thread-safe way.  The [sqlite3_vfs_find()] interface
1536** searches the list.  Neither the application code nor the VFS
1537** implementation should use the pNext pointer.
1538**
1539** The pNext field is the only field in the sqlite3_vfs
1540** structure that SQLite will ever modify.  SQLite will only access
1541** or modify this field while holding a particular static mutex.
1542** The application should never modify anything within the sqlite3_vfs
1543** object once the object has been registered.
1544**
1545** The zName field holds the name of the VFS module.  The name must
1546** be unique across all VFS modules.
1547**
1548** [[sqlite3_vfs.xOpen]]
1549** ^SQLite guarantees that the zFilename parameter to xOpen
1550** is either a NULL pointer or string obtained
1551** from xFullPathname() with an optional suffix added.
1552** ^If a suffix is added to the zFilename parameter, it will
1553** consist of a single "-" character followed by no more than
1554** 11 alphanumeric and/or "-" characters.
1555** ^SQLite further guarantees that
1556** the string will be valid and unchanged until xClose() is
1557** called. Because of the previous sentence,
1558** the [sqlite3_file] can safely store a pointer to the
1559** filename if it needs to remember the filename for some reason.
1560** If the zFilename parameter to xOpen is a NULL pointer then xOpen
1561** must invent its own temporary name for the file.  ^Whenever the
1562** xFilename parameter is NULL it will also be the case that the
1563** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
1564**
1565** The flags argument to xOpen() includes all bits set in
1566** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
1567** or [sqlite3_open16()] is used, then flags includes at least
1568** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
1569** If xOpen() opens a file read-only then it sets *pOutFlags to
1570** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
1571**
1572** ^(SQLite will also add one of the following flags to the xOpen()
1573** call, depending on the object being opened:
1574**
1575** <ul>
1576** <li>  [SQLITE_OPEN_MAIN_DB]
1577** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
1578** <li>  [SQLITE_OPEN_TEMP_DB]
1579** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
1580** <li>  [SQLITE_OPEN_TRANSIENT_DB]
1581** <li>  [SQLITE_OPEN_SUBJOURNAL]
1582** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
1583** <li>  [SQLITE_OPEN_WAL]
1584** </ul>)^
1585**
1586** The file I/O implementation can use the object type flags to
1587** change the way it deals with files.  For example, an application
1588** that does not care about crash recovery or rollback might make
1589** the open of a journal file a no-op.  Writes to this journal would
1590** also be no-ops, and any attempt to read the journal would return
1591** SQLITE_IOERR.  Or the implementation might recognize that a database
1592** file will be doing page-aligned sector reads and writes in a random
1593** order and set up its I/O subsystem accordingly.
1594**
1595** SQLite might also add one of the following flags to the xOpen method:
1596**
1597** <ul>
1598** <li> [SQLITE_OPEN_DELETEONCLOSE]
1599** <li> [SQLITE_OPEN_EXCLUSIVE]
1600** </ul>
1601**
1602** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1603** deleted when it is closed.  ^The [SQLITE_OPEN_DELETEONCLOSE]
1604** will be set for TEMP databases and their journals, transient
1605** databases, and subjournals.
1606**
1607** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
1608** with the [SQLITE_OPEN_CREATE] flag, which are both directly
1609** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
1610** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
1611** SQLITE_OPEN_CREATE, is used to indicate that file should always
1612** be created, and that it is an error if it already exists.
1613** It is <i>not</i> used to indicate the file should be opened
1614** for exclusive access.
1615**
1616** ^At least szOsFile bytes of memory are allocated by SQLite
1617** to hold the  [sqlite3_file] structure passed as the third
1618** argument to xOpen.  The xOpen method does not have to
1619** allocate the structure; it should just fill it in.  Note that
1620** the xOpen method must set the sqlite3_file.pMethods to either
1621** a valid [sqlite3_io_methods] object or to NULL.  xOpen must do
1622** this even if the open fails.  SQLite expects that the sqlite3_file.pMethods
1623** element will be valid after xOpen returns regardless of the success
1624** or failure of the xOpen call.
1625**
1626** [[sqlite3_vfs.xAccess]]
1627** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
1628** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
1629** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
1630** to test whether a file is at least readable.   The file can be a
1631** directory.
1632**
1633** ^SQLite will always allocate at least mxPathname+1 bytes for the
1634** output buffer xFullPathname.  The exact size of the output buffer
1635** is also passed as a parameter to both  methods. If the output buffer
1636** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
1637** handled as a fatal error by SQLite, vfs implementations should endeavor
1638** to prevent this by setting mxPathname to a sufficiently large value.
1639**
1640** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
1641** interfaces are not strictly a part of the filesystem, but they are
1642** included in the VFS structure for completeness.
1643** The xRandomness() function attempts to return nBytes bytes
1644** of good-quality randomness into zOut.  The return value is
1645** the actual number of bytes of randomness obtained.
1646** The xSleep() method causes the calling thread to sleep for at
1647** least the number of microseconds given.  ^The xCurrentTime()
1648** method returns a Julian Day Number for the current date and time as
1649** a floating point value.
1650** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
1651** Day Number multiplied by 86400000 (the number of milliseconds in
1652** a 24-hour day).
1653** ^SQLite will use the xCurrentTimeInt64() method to get the current
1654** date and time if that method is available (if iVersion is 2 or
1655** greater and the function pointer is not NULL) and will fall back
1656** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
1657**
1658** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
1659** are not used by the SQLite core.  These optional interfaces are provided
1660** by some VFSes to facilitate testing of the VFS code. By overriding
1661** system calls with functions under its control, a test program can
1662** simulate faults and error conditions that would otherwise be difficult
1663** or impossible to induce.  The set of system calls that can be overridden
1664** varies from one VFS to another, and from one version of the same VFS to the
1665** next.  Applications that use these interfaces must be prepared for any
1666** or all of these interfaces to be NULL or for their behavior to change
1667** from one release to the next.  Applications must not attempt to access
1668** any of these methods if the iVersion of the VFS is less than 3.
1669*/
1670typedef struct sqlite3_vfs sqlite3_vfs;
1671typedef void (*sqlite3_syscall_ptr)(void);
1672struct sqlite3_vfs {
1673  int iVersion;            /* Structure version number (currently 3) */
1674  int szOsFile;            /* Size of subclassed sqlite3_file */
1675  int mxPathname;          /* Maximum file pathname length */
1676  sqlite3_vfs *pNext;      /* Next registered VFS */
1677  const char *zName;       /* Name of this virtual file system */
1678  void *pAppData;          /* Pointer to application-specific data */
1679  int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
1680               int flags, int *pOutFlags);
1681  int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
1682  int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
1683  int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
1684  void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
1685  void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
1686  void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
1687  void (*xDlClose)(sqlite3_vfs*, void*);
1688  int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
1689  int (*xSleep)(sqlite3_vfs*, int microseconds);
1690  int (*xCurrentTime)(sqlite3_vfs*, double*);
1691  int (*xGetLastError)(sqlite3_vfs*, int, char *);
1692  /*
1693  ** The methods above are in version 1 of the sqlite_vfs object
1694  ** definition.  Those that follow are added in version 2 or later
1695  */
1696  int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
1697  /*
1698  ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
1699  ** Those below are for version 3 and greater.
1700  */
1701  int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
1702  sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
1703  const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
1704  /*
1705  ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
1706  ** New fields may be appended in figure versions.  The iVersion
1707  ** value will increment whenever this happens.
1708  */
1709};
1710
1711/*
1712** CAPI3REF: Flags for the xAccess VFS method
1713**
1714** These integer constants can be used as the third parameter to
1715** the xAccess method of an [sqlite3_vfs] object.  They determine
1716** what kind of permissions the xAccess method is looking for.
1717** With SQLITE_ACCESS_EXISTS, the xAccess method
1718** simply checks whether the file exists.
1719** With SQLITE_ACCESS_READWRITE, the xAccess method
1720** checks whether the named directory is both readable and writable
1721** (in other words, if files can be added, removed, and renamed within
1722** the directory).
1723** The SQLITE_ACCESS_READWRITE constant is currently used only by the
1724** [temp_store_directory pragma], though this could change in a future
1725** release of SQLite.
1726** With SQLITE_ACCESS_READ, the xAccess method
1727** checks whether the file is readable.  The SQLITE_ACCESS_READ constant is
1728** currently unused, though it might be used in a future release of
1729** SQLite.
1730*/
1731#define SQLITE_ACCESS_EXISTS    0
1732#define SQLITE_ACCESS_READWRITE 1   /* Used by PRAGMA temp_store_directory */
1733#define SQLITE_ACCESS_READ      2   /* Unused */
1734
1735/*
1736** CAPI3REF: Flags for the xShmLock VFS method
1737**
1738** These integer constants define the various locking operations
1739** allowed by the xShmLock method of [sqlite3_io_methods].  The
1740** following are the only legal combinations of flags to the
1741** xShmLock method:
1742**
1743** <ul>
1744** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
1745** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
1746** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
1747** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
1748** </ul>
1749**
1750** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
1751** was given no the corresponding lock.
1752**
1753** The xShmLock method can transition between unlocked and SHARED or
1754** between unlocked and EXCLUSIVE.  It cannot transition between SHARED
1755** and EXCLUSIVE.
1756*/
1757#define SQLITE_SHM_UNLOCK       1
1758#define SQLITE_SHM_LOCK         2
1759#define SQLITE_SHM_SHARED       4
1760#define SQLITE_SHM_EXCLUSIVE    8
1761
1762/*
1763** CAPI3REF: Maximum xShmLock index
1764**
1765** The xShmLock method on [sqlite3_io_methods] may use values
1766** between 0 and this upper bound as its "offset" argument.
1767** The SQLite core will never attempt to acquire or release a
1768** lock outside of this range
1769*/
1770#define SQLITE_SHM_NLOCK        8
1771
1772
1773/*
1774** CAPI3REF: Initialize The SQLite Library
1775**
1776** ^The sqlite3_initialize() routine initializes the
1777** SQLite library.  ^The sqlite3_shutdown() routine
1778** deallocates any resources that were allocated by sqlite3_initialize().
1779** These routines are designed to aid in process initialization and
1780** shutdown on embedded systems.  Workstation applications using
1781** SQLite normally do not need to invoke either of these routines.
1782**
1783** A call to sqlite3_initialize() is an "effective" call if it is
1784** the first time sqlite3_initialize() is invoked during the lifetime of
1785** the process, or if it is the first time sqlite3_initialize() is invoked
1786** following a call to sqlite3_shutdown().  ^(Only an effective call
1787** of sqlite3_initialize() does any initialization.  All other calls
1788** are harmless no-ops.)^
1789**
1790** A call to sqlite3_shutdown() is an "effective" call if it is the first
1791** call to sqlite3_shutdown() since the last sqlite3_initialize().  ^(Only
1792** an effective call to sqlite3_shutdown() does any deinitialization.
1793** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
1794**
1795** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
1796** is not.  The sqlite3_shutdown() interface must only be called from a
1797** single thread.  All open [database connections] must be closed and all
1798** other SQLite resources must be deallocated prior to invoking
1799** sqlite3_shutdown().
1800**
1801** Among other things, ^sqlite3_initialize() will invoke
1802** sqlite3_os_init().  Similarly, ^sqlite3_shutdown()
1803** will invoke sqlite3_os_end().
1804**
1805** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
1806** ^If for some reason, sqlite3_initialize() is unable to initialize
1807** the library (perhaps it is unable to allocate a needed resource such
1808** as a mutex) it returns an [error code] other than [SQLITE_OK].
1809**
1810** ^The sqlite3_initialize() routine is called internally by many other
1811** SQLite interfaces so that an application usually does not need to
1812** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]
1813** calls sqlite3_initialize() so the SQLite library will be automatically
1814** initialized when [sqlite3_open()] is called if it has not be initialized
1815** already.  ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
1816** compile-time option, then the automatic calls to sqlite3_initialize()
1817** are omitted and the application must call sqlite3_initialize() directly
1818** prior to using any other SQLite interface.  For maximum portability,
1819** it is recommended that applications always invoke sqlite3_initialize()
1820** directly prior to using any other SQLite interface.  Future releases
1821** of SQLite may require this.  In other words, the behavior exhibited
1822** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
1823** default behavior in some future release of SQLite.
1824**
1825** The sqlite3_os_init() routine does operating-system specific
1826** initialization of the SQLite library.  The sqlite3_os_end()
1827** routine undoes the effect of sqlite3_os_init().  Typical tasks
1828** performed by these routines include allocation or deallocation
1829** of static resources, initialization of global variables,
1830** setting up a default [sqlite3_vfs] module, or setting up
1831** a default configuration using [sqlite3_config()].
1832**
1833** The application should never invoke either sqlite3_os_init()
1834** or sqlite3_os_end() directly.  The application should only invoke
1835** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()
1836** interface is called automatically by sqlite3_initialize() and
1837** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate
1838** implementations for sqlite3_os_init() and sqlite3_os_end()
1839** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
1840** When [custom builds | built for other platforms]
1841** (using the [SQLITE_OS_OTHER=1] compile-time
1842** option) the application must supply a suitable implementation for
1843** sqlite3_os_init() and sqlite3_os_end().  An application-supplied
1844** implementation of sqlite3_os_init() or sqlite3_os_end()
1845** must return [SQLITE_OK] on success and some other [error code] upon
1846** failure.
1847*/
1848SQLITE_API int sqlite3_initialize(void);
1849SQLITE_API int sqlite3_shutdown(void);
1850SQLITE_API int sqlite3_os_init(void);
1851SQLITE_API int sqlite3_os_end(void);
1852
1853/*
1854** CAPI3REF: Configuring The SQLite Library
1855**
1856** The sqlite3_config() interface is used to make global configuration
1857** changes to SQLite in order to tune SQLite to the specific needs of
1858** the application.  The default configuration is recommended for most
1859** applications and so this routine is usually not necessary.  It is
1860** provided to support rare applications with unusual needs.
1861**
1862** The sqlite3_config() interface is not threadsafe.  The application
1863** must insure that no other SQLite interfaces are invoked by other
1864** threads while sqlite3_config() is running.  Furthermore, sqlite3_config()
1865** may only be invoked prior to library initialization using
1866** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
1867** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
1868** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
1869** Note, however, that ^sqlite3_config() can be called as part of the
1870** implementation of an application-defined [sqlite3_os_init()].
1871**
1872** The first argument to sqlite3_config() is an integer
1873** [configuration option] that determines
1874** what property of SQLite is to be configured.  Subsequent arguments
1875** vary depending on the [configuration option]
1876** in the first argument.
1877**
1878** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
1879** ^If the option is unknown or SQLite is unable to set the option
1880** then this routine returns a non-zero [error code].
1881*/
1882SQLITE_API int sqlite3_config(int, ...);
1883
1884/*
1885** CAPI3REF: Configure database connections
1886**
1887** The sqlite3_db_config() interface is used to make configuration
1888** changes to a [database connection].  The interface is similar to
1889** [sqlite3_config()] except that the changes apply to a single
1890** [database connection] (specified in the first argument).
1891**
1892** The second argument to sqlite3_db_config(D,V,...)  is the
1893** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
1894** that indicates what aspect of the [database connection] is being configured.
1895** Subsequent arguments vary depending on the configuration verb.
1896**
1897** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
1898** the call is considered successful.
1899*/
1900SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
1901
1902/*
1903** CAPI3REF: Memory Allocation Routines
1904**
1905** An instance of this object defines the interface between SQLite
1906** and low-level memory allocation routines.
1907**
1908** This object is used in only one place in the SQLite interface.
1909** A pointer to an instance of this object is the argument to
1910** [sqlite3_config()] when the configuration option is
1911** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
1912** By creating an instance of this object
1913** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
1914** during configuration, an application can specify an alternative
1915** memory allocation subsystem for SQLite to use for all of its
1916** dynamic memory needs.
1917**
1918** Note that SQLite comes with several [built-in memory allocators]
1919** that are perfectly adequate for the overwhelming majority of applications
1920** and that this object is only useful to a tiny minority of applications
1921** with specialized memory allocation requirements.  This object is
1922** also used during testing of SQLite in order to specify an alternative
1923** memory allocator that simulates memory out-of-memory conditions in
1924** order to verify that SQLite recovers gracefully from such
1925** conditions.
1926**
1927** The xMalloc, xRealloc, and xFree methods must work like the
1928** malloc(), realloc() and free() functions from the standard C library.
1929** ^SQLite guarantees that the second argument to
1930** xRealloc is always a value returned by a prior call to xRoundup.
1931**
1932** xSize should return the allocated size of a memory allocation
1933** previously obtained from xMalloc or xRealloc.  The allocated size
1934** is always at least as big as the requested size but may be larger.
1935**
1936** The xRoundup method returns what would be the allocated size of
1937** a memory allocation given a particular requested size.  Most memory
1938** allocators round up memory allocations at least to the next multiple
1939** of 8.  Some allocators round up to a larger multiple or to a power of 2.
1940** Every memory allocation request coming in through [sqlite3_malloc()]
1941** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0,
1942** that causes the corresponding memory allocation to fail.
1943**
1944** The xInit method initializes the memory allocator.  (For example,
1945** it might allocate any require mutexes or initialize internal data
1946** structures.  The xShutdown method is invoked (indirectly) by
1947** [sqlite3_shutdown()] and should deallocate any resources acquired
1948** by xInit.  The pAppData pointer is used as the only parameter to
1949** xInit and xShutdown.
1950**
1951** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
1952** the xInit method, so the xInit method need not be threadsafe.  The
1953** xShutdown method is only called from [sqlite3_shutdown()] so it does
1954** not need to be threadsafe either.  For all other methods, SQLite
1955** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
1956** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
1957** it is by default) and so the methods are automatically serialized.
1958** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
1959** methods must be threadsafe or else make their own arrangements for
1960** serialization.
1961**
1962** SQLite will never invoke xInit() more than once without an intervening
1963** call to xShutdown().
1964*/
1965typedef struct sqlite3_mem_methods sqlite3_mem_methods;
1966struct sqlite3_mem_methods {
1967  void *(*xMalloc)(int);         /* Memory allocation function */
1968  void (*xFree)(void*);          /* Free a prior allocation */
1969  void *(*xRealloc)(void*,int);  /* Resize an allocation */
1970  int (*xSize)(void*);           /* Return the size of an allocation */
1971  int (*xRoundup)(int);          /* Round up request size to allocation size */
1972  int (*xInit)(void*);           /* Initialize the memory allocator */
1973  void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
1974  void *pAppData;                /* Argument to xInit() and xShutdown() */
1975};
1976
1977/*
1978** CAPI3REF: Configuration Options
1979** KEYWORDS: {configuration option}
1980**
1981** These constants are the available integer configuration options that
1982** can be passed as the first argument to the [sqlite3_config()] interface.
1983**
1984** New configuration options may be added in future releases of SQLite.
1985** Existing configuration options might be discontinued.  Applications
1986** should check the return code from [sqlite3_config()] to make sure that
1987** the call worked.  The [sqlite3_config()] interface will return a
1988** non-zero [error code] if a discontinued or unsupported configuration option
1989** is invoked.
1990**
1991** <dl>
1992** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
1993** <dd>There are no arguments to this option.  ^This option sets the
1994** [threading mode] to Single-thread.  In other words, it disables
1995** all mutexing and puts SQLite into a mode where it can only be used
1996** by a single thread.   ^If SQLite is compiled with
1997** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1998** it is not possible to change the [threading mode] from its default
1999** value of Single-thread and so [sqlite3_config()] will return
2000** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
2001** configuration option.</dd>
2002**
2003** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
2004** <dd>There are no arguments to this option.  ^This option sets the
2005** [threading mode] to Multi-thread.  In other words, it disables
2006** mutexing on [database connection] and [prepared statement] objects.
2007** The application is responsible for serializing access to
2008** [database connections] and [prepared statements].  But other mutexes
2009** are enabled so that SQLite will be safe to use in a multi-threaded
2010** environment as long as no two threads attempt to use the same
2011** [database connection] at the same time.  ^If SQLite is compiled with
2012** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2013** it is not possible to set the Multi-thread [threading mode] and
2014** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
2015** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
2016**
2017** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
2018** <dd>There are no arguments to this option.  ^This option sets the
2019** [threading mode] to Serialized. In other words, this option enables
2020** all mutexes including the recursive
2021** mutexes on [database connection] and [prepared statement] objects.
2022** In this mode (which is the default when SQLite is compiled with
2023** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
2024** to [database connections] and [prepared statements] so that the
2025** application is free to use the same [database connection] or the
2026** same [prepared statement] in different threads at the same time.
2027** ^If SQLite is compiled with
2028** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2029** it is not possible to set the Serialized [threading mode] and
2030** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
2031** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
2032**
2033** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
2034** <dd> ^(This option takes a single argument which is a pointer to an
2035** instance of the [sqlite3_mem_methods] structure.  The argument specifies
2036** alternative low-level memory allocation routines to be used in place of
2037** the memory allocation routines built into SQLite.)^ ^SQLite makes
2038** its own private copy of the content of the [sqlite3_mem_methods] structure
2039** before the [sqlite3_config()] call returns.</dd>
2040**
2041** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
2042** <dd> ^(This option takes a single argument which is a pointer to an
2043** instance of the [sqlite3_mem_methods] structure.  The [sqlite3_mem_methods]
2044** structure is filled with the currently defined memory allocation routines.)^
2045** This option can be used to overload the default memory allocation
2046** routines with a wrapper that simulations memory allocation failure or
2047** tracks memory usage, for example. </dd>
2048**
2049** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
2050** <dd> ^This option takes single argument of type int, interpreted as a
2051** boolean, which enables or disables the collection of memory allocation
2052** statistics. ^(When memory allocation statistics are disabled, the
2053** following SQLite interfaces become non-operational:
2054**   <ul>
2055**   <li> [sqlite3_memory_used()]
2056**   <li> [sqlite3_memory_highwater()]
2057**   <li> [sqlite3_soft_heap_limit64()]
2058**   <li> [sqlite3_status()]
2059**   </ul>)^
2060** ^Memory allocation statistics are enabled by default unless SQLite is
2061** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
2062** allocation statistics are disabled by default.
2063** </dd>
2064**
2065** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
2066** <dd> ^This option specifies a static memory buffer that SQLite can use for
2067** scratch memory.  There are three arguments:  A pointer an 8-byte
2068** aligned memory buffer from which the scratch allocations will be
2069** drawn, the size of each scratch allocation (sz),
2070** and the maximum number of scratch allocations (N).  The sz
2071** argument must be a multiple of 16.
2072** The first argument must be a pointer to an 8-byte aligned buffer
2073** of at least sz*N bytes of memory.
2074** ^SQLite will use no more than two scratch buffers per thread.  So
2075** N should be set to twice the expected maximum number of threads.
2076** ^SQLite will never require a scratch buffer that is more than 6
2077** times the database page size. ^If SQLite needs needs additional
2078** scratch memory beyond what is provided by this configuration option, then
2079** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
2080**
2081** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
2082** <dd> ^This option specifies a static memory buffer that SQLite can use for
2083** the database page cache with the default page cache implementation.
2084** This configuration should not be used if an application-define page
2085** cache implementation is loaded using the SQLITE_CONFIG_PCACHE2 option.
2086** There are three arguments to this option: A pointer to 8-byte aligned
2087** memory, the size of each page buffer (sz), and the number of pages (N).
2088** The sz argument should be the size of the largest database page
2089** (a power of two between 512 and 32768) plus a little extra for each
2090** page header.  ^The page header size is 20 to 40 bytes depending on
2091** the host architecture.  ^It is harmless, apart from the wasted memory,
2092** to make sz a little too large.  The first
2093** argument should point to an allocation of at least sz*N bytes of memory.
2094** ^SQLite will use the memory provided by the first argument to satisfy its
2095** memory needs for the first N pages that it adds to cache.  ^If additional
2096** page cache memory is needed beyond what is provided by this option, then
2097** SQLite goes to [sqlite3_malloc()] for the additional storage space.
2098** The pointer in the first argument must
2099** be aligned to an 8-byte boundary or subsequent behavior of SQLite
2100** will be undefined.</dd>
2101**
2102** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
2103** <dd> ^This option specifies a static memory buffer that SQLite will use
2104** for all of its dynamic memory allocation needs beyond those provided
2105** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
2106** There are three arguments: An 8-byte aligned pointer to the memory,
2107** the number of bytes in the memory buffer, and the minimum allocation size.
2108** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
2109** to using its default memory allocator (the system malloc() implementation),
2110** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  ^If the
2111** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
2112** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
2113** allocator is engaged to handle all of SQLites memory allocation needs.
2114** The first pointer (the memory pointer) must be aligned to an 8-byte
2115** boundary or subsequent behavior of SQLite will be undefined.
2116** The minimum allocation size is capped at 2**12. Reasonable values
2117** for the minimum allocation size are 2**5 through 2**8.</dd>
2118**
2119** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
2120** <dd> ^(This option takes a single argument which is a pointer to an
2121** instance of the [sqlite3_mutex_methods] structure.  The argument specifies
2122** alternative low-level mutex routines to be used in place
2123** the mutex routines built into SQLite.)^  ^SQLite makes a copy of the
2124** content of the [sqlite3_mutex_methods] structure before the call to
2125** [sqlite3_config()] returns. ^If SQLite is compiled with
2126** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2127** the entire mutexing subsystem is omitted from the build and hence calls to
2128** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
2129** return [SQLITE_ERROR].</dd>
2130**
2131** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
2132** <dd> ^(This option takes a single argument which is a pointer to an
2133** instance of the [sqlite3_mutex_methods] structure.  The
2134** [sqlite3_mutex_methods]
2135** structure is filled with the currently defined mutex routines.)^
2136** This option can be used to overload the default mutex allocation
2137** routines with a wrapper used to track mutex usage for performance
2138** profiling or testing, for example.   ^If SQLite is compiled with
2139** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2140** the entire mutexing subsystem is omitted from the build and hence calls to
2141** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
2142** return [SQLITE_ERROR].</dd>
2143**
2144** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
2145** <dd> ^(This option takes two arguments that determine the default
2146** memory allocation for the lookaside memory allocator on each
2147** [database connection].  The first argument is the
2148** size of each lookaside buffer slot and the second is the number of
2149** slots allocated to each database connection.)^  ^(This option sets the
2150** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
2151** verb to [sqlite3_db_config()] can be used to change the lookaside
2152** configuration on individual connections.)^ </dd>
2153**
2154** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
2155** <dd> ^(This option takes a single argument which is a pointer to
2156** an [sqlite3_pcache_methods2] object.  This object specifies the interface
2157** to a custom page cache implementation.)^  ^SQLite makes a copy of the
2158** object and uses it for page cache memory allocations.</dd>
2159**
2160** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
2161** <dd> ^(This option takes a single argument which is a pointer to an
2162** [sqlite3_pcache_methods2] object.  SQLite copies of the current
2163** page cache implementation into that object.)^ </dd>
2164**
2165** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
2166** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
2167** global [error log].
2168** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
2169** function with a call signature of void(*)(void*,int,const char*),
2170** and a pointer to void. ^If the function pointer is not NULL, it is
2171** invoked by [sqlite3_log()] to process each logging event.  ^If the
2172** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
2173** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
2174** passed through as the first parameter to the application-defined logger
2175** function whenever that function is invoked.  ^The second parameter to
2176** the logger function is a copy of the first parameter to the corresponding
2177** [sqlite3_log()] call and is intended to be a [result code] or an
2178** [extended result code].  ^The third parameter passed to the logger is
2179** log message after formatting via [sqlite3_snprintf()].
2180** The SQLite logging interface is not reentrant; the logger function
2181** supplied by the application must not invoke any SQLite interface.
2182** In a multi-threaded application, the application-defined logger
2183** function must be threadsafe. </dd>
2184**
2185** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
2186** <dd> This option takes a single argument of type int. If non-zero, then
2187** URI handling is globally enabled. If the parameter is zero, then URI handling
2188** is globally disabled. If URI handling is globally enabled, all filenames
2189** passed to [sqlite3_open()], [sqlite3_open_v2()], [sqlite3_open16()] or
2190** specified as part of [ATTACH] commands are interpreted as URIs, regardless
2191** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
2192** connection is opened. If it is globally disabled, filenames are
2193** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
2194** database connection is opened. By default, URI handling is globally
2195** disabled. The default value may be changed by compiling with the
2196** [SQLITE_USE_URI] symbol defined.
2197**
2198** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
2199** <dd> This option takes a single integer argument which is interpreted as
2200** a boolean in order to enable or disable the use of covering indices for
2201** full table scans in the query optimizer.  The default setting is determined
2202** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
2203** if that compile-time option is omitted.
2204** The ability to disable the use of covering indices for full table scans
2205** is because some incorrectly coded legacy applications might malfunction
2206** malfunction when the optimization is enabled.  Providing the ability to
2207** disable the optimization allows the older, buggy application code to work
2208** without change even with newer versions of SQLite.
2209**
2210** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
2211** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
2212** <dd> These options are obsolete and should not be used by new code.
2213** They are retained for backwards compatibility but are now no-ops.
2214** </dd>
2215**
2216** [[SQLITE_CONFIG_SQLLOG]]
2217** <dt>SQLITE_CONFIG_SQLLOG
2218** <dd>This option is only available if sqlite is compiled with the
2219** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
2220** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
2221** The second should be of type (void*). The callback is invoked by the library
2222** in three separate circumstances, identified by the value passed as the
2223** fourth parameter. If the fourth parameter is 0, then the database connection
2224** passed as the second argument has just been opened. The third argument
2225** points to a buffer containing the name of the main database file. If the
2226** fourth parameter is 1, then the SQL statement that the third parameter
2227** points to has just been executed. Or, if the fourth parameter is 2, then
2228** the connection being passed as the second parameter is being closed. The
2229** third parameter is passed NULL In this case.  An example of using this
2230** configuration option can be seen in the "test_sqllog.c" source file in
2231** the canonical SQLite source tree.</dd>
2232**
2233** [[SQLITE_CONFIG_MMAP_SIZE]]
2234** <dt>SQLITE_CONFIG_MMAP_SIZE
2235** <dd>SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
2236** that are the default mmap size limit (the default setting for
2237** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
2238** The default setting can be overridden by each database connection using
2239** either the [PRAGMA mmap_size] command, or by using the
2240** [SQLITE_FCNTL_MMAP_SIZE] file control.  The maximum allowed mmap size
2241** cannot be changed at run-time.  Nor may the maximum allowed mmap size
2242** exceed the compile-time maximum mmap size set by the
2243** [SQLITE_MAX_MMAP_SIZE] compile-time option.
2244** If either argument to this option is negative, then that argument is
2245** changed to its compile-time default.
2246** </dl>
2247*/
2248#define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
2249#define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
2250#define SQLITE_CONFIG_SERIALIZED    3  /* nil */
2251#define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
2252#define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
2253#define SQLITE_CONFIG_SCRATCH       6  /* void*, int sz, int N */
2254#define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
2255#define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
2256#define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
2257#define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
2258#define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
2259/* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
2260#define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
2261#define SQLITE_CONFIG_PCACHE       14  /* no-op */
2262#define SQLITE_CONFIG_GETPCACHE    15  /* no-op */
2263#define SQLITE_CONFIG_LOG          16  /* xFunc, void* */
2264#define SQLITE_CONFIG_URI          17  /* int */
2265#define SQLITE_CONFIG_PCACHE2      18  /* sqlite3_pcache_methods2* */
2266#define SQLITE_CONFIG_GETPCACHE2   19  /* sqlite3_pcache_methods2* */
2267#define SQLITE_CONFIG_COVERING_INDEX_SCAN 20  /* int */
2268#define SQLITE_CONFIG_SQLLOG       21  /* xSqllog, void* */
2269#define SQLITE_CONFIG_MMAP_SIZE    22  /* sqlite3_int64, sqlite3_int64 */
2270
2271/*
2272** CAPI3REF: Database Connection Configuration Options
2273**
2274** These constants are the available integer configuration options that
2275** can be passed as the second argument to the [sqlite3_db_config()] interface.
2276**
2277** New configuration options may be added in future releases of SQLite.
2278** Existing configuration options might be discontinued.  Applications
2279** should check the return code from [sqlite3_db_config()] to make sure that
2280** the call worked.  ^The [sqlite3_db_config()] interface will return a
2281** non-zero [error code] if a discontinued or unsupported configuration option
2282** is invoked.
2283**
2284** <dl>
2285** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
2286** <dd> ^This option takes three additional arguments that determine the
2287** [lookaside memory allocator] configuration for the [database connection].
2288** ^The first argument (the third parameter to [sqlite3_db_config()] is a
2289** pointer to a memory buffer to use for lookaside memory.
2290** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
2291** may be NULL in which case SQLite will allocate the
2292** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
2293** size of each lookaside buffer slot.  ^The third argument is the number of
2294** slots.  The size of the buffer in the first argument must be greater than
2295** or equal to the product of the second and third arguments.  The buffer
2296** must be aligned to an 8-byte boundary.  ^If the second argument to
2297** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
2298** rounded down to the next smaller multiple of 8.  ^(The lookaside memory
2299** configuration for a database connection can only be changed when that
2300** connection is not currently using lookaside memory, or in other words
2301** when the "current value" returned by
2302** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
2303** Any attempt to change the lookaside memory configuration when lookaside
2304** memory is in use leaves the configuration unchanged and returns
2305** [SQLITE_BUSY].)^</dd>
2306**
2307** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
2308** <dd> ^This option is used to enable or disable the enforcement of
2309** [foreign key constraints].  There should be two additional arguments.
2310** The first argument is an integer which is 0 to disable FK enforcement,
2311** positive to enable FK enforcement or negative to leave FK enforcement
2312** unchanged.  The second parameter is a pointer to an integer into which
2313** is written 0 or 1 to indicate whether FK enforcement is off or on
2314** following this call.  The second parameter may be a NULL pointer, in
2315** which case the FK enforcement setting is not reported back. </dd>
2316**
2317** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
2318** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
2319** There should be two additional arguments.
2320** The first argument is an integer which is 0 to disable triggers,
2321** positive to enable triggers or negative to leave the setting unchanged.
2322** The second parameter is a pointer to an integer into which
2323** is written 0 or 1 to indicate whether triggers are disabled or enabled
2324** following this call.  The second parameter may be a NULL pointer, in
2325** which case the trigger setting is not reported back. </dd>
2326**
2327** </dl>
2328*/
2329#define SQLITE_DBCONFIG_LOOKASIDE       1001  /* void* int int */
2330#define SQLITE_DBCONFIG_ENABLE_FKEY     1002  /* int int* */
2331#define SQLITE_DBCONFIG_ENABLE_TRIGGER  1003  /* int int* */
2332
2333
2334/*
2335** CAPI3REF: Enable Or Disable Extended Result Codes
2336**
2337** ^The sqlite3_extended_result_codes() routine enables or disables the
2338** [extended result codes] feature of SQLite. ^The extended result
2339** codes are disabled by default for historical compatibility.
2340*/
2341SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
2342
2343/*
2344** CAPI3REF: Last Insert Rowid
2345**
2346** ^Each entry in an SQLite table has a unique 64-bit signed
2347** integer key called the [ROWID | "rowid"]. ^The rowid is always available
2348** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
2349** names are not also used by explicitly declared columns. ^If
2350** the table has a column of type [INTEGER PRIMARY KEY] then that column
2351** is another alias for the rowid.
2352**
2353** ^This routine returns the [rowid] of the most recent
2354** successful [INSERT] into the database from the [database connection]
2355** in the first argument.  ^As of SQLite version 3.7.7, this routines
2356** records the last insert rowid of both ordinary tables and [virtual tables].
2357** ^If no successful [INSERT]s
2358** have ever occurred on that database connection, zero is returned.
2359**
2360** ^(If an [INSERT] occurs within a trigger or within a [virtual table]
2361** method, then this routine will return the [rowid] of the inserted
2362** row as long as the trigger or virtual table method is running.
2363** But once the trigger or virtual table method ends, the value returned
2364** by this routine reverts to what it was before the trigger or virtual
2365** table method began.)^
2366**
2367** ^An [INSERT] that fails due to a constraint violation is not a
2368** successful [INSERT] and does not change the value returned by this
2369** routine.  ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
2370** and INSERT OR ABORT make no changes to the return value of this
2371** routine when their insertion fails.  ^(When INSERT OR REPLACE
2372** encounters a constraint violation, it does not fail.  The
2373** INSERT continues to completion after deleting rows that caused
2374** the constraint problem so INSERT OR REPLACE will always change
2375** the return value of this interface.)^
2376**
2377** ^For the purposes of this routine, an [INSERT] is considered to
2378** be successful even if it is subsequently rolled back.
2379**
2380** This function is accessible to SQL statements via the
2381** [last_insert_rowid() SQL function].
2382**
2383** If a separate thread performs a new [INSERT] on the same
2384** database connection while the [sqlite3_last_insert_rowid()]
2385** function is running and thus changes the last insert [rowid],
2386** then the value returned by [sqlite3_last_insert_rowid()] is
2387** unpredictable and might not equal either the old or the new
2388** last insert [rowid].
2389*/
2390SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
2391
2392/*
2393** CAPI3REF: Count The Number Of Rows Modified
2394**
2395** ^This function returns the number of database rows that were changed
2396** or inserted or deleted by the most recently completed SQL statement
2397** on the [database connection] specified by the first parameter.
2398** ^(Only changes that are directly specified by the [INSERT], [UPDATE],
2399** or [DELETE] statement are counted.  Auxiliary changes caused by
2400** triggers or [foreign key actions] are not counted.)^ Use the
2401** [sqlite3_total_changes()] function to find the total number of changes
2402** including changes caused by triggers and foreign key actions.
2403**
2404** ^Changes to a view that are simulated by an [INSTEAD OF trigger]
2405** are not counted.  Only real table changes are counted.
2406**
2407** ^(A "row change" is a change to a single row of a single table
2408** caused by an INSERT, DELETE, or UPDATE statement.  Rows that
2409** are changed as side effects of [REPLACE] constraint resolution,
2410** rollback, ABORT processing, [DROP TABLE], or by any other
2411** mechanisms do not count as direct row changes.)^
2412**
2413** A "trigger context" is a scope of execution that begins and
2414** ends with the script of a [CREATE TRIGGER | trigger].
2415** Most SQL statements are
2416** evaluated outside of any trigger.  This is the "top level"
2417** trigger context.  If a trigger fires from the top level, a
2418** new trigger context is entered for the duration of that one
2419** trigger.  Subtriggers create subcontexts for their duration.
2420**
2421** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
2422** not create a new trigger context.
2423**
2424** ^This function returns the number of direct row changes in the
2425** most recent INSERT, UPDATE, or DELETE statement within the same
2426** trigger context.
2427**
2428** ^Thus, when called from the top level, this function returns the
2429** number of changes in the most recent INSERT, UPDATE, or DELETE
2430** that also occurred at the top level.  ^(Within the body of a trigger,
2431** the sqlite3_changes() interface can be called to find the number of
2432** changes in the most recently completed INSERT, UPDATE, or DELETE
2433** statement within the body of the same trigger.
2434** However, the number returned does not include changes
2435** caused by subtriggers since those have their own context.)^
2436**
2437** See also the [sqlite3_total_changes()] interface, the
2438** [count_changes pragma], and the [changes() SQL function].
2439**
2440** If a separate thread makes changes on the same database connection
2441** while [sqlite3_changes()] is running then the value returned
2442** is unpredictable and not meaningful.
2443*/
2444SQLITE_API int sqlite3_changes(sqlite3*);
2445
2446/*
2447** CAPI3REF: Total Number Of Rows Modified
2448**
2449** ^This function returns the number of row changes caused by [INSERT],
2450** [UPDATE] or [DELETE] statements since the [database connection] was opened.
2451** ^(The count returned by sqlite3_total_changes() includes all changes
2452** from all [CREATE TRIGGER | trigger] contexts and changes made by
2453** [foreign key actions]. However,
2454** the count does not include changes used to implement [REPLACE] constraints,
2455** do rollbacks or ABORT processing, or [DROP TABLE] processing.  The
2456** count does not include rows of views that fire an [INSTEAD OF trigger],
2457** though if the INSTEAD OF trigger makes changes of its own, those changes
2458** are counted.)^
2459** ^The sqlite3_total_changes() function counts the changes as soon as
2460** the statement that makes them is completed (when the statement handle
2461** is passed to [sqlite3_reset()] or [sqlite3_finalize()]).
2462**
2463** See also the [sqlite3_changes()] interface, the
2464** [count_changes pragma], and the [total_changes() SQL function].
2465**
2466** If a separate thread makes changes on the same database connection
2467** while [sqlite3_total_changes()] is running then the value
2468** returned is unpredictable and not meaningful.
2469*/
2470SQLITE_API int sqlite3_total_changes(sqlite3*);
2471
2472/*
2473** CAPI3REF: Interrupt A Long-Running Query
2474**
2475** ^This function causes any pending database operation to abort and
2476** return at its earliest opportunity. This routine is typically
2477** called in response to a user action such as pressing "Cancel"
2478** or Ctrl-C where the user wants a long query operation to halt
2479** immediately.
2480**
2481** ^It is safe to call this routine from a thread different from the
2482** thread that is currently running the database operation.  But it
2483** is not safe to call this routine with a [database connection] that
2484** is closed or might close before sqlite3_interrupt() returns.
2485**
2486** ^If an SQL operation is very nearly finished at the time when
2487** sqlite3_interrupt() is called, then it might not have an opportunity
2488** to be interrupted and might continue to completion.
2489**
2490** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
2491** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
2492** that is inside an explicit transaction, then the entire transaction
2493** will be rolled back automatically.
2494**
2495** ^The sqlite3_interrupt(D) call is in effect until all currently running
2496** SQL statements on [database connection] D complete.  ^Any new SQL statements
2497** that are started after the sqlite3_interrupt() call and before the
2498** running statements reaches zero are interrupted as if they had been
2499** running prior to the sqlite3_interrupt() call.  ^New SQL statements
2500** that are started after the running statement count reaches zero are
2501** not effected by the sqlite3_interrupt().
2502** ^A call to sqlite3_interrupt(D) that occurs when there are no running
2503** SQL statements is a no-op and has no effect on SQL statements
2504** that are started after the sqlite3_interrupt() call returns.
2505**
2506** If the database connection closes while [sqlite3_interrupt()]
2507** is running then bad things will likely happen.
2508*/
2509SQLITE_API void sqlite3_interrupt(sqlite3*);
2510
2511/*
2512** CAPI3REF: Determine If An SQL Statement Is Complete
2513**
2514** These routines are useful during command-line input to determine if the
2515** currently entered text seems to form a complete SQL statement or
2516** if additional input is needed before sending the text into
2517** SQLite for parsing.  ^These routines return 1 if the input string
2518** appears to be a complete SQL statement.  ^A statement is judged to be
2519** complete if it ends with a semicolon token and is not a prefix of a
2520** well-formed CREATE TRIGGER statement.  ^Semicolons that are embedded within
2521** string literals or quoted identifier names or comments are not
2522** independent tokens (they are part of the token in which they are
2523** embedded) and thus do not count as a statement terminator.  ^Whitespace
2524** and comments that follow the final semicolon are ignored.
2525**
2526** ^These routines return 0 if the statement is incomplete.  ^If a
2527** memory allocation fails, then SQLITE_NOMEM is returned.
2528**
2529** ^These routines do not parse the SQL statements thus
2530** will not detect syntactically incorrect SQL.
2531**
2532** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
2533** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
2534** automatically by sqlite3_complete16().  If that initialization fails,
2535** then the return value from sqlite3_complete16() will be non-zero
2536** regardless of whether or not the input SQL is complete.)^
2537**
2538** The input to [sqlite3_complete()] must be a zero-terminated
2539** UTF-8 string.
2540**
2541** The input to [sqlite3_complete16()] must be a zero-terminated
2542** UTF-16 string in native byte order.
2543*/
2544SQLITE_API int sqlite3_complete(const char *sql);
2545SQLITE_API int sqlite3_complete16(const void *sql);
2546
2547/*
2548** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
2549**
2550** ^This routine sets a callback function that might be invoked whenever
2551** an attempt is made to open a database table that another thread
2552** or process has locked.
2553**
2554** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
2555** is returned immediately upon encountering the lock.  ^If the busy callback
2556** is not NULL, then the callback might be invoked with two arguments.
2557**
2558** ^The first argument to the busy handler is a copy of the void* pointer which
2559** is the third argument to sqlite3_busy_handler().  ^The second argument to
2560** the busy handler callback is the number of times that the busy handler has
2561** been invoked for this locking event.  ^If the
2562** busy callback returns 0, then no additional attempts are made to
2563** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
2564** ^If the callback returns non-zero, then another attempt
2565** is made to open the database for reading and the cycle repeats.
2566**
2567** The presence of a busy handler does not guarantee that it will be invoked
2568** when there is lock contention. ^If SQLite determines that invoking the busy
2569** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
2570** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
2571** Consider a scenario where one process is holding a read lock that
2572** it is trying to promote to a reserved lock and
2573** a second process is holding a reserved lock that it is trying
2574** to promote to an exclusive lock.  The first process cannot proceed
2575** because it is blocked by the second and the second process cannot
2576** proceed because it is blocked by the first.  If both processes
2577** invoke the busy handlers, neither will make any progress.  Therefore,
2578** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
2579** will induce the first process to release its read lock and allow
2580** the second process to proceed.
2581**
2582** ^The default busy callback is NULL.
2583**
2584** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
2585** when SQLite is in the middle of a large transaction where all the
2586** changes will not fit into the in-memory cache.  SQLite will
2587** already hold a RESERVED lock on the database file, but it needs
2588** to promote this lock to EXCLUSIVE so that it can spill cache
2589** pages into the database file without harm to concurrent
2590** readers.  ^If it is unable to promote the lock, then the in-memory
2591** cache will be left in an inconsistent state and so the error
2592** code is promoted from the relatively benign [SQLITE_BUSY] to
2593** the more severe [SQLITE_IOERR_BLOCKED].  ^This error code promotion
2594** forces an automatic rollback of the changes.  See the
2595** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
2596** CorruptionFollowingBusyError</a> wiki page for a discussion of why
2597** this is important.
2598**
2599** ^(There can only be a single busy handler defined for each
2600** [database connection].  Setting a new busy handler clears any
2601** previously set handler.)^  ^Note that calling [sqlite3_busy_timeout()]
2602** will also set or clear the busy handler.
2603**
2604** The busy callback should not take any actions which modify the
2605** database connection that invoked the busy handler.  Any such actions
2606** result in undefined behavior.
2607**
2608** A busy handler must not close the database connection
2609** or [prepared statement] that invoked the busy handler.
2610*/
2611SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
2612
2613/*
2614** CAPI3REF: Set A Busy Timeout
2615**
2616** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
2617** for a specified amount of time when a table is locked.  ^The handler
2618** will sleep multiple times until at least "ms" milliseconds of sleeping
2619** have accumulated.  ^After at least "ms" milliseconds of sleeping,
2620** the handler returns 0 which causes [sqlite3_step()] to return
2621** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
2622**
2623** ^Calling this routine with an argument less than or equal to zero
2624** turns off all busy handlers.
2625**
2626** ^(There can only be a single busy handler for a particular
2627** [database connection] any any given moment.  If another busy handler
2628** was defined  (using [sqlite3_busy_handler()]) prior to calling
2629** this routine, that other busy handler is cleared.)^
2630*/
2631SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
2632
2633/*
2634** CAPI3REF: Convenience Routines For Running Queries
2635**
2636** This is a legacy interface that is preserved for backwards compatibility.
2637** Use of this interface is not recommended.
2638**
2639** Definition: A <b>result table</b> is memory data structure created by the
2640** [sqlite3_get_table()] interface.  A result table records the
2641** complete query results from one or more queries.
2642**
2643** The table conceptually has a number of rows and columns.  But
2644** these numbers are not part of the result table itself.  These
2645** numbers are obtained separately.  Let N be the number of rows
2646** and M be the number of columns.
2647**
2648** A result table is an array of pointers to zero-terminated UTF-8 strings.
2649** There are (N+1)*M elements in the array.  The first M pointers point
2650** to zero-terminated strings that  contain the names of the columns.
2651** The remaining entries all point to query results.  NULL values result
2652** in NULL pointers.  All other values are in their UTF-8 zero-terminated
2653** string representation as returned by [sqlite3_column_text()].
2654**
2655** A result table might consist of one or more memory allocations.
2656** It is not safe to pass a result table directly to [sqlite3_free()].
2657** A result table should be deallocated using [sqlite3_free_table()].
2658**
2659** ^(As an example of the result table format, suppose a query result
2660** is as follows:
2661**
2662** <blockquote><pre>
2663**        Name        | Age
2664**        -----------------------
2665**        Alice       | 43
2666**        Bob         | 28
2667**        Cindy       | 21
2668** </pre></blockquote>
2669**
2670** There are two column (M==2) and three rows (N==3).  Thus the
2671** result table has 8 entries.  Suppose the result table is stored
2672** in an array names azResult.  Then azResult holds this content:
2673**
2674** <blockquote><pre>
2675**        azResult&#91;0] = "Name";
2676**        azResult&#91;1] = "Age";
2677**        azResult&#91;2] = "Alice";
2678**        azResult&#91;3] = "43";
2679**        azResult&#91;4] = "Bob";
2680**        azResult&#91;5] = "28";
2681**        azResult&#91;6] = "Cindy";
2682**        azResult&#91;7] = "21";
2683** </pre></blockquote>)^
2684**
2685** ^The sqlite3_get_table() function evaluates one or more
2686** semicolon-separated SQL statements in the zero-terminated UTF-8
2687** string of its 2nd parameter and returns a result table to the
2688** pointer given in its 3rd parameter.
2689**
2690** After the application has finished with the result from sqlite3_get_table(),
2691** it must pass the result table pointer to sqlite3_free_table() in order to
2692** release the memory that was malloced.  Because of the way the
2693** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
2694** function must not try to call [sqlite3_free()] directly.  Only
2695** [sqlite3_free_table()] is able to release the memory properly and safely.
2696**
2697** The sqlite3_get_table() interface is implemented as a wrapper around
2698** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
2699** to any internal data structures of SQLite.  It uses only the public
2700** interface defined here.  As a consequence, errors that occur in the
2701** wrapper layer outside of the internal [sqlite3_exec()] call are not
2702** reflected in subsequent calls to [sqlite3_errcode()] or
2703** [sqlite3_errmsg()].
2704*/
2705SQLITE_API int sqlite3_get_table(
2706  sqlite3 *db,          /* An open database */
2707  const char *zSql,     /* SQL to be evaluated */
2708  char ***pazResult,    /* Results of the query */
2709  int *pnRow,           /* Number of result rows written here */
2710  int *pnColumn,        /* Number of result columns written here */
2711  char **pzErrmsg       /* Error msg written here */
2712);
2713SQLITE_API void sqlite3_free_table(char **result);
2714
2715/*
2716** CAPI3REF: Formatted String Printing Functions
2717**
2718** These routines are work-alikes of the "printf()" family of functions
2719** from the standard C library.
2720**
2721** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
2722** results into memory obtained from [sqlite3_malloc()].
2723** The strings returned by these two routines should be
2724** released by [sqlite3_free()].  ^Both routines return a
2725** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
2726** memory to hold the resulting string.
2727**
2728** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
2729** the standard C library.  The result is written into the
2730** buffer supplied as the second parameter whose size is given by
2731** the first parameter. Note that the order of the
2732** first two parameters is reversed from snprintf().)^  This is an
2733** historical accident that cannot be fixed without breaking
2734** backwards compatibility.  ^(Note also that sqlite3_snprintf()
2735** returns a pointer to its buffer instead of the number of
2736** characters actually written into the buffer.)^  We admit that
2737** the number of characters written would be a more useful return
2738** value but we cannot change the implementation of sqlite3_snprintf()
2739** now without breaking compatibility.
2740**
2741** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
2742** guarantees that the buffer is always zero-terminated.  ^The first
2743** parameter "n" is the total size of the buffer, including space for
2744** the zero terminator.  So the longest string that can be completely
2745** written will be n-1 characters.
2746**
2747** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
2748**
2749** These routines all implement some additional formatting
2750** options that are useful for constructing SQL statements.
2751** All of the usual printf() formatting options apply.  In addition, there
2752** is are "%q", "%Q", and "%z" options.
2753**
2754** ^(The %q option works like %s in that it substitutes a nul-terminated
2755** string from the argument list.  But %q also doubles every '\'' character.
2756** %q is designed for use inside a string literal.)^  By doubling each '\''
2757** character it escapes that character and allows it to be inserted into
2758** the string.
2759**
2760** For example, assume the string variable zText contains text as follows:
2761**
2762** <blockquote><pre>
2763**  char *zText = "It's a happy day!";
2764** </pre></blockquote>
2765**
2766** One can use this text in an SQL statement as follows:
2767**
2768** <blockquote><pre>
2769**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
2770**  sqlite3_exec(db, zSQL, 0, 0, 0);
2771**  sqlite3_free(zSQL);
2772** </pre></blockquote>
2773**
2774** Because the %q format string is used, the '\'' character in zText
2775** is escaped and the SQL generated is as follows:
2776**
2777** <blockquote><pre>
2778**  INSERT INTO table1 VALUES('It''s a happy day!')
2779** </pre></blockquote>
2780**
2781** This is correct.  Had we used %s instead of %q, the generated SQL
2782** would have looked like this:
2783**
2784** <blockquote><pre>
2785**  INSERT INTO table1 VALUES('It's a happy day!');
2786** </pre></blockquote>
2787**
2788** This second example is an SQL syntax error.  As a general rule you should
2789** always use %q instead of %s when inserting text into a string literal.
2790**
2791** ^(The %Q option works like %q except it also adds single quotes around
2792** the outside of the total string.  Additionally, if the parameter in the
2793** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
2794** single quotes).)^  So, for example, one could say:
2795**
2796** <blockquote><pre>
2797**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
2798**  sqlite3_exec(db, zSQL, 0, 0, 0);
2799**  sqlite3_free(zSQL);
2800** </pre></blockquote>
2801**
2802** The code above will render a correct SQL statement in the zSQL
2803** variable even if the zText variable is a NULL pointer.
2804**
2805** ^(The "%z" formatting option works like "%s" but with the
2806** addition that after the string has been read and copied into
2807** the result, [sqlite3_free()] is called on the input string.)^
2808*/
2809SQLITE_API char *sqlite3_mprintf(const char*,...);
2810SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
2811SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
2812SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
2813
2814/*
2815** CAPI3REF: Memory Allocation Subsystem
2816**
2817** The SQLite core uses these three routines for all of its own
2818** internal memory allocation needs. "Core" in the previous sentence
2819** does not include operating-system specific VFS implementation.  The
2820** Windows VFS uses native malloc() and free() for some operations.
2821**
2822** ^The sqlite3_malloc() routine returns a pointer to a block
2823** of memory at least N bytes in length, where N is the parameter.
2824** ^If sqlite3_malloc() is unable to obtain sufficient free
2825** memory, it returns a NULL pointer.  ^If the parameter N to
2826** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
2827** a NULL pointer.
2828**
2829** ^Calling sqlite3_free() with a pointer previously returned
2830** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
2831** that it might be reused.  ^The sqlite3_free() routine is
2832** a no-op if is called with a NULL pointer.  Passing a NULL pointer
2833** to sqlite3_free() is harmless.  After being freed, memory
2834** should neither be read nor written.  Even reading previously freed
2835** memory might result in a segmentation fault or other severe error.
2836** Memory corruption, a segmentation fault, or other severe error
2837** might result if sqlite3_free() is called with a non-NULL pointer that
2838** was not obtained from sqlite3_malloc() or sqlite3_realloc().
2839**
2840** ^(The sqlite3_realloc() interface attempts to resize a
2841** prior memory allocation to be at least N bytes, where N is the
2842** second parameter.  The memory allocation to be resized is the first
2843** parameter.)^ ^ If the first parameter to sqlite3_realloc()
2844** is a NULL pointer then its behavior is identical to calling
2845** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
2846** ^If the second parameter to sqlite3_realloc() is zero or
2847** negative then the behavior is exactly the same as calling
2848** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
2849** ^sqlite3_realloc() returns a pointer to a memory allocation
2850** of at least N bytes in size or NULL if sufficient memory is unavailable.
2851** ^If M is the size of the prior allocation, then min(N,M) bytes
2852** of the prior allocation are copied into the beginning of buffer returned
2853** by sqlite3_realloc() and the prior allocation is freed.
2854** ^If sqlite3_realloc() returns NULL, then the prior allocation
2855** is not freed.
2856**
2857** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()
2858** is always aligned to at least an 8 byte boundary, or to a
2859** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
2860** option is used.
2861**
2862** In SQLite version 3.5.0 and 3.5.1, it was possible to define
2863** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
2864** implementation of these routines to be omitted.  That capability
2865** is no longer provided.  Only built-in memory allocators can be used.
2866**
2867** Prior to SQLite version 3.7.10, the Windows OS interface layer called
2868** the system malloc() and free() directly when converting
2869** filenames between the UTF-8 encoding used by SQLite
2870** and whatever filename encoding is used by the particular Windows
2871** installation.  Memory allocation errors were detected, but
2872** they were reported back as [SQLITE_CANTOPEN] or
2873** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
2874**
2875** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
2876** must be either NULL or else pointers obtained from a prior
2877** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
2878** not yet been released.
2879**
2880** The application must not read or write any part of
2881** a block of memory after it has been released using
2882** [sqlite3_free()] or [sqlite3_realloc()].
2883*/
2884SQLITE_API void *sqlite3_malloc(int);
2885SQLITE_API void *sqlite3_realloc(void*, int);
2886SQLITE_API void sqlite3_free(void*);
2887
2888/*
2889** CAPI3REF: Memory Allocator Statistics
2890**
2891** SQLite provides these two interfaces for reporting on the status
2892** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
2893** routines, which form the built-in memory allocation subsystem.
2894**
2895** ^The [sqlite3_memory_used()] routine returns the number of bytes
2896** of memory currently outstanding (malloced but not freed).
2897** ^The [sqlite3_memory_highwater()] routine returns the maximum
2898** value of [sqlite3_memory_used()] since the high-water mark
2899** was last reset.  ^The values returned by [sqlite3_memory_used()] and
2900** [sqlite3_memory_highwater()] include any overhead
2901** added by SQLite in its implementation of [sqlite3_malloc()],
2902** but not overhead added by the any underlying system library
2903** routines that [sqlite3_malloc()] may call.
2904**
2905** ^The memory high-water mark is reset to the current value of
2906** [sqlite3_memory_used()] if and only if the parameter to
2907** [sqlite3_memory_highwater()] is true.  ^The value returned
2908** by [sqlite3_memory_highwater(1)] is the high-water mark
2909** prior to the reset.
2910*/
2911SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
2912SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
2913
2914/*
2915** CAPI3REF: Pseudo-Random Number Generator
2916**
2917** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
2918** select random [ROWID | ROWIDs] when inserting new records into a table that
2919** already uses the largest possible [ROWID].  The PRNG is also used for
2920** the build-in random() and randomblob() SQL functions.  This interface allows
2921** applications to access the same PRNG for other purposes.
2922**
2923** ^A call to this routine stores N bytes of randomness into buffer P.
2924**
2925** ^The first time this routine is invoked (either internally or by
2926** the application) the PRNG is seeded using randomness obtained
2927** from the xRandomness method of the default [sqlite3_vfs] object.
2928** ^On all subsequent invocations, the pseudo-randomness is generated
2929** internally and without recourse to the [sqlite3_vfs] xRandomness
2930** method.
2931*/
2932SQLITE_API void sqlite3_randomness(int N, void *P);
2933
2934/*
2935** CAPI3REF: Compile-Time Authorization Callbacks
2936**
2937** ^This routine registers an authorizer callback with a particular
2938** [database connection], supplied in the first argument.
2939** ^The authorizer callback is invoked as SQL statements are being compiled
2940** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
2941** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  ^At various
2942** points during the compilation process, as logic is being created
2943** to perform various actions, the authorizer callback is invoked to
2944** see if those actions are allowed.  ^The authorizer callback should
2945** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
2946** specific action but allow the SQL statement to continue to be
2947** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
2948** rejected with an error.  ^If the authorizer callback returns
2949** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
2950** then the [sqlite3_prepare_v2()] or equivalent call that triggered
2951** the authorizer will fail with an error message.
2952**
2953** When the callback returns [SQLITE_OK], that means the operation
2954** requested is ok.  ^When the callback returns [SQLITE_DENY], the
2955** [sqlite3_prepare_v2()] or equivalent call that triggered the
2956** authorizer will fail with an error message explaining that
2957** access is denied.
2958**
2959** ^The first parameter to the authorizer callback is a copy of the third
2960** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
2961** to the callback is an integer [SQLITE_COPY | action code] that specifies
2962** the particular action to be authorized. ^The third through sixth parameters
2963** to the callback are zero-terminated strings that contain additional
2964** details about the action to be authorized.
2965**
2966** ^If the action code is [SQLITE_READ]
2967** and the callback returns [SQLITE_IGNORE] then the
2968** [prepared statement] statement is constructed to substitute
2969** a NULL value in place of the table column that would have
2970** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
2971** return can be used to deny an untrusted user access to individual
2972** columns of a table.
2973** ^If the action code is [SQLITE_DELETE] and the callback returns
2974** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
2975** [truncate optimization] is disabled and all rows are deleted individually.
2976**
2977** An authorizer is used when [sqlite3_prepare | preparing]
2978** SQL statements from an untrusted source, to ensure that the SQL statements
2979** do not try to access data they are not allowed to see, or that they do not
2980** try to execute malicious statements that damage the database.  For
2981** example, an application may allow a user to enter arbitrary
2982** SQL queries for evaluation by a database.  But the application does
2983** not want the user to be able to make arbitrary changes to the
2984** database.  An authorizer could then be put in place while the
2985** user-entered SQL is being [sqlite3_prepare | prepared] that
2986** disallows everything except [SELECT] statements.
2987**
2988** Applications that need to process SQL from untrusted sources
2989** might also consider lowering resource limits using [sqlite3_limit()]
2990** and limiting database size using the [max_page_count] [PRAGMA]
2991** in addition to using an authorizer.
2992**
2993** ^(Only a single authorizer can be in place on a database connection
2994** at a time.  Each call to sqlite3_set_authorizer overrides the
2995** previous call.)^  ^Disable the authorizer by installing a NULL callback.
2996** The authorizer is disabled by default.
2997**
2998** The authorizer callback must not do anything that will modify
2999** the database connection that invoked the authorizer callback.
3000** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
3001** database connections for the meaning of "modify" in this paragraph.
3002**
3003** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
3004** statement might be re-prepared during [sqlite3_step()] due to a
3005** schema change.  Hence, the application should ensure that the
3006** correct authorizer callback remains in place during the [sqlite3_step()].
3007**
3008** ^Note that the authorizer callback is invoked only during
3009** [sqlite3_prepare()] or its variants.  Authorization is not
3010** performed during statement evaluation in [sqlite3_step()], unless
3011** as stated in the previous paragraph, sqlite3_step() invokes
3012** sqlite3_prepare_v2() to reprepare a statement after a schema change.
3013*/
3014SQLITE_API int sqlite3_set_authorizer(
3015  sqlite3*,
3016  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
3017  void *pUserData
3018);
3019
3020/*
3021** CAPI3REF: Authorizer Return Codes
3022**
3023** The [sqlite3_set_authorizer | authorizer callback function] must
3024** return either [SQLITE_OK] or one of these two constants in order
3025** to signal SQLite whether or not the action is permitted.  See the
3026** [sqlite3_set_authorizer | authorizer documentation] for additional
3027** information.
3028**
3029** Note that SQLITE_IGNORE is also used as a [SQLITE_ROLLBACK | return code]
3030** from the [sqlite3_vtab_on_conflict()] interface.
3031*/
3032#define SQLITE_DENY   1   /* Abort the SQL statement with an error */
3033#define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
3034
3035/*
3036** CAPI3REF: Authorizer Action Codes
3037**
3038** The [sqlite3_set_authorizer()] interface registers a callback function
3039** that is invoked to authorize certain SQL statement actions.  The
3040** second parameter to the callback is an integer code that specifies
3041** what action is being authorized.  These are the integer action codes that
3042** the authorizer callback may be passed.
3043**
3044** These action code values signify what kind of operation is to be
3045** authorized.  The 3rd and 4th parameters to the authorization
3046** callback function will be parameters or NULL depending on which of these
3047** codes is used as the second parameter.  ^(The 5th parameter to the
3048** authorizer callback is the name of the database ("main", "temp",
3049** etc.) if applicable.)^  ^The 6th parameter to the authorizer callback
3050** is the name of the inner-most trigger or view that is responsible for
3051** the access attempt or NULL if this access attempt is directly from
3052** top-level SQL code.
3053*/
3054/******************************************* 3rd ************ 4th ***********/
3055#define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
3056#define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
3057#define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
3058#define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
3059#define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
3060#define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
3061#define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
3062#define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
3063#define SQLITE_DELETE                9   /* Table Name      NULL            */
3064#define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
3065#define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
3066#define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
3067#define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
3068#define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
3069#define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
3070#define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
3071#define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
3072#define SQLITE_INSERT               18   /* Table Name      NULL            */
3073#define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
3074#define SQLITE_READ                 20   /* Table Name      Column Name     */
3075#define SQLITE_SELECT               21   /* NULL            NULL            */
3076#define SQLITE_TRANSACTION          22   /* Operation       NULL            */
3077#define SQLITE_UPDATE               23   /* Table Name      Column Name     */
3078#define SQLITE_ATTACH               24   /* Filename        NULL            */
3079#define SQLITE_DETACH               25   /* Database Name   NULL            */
3080#define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
3081#define SQLITE_REINDEX              27   /* Index Name      NULL            */
3082#define SQLITE_ANALYZE              28   /* Table Name      NULL            */
3083#define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
3084#define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
3085#define SQLITE_FUNCTION             31   /* NULL            Function Name   */
3086#define SQLITE_SAVEPOINT            32   /* Operation       Savepoint Name  */
3087#define SQLITE_COPY                  0   /* No longer used */
3088
3089/*
3090** CAPI3REF: Tracing And Profiling Functions
3091**
3092** These routines register callback functions that can be used for
3093** tracing and profiling the execution of SQL statements.
3094**
3095** ^The callback function registered by sqlite3_trace() is invoked at
3096** various times when an SQL statement is being run by [sqlite3_step()].
3097** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
3098** SQL statement text as the statement first begins executing.
3099** ^(Additional sqlite3_trace() callbacks might occur
3100** as each triggered subprogram is entered.  The callbacks for triggers
3101** contain a UTF-8 SQL comment that identifies the trigger.)^
3102**
3103** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
3104** the length of [bound parameter] expansion in the output of sqlite3_trace().
3105**
3106** ^The callback function registered by sqlite3_profile() is invoked
3107** as each SQL statement finishes.  ^The profile callback contains
3108** the original statement text and an estimate of wall-clock time
3109** of how long that statement took to run.  ^The profile callback
3110** time is in units of nanoseconds, however the current implementation
3111** is only capable of millisecond resolution so the six least significant
3112** digits in the time are meaningless.  Future versions of SQLite
3113** might provide greater resolution on the profiler callback.  The
3114** sqlite3_profile() function is considered experimental and is
3115** subject to change in future versions of SQLite.
3116*/
3117SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
3118SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
3119   void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
3120
3121/*
3122** CAPI3REF: Query Progress Callbacks
3123**
3124** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
3125** function X to be invoked periodically during long running calls to
3126** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
3127** database connection D.  An example use for this
3128** interface is to keep a GUI updated during a large query.
3129**
3130** ^The parameter P is passed through as the only parameter to the
3131** callback function X.  ^The parameter N is the number of
3132** [virtual machine instructions] that are evaluated between successive
3133** invocations of the callback X.
3134**
3135** ^Only a single progress handler may be defined at one time per
3136** [database connection]; setting a new progress handler cancels the
3137** old one.  ^Setting parameter X to NULL disables the progress handler.
3138** ^The progress handler is also disabled by setting N to a value less
3139** than 1.
3140**
3141** ^If the progress callback returns non-zero, the operation is
3142** interrupted.  This feature can be used to implement a
3143** "Cancel" button on a GUI progress dialog box.
3144**
3145** The progress handler callback must not do anything that will modify
3146** the database connection that invoked the progress handler.
3147** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
3148** database connections for the meaning of "modify" in this paragraph.
3149**
3150*/
3151SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
3152
3153/*
3154** CAPI3REF: Opening A New Database Connection
3155**
3156** ^These routines open an SQLite database file as specified by the
3157** filename argument. ^The filename argument is interpreted as UTF-8 for
3158** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
3159** order for sqlite3_open16(). ^(A [database connection] handle is usually
3160** returned in *ppDb, even if an error occurs.  The only exception is that
3161** if SQLite is unable to allocate memory to hold the [sqlite3] object,
3162** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
3163** object.)^ ^(If the database is opened (and/or created) successfully, then
3164** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.)^ ^The
3165** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
3166** an English language description of the error following a failure of any
3167** of the sqlite3_open() routines.
3168**
3169** ^The default encoding for the database will be UTF-8 if
3170** sqlite3_open() or sqlite3_open_v2() is called and
3171** UTF-16 in the native byte order if sqlite3_open16() is used.
3172**
3173** Whether or not an error occurs when it is opened, resources
3174** associated with the [database connection] handle should be released by
3175** passing it to [sqlite3_close()] when it is no longer required.
3176**
3177** The sqlite3_open_v2() interface works like sqlite3_open()
3178** except that it accepts two additional parameters for additional control
3179** over the new database connection.  ^(The flags parameter to
3180** sqlite3_open_v2() can take one of
3181** the following three values, optionally combined with the
3182** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
3183** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
3184**
3185** <dl>
3186** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
3187** <dd>The database is opened in read-only mode.  If the database does not
3188** already exist, an error is returned.</dd>)^
3189**
3190** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
3191** <dd>The database is opened for reading and writing if possible, or reading
3192** only if the file is write protected by the operating system.  In either
3193** case the database must already exist, otherwise an error is returned.</dd>)^
3194**
3195** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
3196** <dd>The database is opened for reading and writing, and is created if
3197** it does not already exist. This is the behavior that is always used for
3198** sqlite3_open() and sqlite3_open16().</dd>)^
3199** </dl>
3200**
3201** If the 3rd parameter to sqlite3_open_v2() is not one of the
3202** combinations shown above optionally combined with other
3203** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
3204** then the behavior is undefined.
3205**
3206** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
3207** opens in the multi-thread [threading mode] as long as the single-thread
3208** mode has not been set at compile-time or start-time.  ^If the
3209** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
3210** in the serialized [threading mode] unless single-thread was
3211** previously selected at compile-time or start-time.
3212** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
3213** eligible to use [shared cache mode], regardless of whether or not shared
3214** cache is enabled using [sqlite3_enable_shared_cache()].  ^The
3215** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
3216** participate in [shared cache mode] even if it is enabled.
3217**
3218** ^The fourth parameter to sqlite3_open_v2() is the name of the
3219** [sqlite3_vfs] object that defines the operating system interface that
3220** the new database connection should use.  ^If the fourth parameter is
3221** a NULL pointer then the default [sqlite3_vfs] object is used.
3222**
3223** ^If the filename is ":memory:", then a private, temporary in-memory database
3224** is created for the connection.  ^This in-memory database will vanish when
3225** the database connection is closed.  Future versions of SQLite might
3226** make use of additional special filenames that begin with the ":" character.
3227** It is recommended that when a database filename actually does begin with
3228** a ":" character you should prefix the filename with a pathname such as
3229** "./" to avoid ambiguity.
3230**
3231** ^If the filename is an empty string, then a private, temporary
3232** on-disk database will be created.  ^This private database will be
3233** automatically deleted as soon as the database connection is closed.
3234**
3235** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
3236**
3237** ^If [URI filename] interpretation is enabled, and the filename argument
3238** begins with "file:", then the filename is interpreted as a URI. ^URI
3239** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
3240** set in the fourth argument to sqlite3_open_v2(), or if it has
3241** been enabled globally using the [SQLITE_CONFIG_URI] option with the
3242** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
3243** As of SQLite version 3.7.7, URI filename interpretation is turned off
3244** by default, but future releases of SQLite might enable URI filename
3245** interpretation by default.  See "[URI filenames]" for additional
3246** information.
3247**
3248** URI filenames are parsed according to RFC 3986. ^If the URI contains an
3249** authority, then it must be either an empty string or the string
3250** "localhost". ^If the authority is not an empty string or "localhost", an
3251** error is returned to the caller. ^The fragment component of a URI, if
3252** present, is ignored.
3253**
3254** ^SQLite uses the path component of the URI as the name of the disk file
3255** which contains the database. ^If the path begins with a '/' character,
3256** then it is interpreted as an absolute path. ^If the path does not begin
3257** with a '/' (meaning that the authority section is omitted from the URI)
3258** then the path is interpreted as a relative path.
3259** ^On windows, the first component of an absolute path
3260** is a drive specification (e.g. "C:").
3261**
3262** [[core URI query parameters]]
3263** The query component of a URI may contain parameters that are interpreted
3264** either by SQLite itself, or by a [VFS | custom VFS implementation].
3265** SQLite interprets the following three query parameters:
3266**
3267** <ul>
3268**   <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
3269**     a VFS object that provides the operating system interface that should
3270**     be used to access the database file on disk. ^If this option is set to
3271**     an empty string the default VFS object is used. ^Specifying an unknown
3272**     VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
3273**     present, then the VFS specified by the option takes precedence over
3274**     the value passed as the fourth parameter to sqlite3_open_v2().
3275**
3276**   <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
3277**     "rwc", or "memory". Attempting to set it to any other value is
3278**     an error)^.
3279**     ^If "ro" is specified, then the database is opened for read-only
3280**     access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
3281**     third argument to sqlite3_open_v2(). ^If the mode option is set to
3282**     "rw", then the database is opened for read-write (but not create)
3283**     access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
3284**     been set. ^Value "rwc" is equivalent to setting both
3285**     SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE.  ^If the mode option is
3286**     set to "memory" then a pure [in-memory database] that never reads
3287**     or writes from disk is used. ^It is an error to specify a value for
3288**     the mode parameter that is less restrictive than that specified by
3289**     the flags passed in the third parameter to sqlite3_open_v2().
3290**
3291**   <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
3292**     "private". ^Setting it to "shared" is equivalent to setting the
3293**     SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
3294**     sqlite3_open_v2(). ^Setting the cache parameter to "private" is
3295**     equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
3296**     ^If sqlite3_open_v2() is used and the "cache" parameter is present in
3297**     a URI filename, its value overrides any behavior requested by setting
3298**     SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
3299** </ul>
3300**
3301** ^Specifying an unknown parameter in the query component of a URI is not an
3302** error.  Future versions of SQLite might understand additional query
3303** parameters.  See "[query parameters with special meaning to SQLite]" for
3304** additional information.
3305**
3306** [[URI filename examples]] <h3>URI filename examples</h3>
3307**
3308** <table border="1" align=center cellpadding=5>
3309** <tr><th> URI filenames <th> Results
3310** <tr><td> file:data.db <td>
3311**          Open the file "data.db" in the current directory.
3312** <tr><td> file:/home/fred/data.db<br>
3313**          file:///home/fred/data.db <br>
3314**          file://localhost/home/fred/data.db <br> <td>
3315**          Open the database file "/home/fred/data.db".
3316** <tr><td> file://darkstar/home/fred/data.db <td>
3317**          An error. "darkstar" is not a recognized authority.
3318** <tr><td style="white-space:nowrap">
3319**          file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
3320**     <td> Windows only: Open the file "data.db" on fred's desktop on drive
3321**          C:. Note that the %20 escaping in this example is not strictly
3322**          necessary - space characters can be used literally
3323**          in URI filenames.
3324** <tr><td> file:data.db?mode=ro&cache=private <td>
3325**          Open file "data.db" in the current directory for read-only access.
3326**          Regardless of whether or not shared-cache mode is enabled by
3327**          default, use a private cache.
3328** <tr><td> file:/home/fred/data.db?vfs=unix-nolock <td>
3329**          Open file "/home/fred/data.db". Use the special VFS "unix-nolock".
3330** <tr><td> file:data.db?mode=readonly <td>
3331**          An error. "readonly" is not a valid option for the "mode" parameter.
3332** </table>
3333**
3334** ^URI hexadecimal escape sequences (%HH) are supported within the path and
3335** query components of a URI. A hexadecimal escape sequence consists of a
3336** percent sign - "%" - followed by exactly two hexadecimal digits
3337** specifying an octet value. ^Before the path or query components of a
3338** URI filename are interpreted, they are encoded using UTF-8 and all
3339** hexadecimal escape sequences replaced by a single byte containing the
3340** corresponding octet. If this process generates an invalid UTF-8 encoding,
3341** the results are undefined.
3342**
3343** <b>Note to Windows users:</b>  The encoding used for the filename argument
3344** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
3345** codepage is currently defined.  Filenames containing international
3346** characters must be converted to UTF-8 prior to passing them into
3347** sqlite3_open() or sqlite3_open_v2().
3348**
3349** <b>Note to Windows Runtime users:</b>  The temporary directory must be set
3350** prior to calling sqlite3_open() or sqlite3_open_v2().  Otherwise, various
3351** features that require the use of temporary files may fail.
3352**
3353** See also: [sqlite3_temp_directory]
3354*/
3355SQLITE_API int sqlite3_open(
3356  const char *filename,   /* Database filename (UTF-8) */
3357  sqlite3 **ppDb          /* OUT: SQLite db handle */
3358);
3359SQLITE_API int sqlite3_open16(
3360  const void *filename,   /* Database filename (UTF-16) */
3361  sqlite3 **ppDb          /* OUT: SQLite db handle */
3362);
3363SQLITE_API int sqlite3_open_v2(
3364  const char *filename,   /* Database filename (UTF-8) */
3365  sqlite3 **ppDb,         /* OUT: SQLite db handle */
3366  int flags,              /* Flags */
3367  const char *zVfs        /* Name of VFS module to use */
3368);
3369
3370/*
3371** CAPI3REF: Obtain Values For URI Parameters
3372**
3373** These are utility routines, useful to VFS implementations, that check
3374** to see if a database file was a URI that contained a specific query
3375** parameter, and if so obtains the value of that query parameter.
3376**
3377** If F is the database filename pointer passed into the xOpen() method of
3378** a VFS implementation when the flags parameter to xOpen() has one or
3379** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
3380** P is the name of the query parameter, then
3381** sqlite3_uri_parameter(F,P) returns the value of the P
3382** parameter if it exists or a NULL pointer if P does not appear as a
3383** query parameter on F.  If P is a query parameter of F
3384** has no explicit value, then sqlite3_uri_parameter(F,P) returns
3385** a pointer to an empty string.
3386**
3387** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
3388** parameter and returns true (1) or false (0) according to the value
3389** of P.  The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
3390** value of query parameter P is one of "yes", "true", or "on" in any
3391** case or if the value begins with a non-zero number.  The
3392** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
3393** query parameter P is one of "no", "false", or "off" in any case or
3394** if the value begins with a numeric zero.  If P is not a query
3395** parameter on F or if the value of P is does not match any of the
3396** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
3397**
3398** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
3399** 64-bit signed integer and returns that integer, or D if P does not
3400** exist.  If the value of P is something other than an integer, then
3401** zero is returned.
3402**
3403** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
3404** sqlite3_uri_boolean(F,P,B) returns B.  If F is not a NULL pointer and
3405** is not a database file pathname pointer that SQLite passed into the xOpen
3406** VFS method, then the behavior of this routine is undefined and probably
3407** undesirable.
3408*/
3409SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
3410SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
3411SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
3412
3413
3414/*
3415** CAPI3REF: Error Codes And Messages
3416**
3417** ^The sqlite3_errcode() interface returns the numeric [result code] or
3418** [extended result code] for the most recent failed sqlite3_* API call
3419** associated with a [database connection]. If a prior API call failed
3420** but the most recent API call succeeded, the return value from
3421** sqlite3_errcode() is undefined.  ^The sqlite3_extended_errcode()
3422** interface is the same except that it always returns the
3423** [extended result code] even when extended result codes are
3424** disabled.
3425**
3426** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
3427** text that describes the error, as either UTF-8 or UTF-16 respectively.
3428** ^(Memory to hold the error message string is managed internally.
3429** The application does not need to worry about freeing the result.
3430** However, the error string might be overwritten or deallocated by
3431** subsequent calls to other SQLite interface functions.)^
3432**
3433** ^The sqlite3_errstr() interface returns the English-language text
3434** that describes the [result code], as UTF-8.
3435** ^(Memory to hold the error message string is managed internally
3436** and must not be freed by the application)^.
3437**
3438** When the serialized [threading mode] is in use, it might be the
3439** case that a second error occurs on a separate thread in between
3440** the time of the first error and the call to these interfaces.
3441** When that happens, the second error will be reported since these
3442** interfaces always report the most recent result.  To avoid
3443** this, each thread can obtain exclusive use of the [database connection] D
3444** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
3445** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
3446** all calls to the interfaces listed here are completed.
3447**
3448** If an interface fails with SQLITE_MISUSE, that means the interface
3449** was invoked incorrectly by the application.  In that case, the
3450** error code and message may or may not be set.
3451*/
3452SQLITE_API int sqlite3_errcode(sqlite3 *db);
3453SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
3454SQLITE_API const char *sqlite3_errmsg(sqlite3*);
3455SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
3456SQLITE_API const char *sqlite3_errstr(int);
3457
3458/*
3459** CAPI3REF: SQL Statement Object
3460** KEYWORDS: {prepared statement} {prepared statements}
3461**
3462** An instance of this object represents a single SQL statement.
3463** This object is variously known as a "prepared statement" or a
3464** "compiled SQL statement" or simply as a "statement".
3465**
3466** The life of a statement object goes something like this:
3467**
3468** <ol>
3469** <li> Create the object using [sqlite3_prepare_v2()] or a related
3470**      function.
3471** <li> Bind values to [host parameters] using the sqlite3_bind_*()
3472**      interfaces.
3473** <li> Run the SQL by calling [sqlite3_step()] one or more times.
3474** <li> Reset the statement using [sqlite3_reset()] then go back
3475**      to step 2.  Do this zero or more times.
3476** <li> Destroy the object using [sqlite3_finalize()].
3477** </ol>
3478**
3479** Refer to documentation on individual methods above for additional
3480** information.
3481*/
3482typedef struct sqlite3_stmt sqlite3_stmt;
3483
3484/*
3485** CAPI3REF: Run-time Limits
3486**
3487** ^(This interface allows the size of various constructs to be limited
3488** on a connection by connection basis.  The first parameter is the
3489** [database connection] whose limit is to be set or queried.  The
3490** second parameter is one of the [limit categories] that define a
3491** class of constructs to be size limited.  The third parameter is the
3492** new limit for that construct.)^
3493**
3494** ^If the new limit is a negative number, the limit is unchanged.
3495** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
3496** [limits | hard upper bound]
3497** set at compile-time by a C preprocessor macro called
3498** [limits | SQLITE_MAX_<i>NAME</i>].
3499** (The "_LIMIT_" in the name is changed to "_MAX_".))^
3500** ^Attempts to increase a limit above its hard upper bound are
3501** silently truncated to the hard upper bound.
3502**
3503** ^Regardless of whether or not the limit was changed, the
3504** [sqlite3_limit()] interface returns the prior value of the limit.
3505** ^Hence, to find the current value of a limit without changing it,
3506** simply invoke this interface with the third parameter set to -1.
3507**
3508** Run-time limits are intended for use in applications that manage
3509** both their own internal database and also databases that are controlled
3510** by untrusted external sources.  An example application might be a
3511** web browser that has its own databases for storing history and
3512** separate databases controlled by JavaScript applications downloaded
3513** off the Internet.  The internal databases can be given the
3514** large, default limits.  Databases managed by external sources can
3515** be given much smaller limits designed to prevent a denial of service
3516** attack.  Developers might also want to use the [sqlite3_set_authorizer()]
3517** interface to further control untrusted SQL.  The size of the database
3518** created by an untrusted script can be contained using the
3519** [max_page_count] [PRAGMA].
3520**
3521** New run-time limit categories may be added in future releases.
3522*/
3523SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
3524
3525/*
3526** CAPI3REF: Run-Time Limit Categories
3527** KEYWORDS: {limit category} {*limit categories}
3528**
3529** These constants define various performance limits
3530** that can be lowered at run-time using [sqlite3_limit()].
3531** The synopsis of the meanings of the various limits is shown below.
3532** Additional information is available at [limits | Limits in SQLite].
3533**
3534** <dl>
3535** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
3536** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
3537**
3538** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
3539** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
3540**
3541** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
3542** <dd>The maximum number of columns in a table definition or in the
3543** result set of a [SELECT] or the maximum number of columns in an index
3544** or in an ORDER BY or GROUP BY clause.</dd>)^
3545**
3546** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
3547** <dd>The maximum depth of the parse tree on any expression.</dd>)^
3548**
3549** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
3550** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
3551**
3552** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
3553** <dd>The maximum number of instructions in a virtual machine program
3554** used to implement an SQL statement.  This limit is not currently
3555** enforced, though that might be added in some future release of
3556** SQLite.</dd>)^
3557**
3558** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
3559** <dd>The maximum number of arguments on a function.</dd>)^
3560**
3561** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
3562** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
3563**
3564** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
3565** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
3566** <dd>The maximum length of the pattern argument to the [LIKE] or
3567** [GLOB] operators.</dd>)^
3568**
3569** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
3570** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
3571** <dd>The maximum index number of any [parameter] in an SQL statement.)^
3572**
3573** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
3574** <dd>The maximum depth of recursion for triggers.</dd>)^
3575** </dl>
3576*/
3577#define SQLITE_LIMIT_LENGTH                    0
3578#define SQLITE_LIMIT_SQL_LENGTH                1
3579#define SQLITE_LIMIT_COLUMN                    2
3580#define SQLITE_LIMIT_EXPR_DEPTH                3
3581#define SQLITE_LIMIT_COMPOUND_SELECT           4
3582#define SQLITE_LIMIT_VDBE_OP                   5
3583#define SQLITE_LIMIT_FUNCTION_ARG              6
3584#define SQLITE_LIMIT_ATTACHED                  7
3585#define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
3586#define SQLITE_LIMIT_VARIABLE_NUMBER           9
3587#define SQLITE_LIMIT_TRIGGER_DEPTH            10
3588
3589/*
3590** CAPI3REF: Compiling An SQL Statement
3591** KEYWORDS: {SQL statement compiler}
3592**
3593** To execute an SQL query, it must first be compiled into a byte-code
3594** program using one of these routines.
3595**
3596** The first argument, "db", is a [database connection] obtained from a
3597** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
3598** [sqlite3_open16()].  The database connection must not have been closed.
3599**
3600** The second argument, "zSql", is the statement to be compiled, encoded
3601** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
3602** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
3603** use UTF-16.
3604**
3605** ^If the nByte argument is less than zero, then zSql is read up to the
3606** first zero terminator. ^If nByte is non-negative, then it is the maximum
3607** number of  bytes read from zSql.  ^When nByte is non-negative, the
3608** zSql string ends at either the first '\000' or '\u0000' character or
3609** the nByte-th byte, whichever comes first. If the caller knows
3610** that the supplied string is nul-terminated, then there is a small
3611** performance advantage to be gained by passing an nByte parameter that
3612** is equal to the number of bytes in the input string <i>including</i>
3613** the nul-terminator bytes as this saves SQLite from having to
3614** make a copy of the input string.
3615**
3616** ^If pzTail is not NULL then *pzTail is made to point to the first byte
3617** past the end of the first SQL statement in zSql.  These routines only
3618** compile the first statement in zSql, so *pzTail is left pointing to
3619** what remains uncompiled.
3620**
3621** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
3622** executed using [sqlite3_step()].  ^If there is an error, *ppStmt is set
3623** to NULL.  ^If the input text contains no SQL (if the input is an empty
3624** string or a comment) then *ppStmt is set to NULL.
3625** The calling procedure is responsible for deleting the compiled
3626** SQL statement using [sqlite3_finalize()] after it has finished with it.
3627** ppStmt may not be NULL.
3628**
3629** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
3630** otherwise an [error code] is returned.
3631**
3632** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
3633** recommended for all new programs. The two older interfaces are retained
3634** for backwards compatibility, but their use is discouraged.
3635** ^In the "v2" interfaces, the prepared statement
3636** that is returned (the [sqlite3_stmt] object) contains a copy of the
3637** original SQL text. This causes the [sqlite3_step()] interface to
3638** behave differently in three ways:
3639**
3640** <ol>
3641** <li>
3642** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
3643** always used to do, [sqlite3_step()] will automatically recompile the SQL
3644** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]
3645** retries will occur before sqlite3_step() gives up and returns an error.
3646** </li>
3647**
3648** <li>
3649** ^When an error occurs, [sqlite3_step()] will return one of the detailed
3650** [error codes] or [extended error codes].  ^The legacy behavior was that
3651** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
3652** and the application would have to make a second call to [sqlite3_reset()]
3653** in order to find the underlying cause of the problem. With the "v2" prepare
3654** interfaces, the underlying reason for the error is returned immediately.
3655** </li>
3656**
3657** <li>
3658** ^If the specific value bound to [parameter | host parameter] in the
3659** WHERE clause might influence the choice of query plan for a statement,
3660** then the statement will be automatically recompiled, as if there had been
3661** a schema change, on the first  [sqlite3_step()] call following any change
3662** to the [sqlite3_bind_text | bindings] of that [parameter].
3663** ^The specific value of WHERE-clause [parameter] might influence the
3664** choice of query plan if the parameter is the left-hand side of a [LIKE]
3665** or [GLOB] operator or if the parameter is compared to an indexed column
3666** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
3667** the
3668** </li>
3669** </ol>
3670*/
3671SQLITE_API int sqlite3_prepare(
3672  sqlite3 *db,            /* Database handle */
3673  const char *zSql,       /* SQL statement, UTF-8 encoded */
3674  int nByte,              /* Maximum length of zSql in bytes. */
3675  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3676  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3677);
3678SQLITE_API int sqlite3_prepare_v2(
3679  sqlite3 *db,            /* Database handle */
3680  const char *zSql,       /* SQL statement, UTF-8 encoded */
3681  int nByte,              /* Maximum length of zSql in bytes. */
3682  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3683  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3684);
3685SQLITE_API int sqlite3_prepare16(
3686  sqlite3 *db,            /* Database handle */
3687  const void *zSql,       /* SQL statement, UTF-16 encoded */
3688  int nByte,              /* Maximum length of zSql in bytes. */
3689  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3690  const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3691);
3692SQLITE_API int sqlite3_prepare16_v2(
3693  sqlite3 *db,            /* Database handle */
3694  const void *zSql,       /* SQL statement, UTF-16 encoded */
3695  int nByte,              /* Maximum length of zSql in bytes. */
3696  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3697  const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3698);
3699
3700/*
3701** CAPI3REF: Retrieving Statement SQL
3702**
3703** ^This interface can be used to retrieve a saved copy of the original
3704** SQL text used to create a [prepared statement] if that statement was
3705** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
3706*/
3707SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
3708
3709/*
3710** CAPI3REF: Determine If An SQL Statement Writes The Database
3711**
3712** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
3713** and only if the [prepared statement] X makes no direct changes to
3714** the content of the database file.
3715**
3716** Note that [application-defined SQL functions] or
3717** [virtual tables] might change the database indirectly as a side effect.
3718** ^(For example, if an application defines a function "eval()" that
3719** calls [sqlite3_exec()], then the following SQL statement would
3720** change the database file through side-effects:
3721**
3722** <blockquote><pre>
3723**    SELECT eval('DELETE FROM t1') FROM t2;
3724** </pre></blockquote>
3725**
3726** But because the [SELECT] statement does not change the database file
3727** directly, sqlite3_stmt_readonly() would still return true.)^
3728**
3729** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
3730** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
3731** since the statements themselves do not actually modify the database but
3732** rather they control the timing of when other statements modify the
3733** database.  ^The [ATTACH] and [DETACH] statements also cause
3734** sqlite3_stmt_readonly() to return true since, while those statements
3735** change the configuration of a database connection, they do not make
3736** changes to the content of the database files on disk.
3737*/
3738SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
3739
3740/*
3741** CAPI3REF: Determine If A Prepared Statement Has Been Reset
3742**
3743** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
3744** [prepared statement] S has been stepped at least once using
3745** [sqlite3_step(S)] but has not run to completion and/or has not
3746** been reset using [sqlite3_reset(S)].  ^The sqlite3_stmt_busy(S)
3747** interface returns false if S is a NULL pointer.  If S is not a
3748** NULL pointer and is not a pointer to a valid [prepared statement]
3749** object, then the behavior is undefined and probably undesirable.
3750**
3751** This interface can be used in combination [sqlite3_next_stmt()]
3752** to locate all prepared statements associated with a database
3753** connection that are in need of being reset.  This can be used,
3754** for example, in diagnostic routines to search for prepared
3755** statements that are holding a transaction open.
3756*/
3757SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
3758
3759/*
3760** CAPI3REF: Dynamically Typed Value Object
3761** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
3762**
3763** SQLite uses the sqlite3_value object to represent all values
3764** that can be stored in a database table. SQLite uses dynamic typing
3765** for the values it stores.  ^Values stored in sqlite3_value objects
3766** can be integers, floating point values, strings, BLOBs, or NULL.
3767**
3768** An sqlite3_value object may be either "protected" or "unprotected".
3769** Some interfaces require a protected sqlite3_value.  Other interfaces
3770** will accept either a protected or an unprotected sqlite3_value.
3771** Every interface that accepts sqlite3_value arguments specifies
3772** whether or not it requires a protected sqlite3_value.
3773**
3774** The terms "protected" and "unprotected" refer to whether or not
3775** a mutex is held.  An internal mutex is held for a protected
3776** sqlite3_value object but no mutex is held for an unprotected
3777** sqlite3_value object.  If SQLite is compiled to be single-threaded
3778** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
3779** or if SQLite is run in one of reduced mutex modes
3780** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
3781** then there is no distinction between protected and unprotected
3782** sqlite3_value objects and they can be used interchangeably.  However,
3783** for maximum code portability it is recommended that applications
3784** still make the distinction between protected and unprotected
3785** sqlite3_value objects even when not strictly required.
3786**
3787** ^The sqlite3_value objects that are passed as parameters into the
3788** implementation of [application-defined SQL functions] are protected.
3789** ^The sqlite3_value object returned by
3790** [sqlite3_column_value()] is unprotected.
3791** Unprotected sqlite3_value objects may only be used with
3792** [sqlite3_result_value()] and [sqlite3_bind_value()].
3793** The [sqlite3_value_blob | sqlite3_value_type()] family of
3794** interfaces require protected sqlite3_value objects.
3795*/
3796typedef struct Mem sqlite3_value;
3797
3798/*
3799** CAPI3REF: SQL Function Context Object
3800**
3801** The context in which an SQL function executes is stored in an
3802** sqlite3_context object.  ^A pointer to an sqlite3_context object
3803** is always first parameter to [application-defined SQL functions].
3804** The application-defined SQL function implementation will pass this
3805** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
3806** [sqlite3_aggregate_context()], [sqlite3_user_data()],
3807** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
3808** and/or [sqlite3_set_auxdata()].
3809*/
3810typedef struct sqlite3_context sqlite3_context;
3811
3812/*
3813** CAPI3REF: Binding Values To Prepared Statements
3814** KEYWORDS: {host parameter} {host parameters} {host parameter name}
3815** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
3816**
3817** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
3818** literals may be replaced by a [parameter] that matches one of following
3819** templates:
3820**
3821** <ul>
3822** <li>  ?
3823** <li>  ?NNN
3824** <li>  :VVV
3825** <li>  @VVV
3826** <li>  $VVV
3827** </ul>
3828**
3829** In the templates above, NNN represents an integer literal,
3830** and VVV represents an alphanumeric identifier.)^  ^The values of these
3831** parameters (also called "host parameter names" or "SQL parameters")
3832** can be set using the sqlite3_bind_*() routines defined here.
3833**
3834** ^The first argument to the sqlite3_bind_*() routines is always
3835** a pointer to the [sqlite3_stmt] object returned from
3836** [sqlite3_prepare_v2()] or its variants.
3837**
3838** ^The second argument is the index of the SQL parameter to be set.
3839** ^The leftmost SQL parameter has an index of 1.  ^When the same named
3840** SQL parameter is used more than once, second and subsequent
3841** occurrences have the same index as the first occurrence.
3842** ^The index for named parameters can be looked up using the
3843** [sqlite3_bind_parameter_index()] API if desired.  ^The index
3844** for "?NNN" parameters is the value of NNN.
3845** ^The NNN value must be between 1 and the [sqlite3_limit()]
3846** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
3847**
3848** ^The third argument is the value to bind to the parameter.
3849** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
3850** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
3851** is ignored and the end result is the same as sqlite3_bind_null().
3852**
3853** ^(In those routines that have a fourth argument, its value is the
3854** number of bytes in the parameter.  To be clear: the value is the
3855** number of <u>bytes</u> in the value, not the number of characters.)^
3856** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
3857** is negative, then the length of the string is
3858** the number of bytes up to the first zero terminator.
3859** If the fourth parameter to sqlite3_bind_blob() is negative, then
3860** the behavior is undefined.
3861** If a non-negative fourth parameter is provided to sqlite3_bind_text()
3862** or sqlite3_bind_text16() then that parameter must be the byte offset
3863** where the NUL terminator would occur assuming the string were NUL
3864** terminated.  If any NUL characters occur at byte offsets less than
3865** the value of the fourth parameter then the resulting string value will
3866** contain embedded NULs.  The result of expressions involving strings
3867** with embedded NULs is undefined.
3868**
3869** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
3870** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
3871** string after SQLite has finished with it.  ^The destructor is called
3872** to dispose of the BLOB or string even if the call to sqlite3_bind_blob(),
3873** sqlite3_bind_text(), or sqlite3_bind_text16() fails.
3874** ^If the fifth argument is
3875** the special value [SQLITE_STATIC], then SQLite assumes that the
3876** information is in static, unmanaged space and does not need to be freed.
3877** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
3878** SQLite makes its own private copy of the data immediately, before
3879** the sqlite3_bind_*() routine returns.
3880**
3881** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
3882** is filled with zeroes.  ^A zeroblob uses a fixed amount of memory
3883** (just an integer to hold its size) while it is being processed.
3884** Zeroblobs are intended to serve as placeholders for BLOBs whose
3885** content is later written using
3886** [sqlite3_blob_open | incremental BLOB I/O] routines.
3887** ^A negative value for the zeroblob results in a zero-length BLOB.
3888**
3889** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
3890** for the [prepared statement] or with a prepared statement for which
3891** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
3892** then the call will return [SQLITE_MISUSE].  If any sqlite3_bind_()
3893** routine is passed a [prepared statement] that has been finalized, the
3894** result is undefined and probably harmful.
3895**
3896** ^Bindings are not cleared by the [sqlite3_reset()] routine.
3897** ^Unbound parameters are interpreted as NULL.
3898**
3899** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
3900** [error code] if anything goes wrong.
3901** ^[SQLITE_RANGE] is returned if the parameter
3902** index is out of range.  ^[SQLITE_NOMEM] is returned if malloc() fails.
3903**
3904** See also: [sqlite3_bind_parameter_count()],
3905** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
3906*/
3907SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
3908SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
3909SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
3910SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
3911SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
3912SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
3913SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
3914SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
3915SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
3916
3917/*
3918** CAPI3REF: Number Of SQL Parameters
3919**
3920** ^This routine can be used to find the number of [SQL parameters]
3921** in a [prepared statement].  SQL parameters are tokens of the
3922** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
3923** placeholders for values that are [sqlite3_bind_blob | bound]
3924** to the parameters at a later time.
3925**
3926** ^(This routine actually returns the index of the largest (rightmost)
3927** parameter. For all forms except ?NNN, this will correspond to the
3928** number of unique parameters.  If parameters of the ?NNN form are used,
3929** there may be gaps in the list.)^
3930**
3931** See also: [sqlite3_bind_blob|sqlite3_bind()],
3932** [sqlite3_bind_parameter_name()], and
3933** [sqlite3_bind_parameter_index()].
3934*/
3935SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
3936
3937/*
3938** CAPI3REF: Name Of A Host Parameter
3939**
3940** ^The sqlite3_bind_parameter_name(P,N) interface returns
3941** the name of the N-th [SQL parameter] in the [prepared statement] P.
3942** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
3943** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
3944** respectively.
3945** In other words, the initial ":" or "$" or "@" or "?"
3946** is included as part of the name.)^
3947** ^Parameters of the form "?" without a following integer have no name
3948** and are referred to as "nameless" or "anonymous parameters".
3949**
3950** ^The first host parameter has an index of 1, not 0.
3951**
3952** ^If the value N is out of range or if the N-th parameter is
3953** nameless, then NULL is returned.  ^The returned string is
3954** always in UTF-8 encoding even if the named parameter was
3955** originally specified as UTF-16 in [sqlite3_prepare16()] or
3956** [sqlite3_prepare16_v2()].
3957**
3958** See also: [sqlite3_bind_blob|sqlite3_bind()],
3959** [sqlite3_bind_parameter_count()], and
3960** [sqlite3_bind_parameter_index()].
3961*/
3962SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
3963
3964/*
3965** CAPI3REF: Index Of A Parameter With A Given Name
3966**
3967** ^Return the index of an SQL parameter given its name.  ^The
3968** index value returned is suitable for use as the second
3969** parameter to [sqlite3_bind_blob|sqlite3_bind()].  ^A zero
3970** is returned if no matching parameter is found.  ^The parameter
3971** name must be given in UTF-8 even if the original statement
3972** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
3973**
3974** See also: [sqlite3_bind_blob|sqlite3_bind()],
3975** [sqlite3_bind_parameter_count()], and
3976** [sqlite3_bind_parameter_index()].
3977*/
3978SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
3979
3980/*
3981** CAPI3REF: Reset All Bindings On A Prepared Statement
3982**
3983** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
3984** the [sqlite3_bind_blob | bindings] on a [prepared statement].
3985** ^Use this routine to reset all host parameters to NULL.
3986*/
3987SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
3988
3989/*
3990** CAPI3REF: Number Of Columns In A Result Set
3991**
3992** ^Return the number of columns in the result set returned by the
3993** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
3994** statement that does not return data (for example an [UPDATE]).
3995**
3996** See also: [sqlite3_data_count()]
3997*/
3998SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
3999
4000/*
4001** CAPI3REF: Column Names In A Result Set
4002**
4003** ^These routines return the name assigned to a particular column
4004** in the result set of a [SELECT] statement.  ^The sqlite3_column_name()
4005** interface returns a pointer to a zero-terminated UTF-8 string
4006** and sqlite3_column_name16() returns a pointer to a zero-terminated
4007** UTF-16 string.  ^The first parameter is the [prepared statement]
4008** that implements the [SELECT] statement. ^The second parameter is the
4009** column number.  ^The leftmost column is number 0.
4010**
4011** ^The returned string pointer is valid until either the [prepared statement]
4012** is destroyed by [sqlite3_finalize()] or until the statement is automatically
4013** reprepared by the first call to [sqlite3_step()] for a particular run
4014** or until the next call to
4015** sqlite3_column_name() or sqlite3_column_name16() on the same column.
4016**
4017** ^If sqlite3_malloc() fails during the processing of either routine
4018** (for example during a conversion from UTF-8 to UTF-16) then a
4019** NULL pointer is returned.
4020**
4021** ^The name of a result column is the value of the "AS" clause for
4022** that column, if there is an AS clause.  If there is no AS clause
4023** then the name of the column is unspecified and may change from
4024** one release of SQLite to the next.
4025*/
4026SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
4027SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
4028
4029/*
4030** CAPI3REF: Source Of Data In A Query Result
4031**
4032** ^These routines provide a means to determine the database, table, and
4033** table column that is the origin of a particular result column in
4034** [SELECT] statement.
4035** ^The name of the database or table or column can be returned as
4036** either a UTF-8 or UTF-16 string.  ^The _database_ routines return
4037** the database name, the _table_ routines return the table name, and
4038** the origin_ routines return the column name.
4039** ^The returned string is valid until the [prepared statement] is destroyed
4040** using [sqlite3_finalize()] or until the statement is automatically
4041** reprepared by the first call to [sqlite3_step()] for a particular run
4042** or until the same information is requested
4043** again in a different encoding.
4044**
4045** ^The names returned are the original un-aliased names of the
4046** database, table, and column.
4047**
4048** ^The first argument to these interfaces is a [prepared statement].
4049** ^These functions return information about the Nth result column returned by
4050** the statement, where N is the second function argument.
4051** ^The left-most column is column 0 for these routines.
4052**
4053** ^If the Nth column returned by the statement is an expression or
4054** subquery and is not a column value, then all of these functions return
4055** NULL.  ^These routine might also return NULL if a memory allocation error
4056** occurs.  ^Otherwise, they return the name of the attached database, table,
4057** or column that query result column was extracted from.
4058**
4059** ^As with all other SQLite APIs, those whose names end with "16" return
4060** UTF-16 encoded strings and the other functions return UTF-8.
4061**
4062** ^These APIs are only available if the library was compiled with the
4063** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
4064**
4065** If two or more threads call one or more of these routines against the same
4066** prepared statement and column at the same time then the results are
4067** undefined.
4068**
4069** If two or more threads call one or more
4070** [sqlite3_column_database_name | column metadata interfaces]
4071** for the same [prepared statement] and result column
4072** at the same time then the results are undefined.
4073*/
4074SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
4075SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
4076SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
4077SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
4078SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
4079SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
4080
4081/*
4082** CAPI3REF: Declared Datatype Of A Query Result
4083**
4084** ^(The first parameter is a [prepared statement].
4085** If this statement is a [SELECT] statement and the Nth column of the
4086** returned result set of that [SELECT] is a table column (not an
4087** expression or subquery) then the declared type of the table
4088** column is returned.)^  ^If the Nth column of the result set is an
4089** expression or subquery, then a NULL pointer is returned.
4090** ^The returned string is always UTF-8 encoded.
4091**
4092** ^(For example, given the database schema:
4093**
4094** CREATE TABLE t1(c1 VARIANT);
4095**
4096** and the following statement to be compiled:
4097**
4098** SELECT c1 + 1, c1 FROM t1;
4099**
4100** this routine would return the string "VARIANT" for the second result
4101** column (i==1), and a NULL pointer for the first result column (i==0).)^
4102**
4103** ^SQLite uses dynamic run-time typing.  ^So just because a column
4104** is declared to contain a particular type does not mean that the
4105** data stored in that column is of the declared type.  SQLite is
4106** strongly typed, but the typing is dynamic not static.  ^Type
4107** is associated with individual values, not with the containers
4108** used to hold those values.
4109*/
4110SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
4111SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
4112
4113/*
4114** CAPI3REF: Evaluate An SQL Statement
4115**
4116** After a [prepared statement] has been prepared using either
4117** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
4118** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
4119** must be called one or more times to evaluate the statement.
4120**
4121** The details of the behavior of the sqlite3_step() interface depend
4122** on whether the statement was prepared using the newer "v2" interface
4123** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
4124** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
4125** new "v2" interface is recommended for new applications but the legacy
4126** interface will continue to be supported.
4127**
4128** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
4129** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
4130** ^With the "v2" interface, any of the other [result codes] or
4131** [extended result codes] might be returned as well.
4132**
4133** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
4134** database locks it needs to do its job.  ^If the statement is a [COMMIT]
4135** or occurs outside of an explicit transaction, then you can retry the
4136** statement.  If the statement is not a [COMMIT] and occurs within an
4137** explicit transaction then you should rollback the transaction before
4138** continuing.
4139**
4140** ^[SQLITE_DONE] means that the statement has finished executing
4141** successfully.  sqlite3_step() should not be called again on this virtual
4142** machine without first calling [sqlite3_reset()] to reset the virtual
4143** machine back to its initial state.
4144**
4145** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
4146** is returned each time a new row of data is ready for processing by the
4147** caller. The values may be accessed using the [column access functions].
4148** sqlite3_step() is called again to retrieve the next row of data.
4149**
4150** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
4151** violation) has occurred.  sqlite3_step() should not be called again on
4152** the VM. More information may be found by calling [sqlite3_errmsg()].
4153** ^With the legacy interface, a more specific error code (for example,
4154** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
4155** can be obtained by calling [sqlite3_reset()] on the
4156** [prepared statement].  ^In the "v2" interface,
4157** the more specific error code is returned directly by sqlite3_step().
4158**
4159** [SQLITE_MISUSE] means that the this routine was called inappropriately.
4160** Perhaps it was called on a [prepared statement] that has
4161** already been [sqlite3_finalize | finalized] or on one that had
4162** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
4163** be the case that the same database connection is being used by two or
4164** more threads at the same moment in time.
4165**
4166** For all versions of SQLite up to and including 3.6.23.1, a call to
4167** [sqlite3_reset()] was required after sqlite3_step() returned anything
4168** other than [SQLITE_ROW] before any subsequent invocation of
4169** sqlite3_step().  Failure to reset the prepared statement using
4170** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
4171** sqlite3_step().  But after version 3.6.23.1, sqlite3_step() began
4172** calling [sqlite3_reset()] automatically in this circumstance rather
4173** than returning [SQLITE_MISUSE].  This is not considered a compatibility
4174** break because any application that ever receives an SQLITE_MISUSE error
4175** is broken by definition.  The [SQLITE_OMIT_AUTORESET] compile-time option
4176** can be used to restore the legacy behavior.
4177**
4178** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
4179** API always returns a generic error code, [SQLITE_ERROR], following any
4180** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
4181** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
4182** specific [error codes] that better describes the error.
4183** We admit that this is a goofy design.  The problem has been fixed
4184** with the "v2" interface.  If you prepare all of your SQL statements
4185** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
4186** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
4187** then the more specific [error codes] are returned directly
4188** by sqlite3_step().  The use of the "v2" interface is recommended.
4189*/
4190SQLITE_API int sqlite3_step(sqlite3_stmt*);
4191
4192/*
4193** CAPI3REF: Number of columns in a result set
4194**
4195** ^The sqlite3_data_count(P) interface returns the number of columns in the
4196** current row of the result set of [prepared statement] P.
4197** ^If prepared statement P does not have results ready to return
4198** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
4199** interfaces) then sqlite3_data_count(P) returns 0.
4200** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
4201** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
4202** [sqlite3_step](P) returned [SQLITE_DONE].  ^The sqlite3_data_count(P)
4203** will return non-zero if previous call to [sqlite3_step](P) returned
4204** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
4205** where it always returns zero since each step of that multi-step
4206** pragma returns 0 columns of data.
4207**
4208** See also: [sqlite3_column_count()]
4209*/
4210SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
4211
4212/*
4213** CAPI3REF: Fundamental Datatypes
4214** KEYWORDS: SQLITE_TEXT
4215**
4216** ^(Every value in SQLite has one of five fundamental datatypes:
4217**
4218** <ul>
4219** <li> 64-bit signed integer
4220** <li> 64-bit IEEE floating point number
4221** <li> string
4222** <li> BLOB
4223** <li> NULL
4224** </ul>)^
4225**
4226** These constants are codes for each of those types.
4227**
4228** Note that the SQLITE_TEXT constant was also used in SQLite version 2
4229** for a completely different meaning.  Software that links against both
4230** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
4231** SQLITE_TEXT.
4232*/
4233#define SQLITE_INTEGER  1
4234#define SQLITE_FLOAT    2
4235#define SQLITE_BLOB     4
4236#define SQLITE_NULL     5
4237#ifdef SQLITE_TEXT
4238# undef SQLITE_TEXT
4239#else
4240# define SQLITE_TEXT     3
4241#endif
4242#define SQLITE3_TEXT     3
4243
4244/*
4245** CAPI3REF: Result Values From A Query
4246** KEYWORDS: {column access functions}
4247**
4248** These routines form the "result set" interface.
4249**
4250** ^These routines return information about a single column of the current
4251** result row of a query.  ^In every case the first argument is a pointer
4252** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
4253** that was returned from [sqlite3_prepare_v2()] or one of its variants)
4254** and the second argument is the index of the column for which information
4255** should be returned. ^The leftmost column of the result set has the index 0.
4256** ^The number of columns in the result can be determined using
4257** [sqlite3_column_count()].
4258**
4259** If the SQL statement does not currently point to a valid row, or if the
4260** column index is out of range, the result is undefined.
4261** These routines may only be called when the most recent call to
4262** [sqlite3_step()] has returned [SQLITE_ROW] and neither
4263** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
4264** If any of these routines are called after [sqlite3_reset()] or
4265** [sqlite3_finalize()] or after [sqlite3_step()] has returned
4266** something other than [SQLITE_ROW], the results are undefined.
4267** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
4268** are called from a different thread while any of these routines
4269** are pending, then the results are undefined.
4270**
4271** ^The sqlite3_column_type() routine returns the
4272** [SQLITE_INTEGER | datatype code] for the initial data type
4273** of the result column.  ^The returned value is one of [SQLITE_INTEGER],
4274** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
4275** returned by sqlite3_column_type() is only meaningful if no type
4276** conversions have occurred as described below.  After a type conversion,
4277** the value returned by sqlite3_column_type() is undefined.  Future
4278** versions of SQLite may change the behavior of sqlite3_column_type()
4279** following a type conversion.
4280**
4281** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
4282** routine returns the number of bytes in that BLOB or string.
4283** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
4284** the string to UTF-8 and then returns the number of bytes.
4285** ^If the result is a numeric value then sqlite3_column_bytes() uses
4286** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
4287** the number of bytes in that string.
4288** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
4289**
4290** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
4291** routine returns the number of bytes in that BLOB or string.
4292** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
4293** the string to UTF-16 and then returns the number of bytes.
4294** ^If the result is a numeric value then sqlite3_column_bytes16() uses
4295** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
4296** the number of bytes in that string.
4297** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
4298**
4299** ^The values returned by [sqlite3_column_bytes()] and
4300** [sqlite3_column_bytes16()] do not include the zero terminators at the end
4301** of the string.  ^For clarity: the values returned by
4302** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
4303** bytes in the string, not the number of characters.
4304**
4305** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
4306** even empty strings, are always zero-terminated.  ^The return
4307** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
4308**
4309** ^The object returned by [sqlite3_column_value()] is an
4310** [unprotected sqlite3_value] object.  An unprotected sqlite3_value object
4311** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
4312** If the [unprotected sqlite3_value] object returned by
4313** [sqlite3_column_value()] is used in any other way, including calls
4314** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
4315** or [sqlite3_value_bytes()], then the behavior is undefined.
4316**
4317** These routines attempt to convert the value where appropriate.  ^For
4318** example, if the internal representation is FLOAT and a text result
4319** is requested, [sqlite3_snprintf()] is used internally to perform the
4320** conversion automatically.  ^(The following table details the conversions
4321** that are applied:
4322**
4323** <blockquote>
4324** <table border="1">
4325** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
4326**
4327** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
4328** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
4329** <tr><td>  NULL    <td>   TEXT    <td> Result is NULL pointer
4330** <tr><td>  NULL    <td>   BLOB    <td> Result is NULL pointer
4331** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
4332** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
4333** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
4334** <tr><td>  FLOAT   <td> INTEGER   <td> Convert from float to integer
4335** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
4336** <tr><td>  FLOAT   <td>   BLOB    <td> Same as FLOAT->TEXT
4337** <tr><td>  TEXT    <td> INTEGER   <td> Use atoi()
4338** <tr><td>  TEXT    <td>  FLOAT    <td> Use atof()
4339** <tr><td>  TEXT    <td>   BLOB    <td> No change
4340** <tr><td>  BLOB    <td> INTEGER   <td> Convert to TEXT then use atoi()
4341** <tr><td>  BLOB    <td>  FLOAT    <td> Convert to TEXT then use atof()
4342** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
4343** </table>
4344** </blockquote>)^
4345**
4346** The table above makes reference to standard C library functions atoi()
4347** and atof().  SQLite does not really use these functions.  It has its
4348** own equivalent internal routines.  The atoi() and atof() names are
4349** used in the table for brevity and because they are familiar to most
4350** C programmers.
4351**
4352** Note that when type conversions occur, pointers returned by prior
4353** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
4354** sqlite3_column_text16() may be invalidated.
4355** Type conversions and pointer invalidations might occur
4356** in the following cases:
4357**
4358** <ul>
4359** <li> The initial content is a BLOB and sqlite3_column_text() or
4360**      sqlite3_column_text16() is called.  A zero-terminator might
4361**      need to be added to the string.</li>
4362** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
4363**      sqlite3_column_text16() is called.  The content must be converted
4364**      to UTF-16.</li>
4365** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
4366**      sqlite3_column_text() is called.  The content must be converted
4367**      to UTF-8.</li>
4368** </ul>
4369**
4370** ^Conversions between UTF-16be and UTF-16le are always done in place and do
4371** not invalidate a prior pointer, though of course the content of the buffer
4372** that the prior pointer references will have been modified.  Other kinds
4373** of conversion are done in place when it is possible, but sometimes they
4374** are not possible and in those cases prior pointers are invalidated.
4375**
4376** The safest and easiest to remember policy is to invoke these routines
4377** in one of the following ways:
4378**
4379** <ul>
4380**  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
4381**  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
4382**  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
4383** </ul>
4384**
4385** In other words, you should call sqlite3_column_text(),
4386** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
4387** into the desired format, then invoke sqlite3_column_bytes() or
4388** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls
4389** to sqlite3_column_text() or sqlite3_column_blob() with calls to
4390** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
4391** with calls to sqlite3_column_bytes().
4392**
4393** ^The pointers returned are valid until a type conversion occurs as
4394** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
4395** [sqlite3_finalize()] is called.  ^The memory space used to hold strings
4396** and BLOBs is freed automatically.  Do <b>not</b> pass the pointers returned
4397** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
4398** [sqlite3_free()].
4399**
4400** ^(If a memory allocation error occurs during the evaluation of any
4401** of these routines, a default value is returned.  The default value
4402** is either the integer 0, the floating point number 0.0, or a NULL
4403** pointer.  Subsequent calls to [sqlite3_errcode()] will return
4404** [SQLITE_NOMEM].)^
4405*/
4406SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
4407SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
4408SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
4409SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
4410SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
4411SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
4412SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
4413SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
4414SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
4415SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
4416
4417/*
4418** CAPI3REF: Destroy A Prepared Statement Object
4419**
4420** ^The sqlite3_finalize() function is called to delete a [prepared statement].
4421** ^If the most recent evaluation of the statement encountered no errors
4422** or if the statement is never been evaluated, then sqlite3_finalize() returns
4423** SQLITE_OK.  ^If the most recent evaluation of statement S failed, then
4424** sqlite3_finalize(S) returns the appropriate [error code] or
4425** [extended error code].
4426**
4427** ^The sqlite3_finalize(S) routine can be called at any point during
4428** the life cycle of [prepared statement] S:
4429** before statement S is ever evaluated, after
4430** one or more calls to [sqlite3_reset()], or after any call
4431** to [sqlite3_step()] regardless of whether or not the statement has
4432** completed execution.
4433**
4434** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
4435**
4436** The application must finalize every [prepared statement] in order to avoid
4437** resource leaks.  It is a grievous error for the application to try to use
4438** a prepared statement after it has been finalized.  Any use of a prepared
4439** statement after it has been finalized can result in undefined and
4440** undesirable behavior such as segfaults and heap corruption.
4441*/
4442SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
4443
4444/*
4445** CAPI3REF: Reset A Prepared Statement Object
4446**
4447** The sqlite3_reset() function is called to reset a [prepared statement]
4448** object back to its initial state, ready to be re-executed.
4449** ^Any SQL statement variables that had values bound to them using
4450** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
4451** Use [sqlite3_clear_bindings()] to reset the bindings.
4452**
4453** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
4454** back to the beginning of its program.
4455**
4456** ^If the most recent call to [sqlite3_step(S)] for the
4457** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
4458** or if [sqlite3_step(S)] has never before been called on S,
4459** then [sqlite3_reset(S)] returns [SQLITE_OK].
4460**
4461** ^If the most recent call to [sqlite3_step(S)] for the
4462** [prepared statement] S indicated an error, then
4463** [sqlite3_reset(S)] returns an appropriate [error code].
4464**
4465** ^The [sqlite3_reset(S)] interface does not change the values
4466** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
4467*/
4468SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
4469
4470/*
4471** CAPI3REF: Create Or Redefine SQL Functions
4472** KEYWORDS: {function creation routines}
4473** KEYWORDS: {application-defined SQL function}
4474** KEYWORDS: {application-defined SQL functions}
4475**
4476** ^These functions (collectively known as "function creation routines")
4477** are used to add SQL functions or aggregates or to redefine the behavior
4478** of existing SQL functions or aggregates.  The only differences between
4479** these routines are the text encoding expected for
4480** the second parameter (the name of the function being created)
4481** and the presence or absence of a destructor callback for
4482** the application data pointer.
4483**
4484** ^The first parameter is the [database connection] to which the SQL
4485** function is to be added.  ^If an application uses more than one database
4486** connection then application-defined SQL functions must be added
4487** to each database connection separately.
4488**
4489** ^The second parameter is the name of the SQL function to be created or
4490** redefined.  ^The length of the name is limited to 255 bytes in a UTF-8
4491** representation, exclusive of the zero-terminator.  ^Note that the name
4492** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
4493** ^Any attempt to create a function with a longer name
4494** will result in [SQLITE_MISUSE] being returned.
4495**
4496** ^The third parameter (nArg)
4497** is the number of arguments that the SQL function or
4498** aggregate takes. ^If this parameter is -1, then the SQL function or
4499** aggregate may take any number of arguments between 0 and the limit
4500** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]).  If the third
4501** parameter is less than -1 or greater than 127 then the behavior is
4502** undefined.
4503**
4504** ^The fourth parameter, eTextRep, specifies what
4505** [SQLITE_UTF8 | text encoding] this SQL function prefers for
4506** its parameters.  Every SQL function implementation must be able to work
4507** with UTF-8, UTF-16le, or UTF-16be.  But some implementations may be
4508** more efficient with one encoding than another.  ^An application may
4509** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
4510** times with the same function but with different values of eTextRep.
4511** ^When multiple implementations of the same function are available, SQLite
4512** will pick the one that involves the least amount of data conversion.
4513** If there is only a single implementation which does not care what text
4514** encoding is used, then the fourth argument should be [SQLITE_ANY].
4515**
4516** ^(The fifth parameter is an arbitrary pointer.  The implementation of the
4517** function can gain access to this pointer using [sqlite3_user_data()].)^
4518**
4519** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
4520** pointers to C-language functions that implement the SQL function or
4521** aggregate. ^A scalar SQL function requires an implementation of the xFunc
4522** callback only; NULL pointers must be passed as the xStep and xFinal
4523** parameters. ^An aggregate SQL function requires an implementation of xStep
4524** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
4525** SQL function or aggregate, pass NULL pointers for all three function
4526** callbacks.
4527**
4528** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
4529** then it is destructor for the application data pointer.
4530** The destructor is invoked when the function is deleted, either by being
4531** overloaded or when the database connection closes.)^
4532** ^The destructor is also invoked if the call to
4533** sqlite3_create_function_v2() fails.
4534** ^When the destructor callback of the tenth parameter is invoked, it
4535** is passed a single argument which is a copy of the application data
4536** pointer which was the fifth parameter to sqlite3_create_function_v2().
4537**
4538** ^It is permitted to register multiple implementations of the same
4539** functions with the same name but with either differing numbers of
4540** arguments or differing preferred text encodings.  ^SQLite will use
4541** the implementation that most closely matches the way in which the
4542** SQL function is used.  ^A function implementation with a non-negative
4543** nArg parameter is a better match than a function implementation with
4544** a negative nArg.  ^A function where the preferred text encoding
4545** matches the database encoding is a better
4546** match than a function where the encoding is different.
4547** ^A function where the encoding difference is between UTF16le and UTF16be
4548** is a closer match than a function where the encoding difference is
4549** between UTF8 and UTF16.
4550**
4551** ^Built-in functions may be overloaded by new application-defined functions.
4552**
4553** ^An application-defined function is permitted to call other
4554** SQLite interfaces.  However, such calls must not
4555** close the database connection nor finalize or reset the prepared
4556** statement in which the function is running.
4557*/
4558SQLITE_API int sqlite3_create_function(
4559  sqlite3 *db,
4560  const char *zFunctionName,
4561  int nArg,
4562  int eTextRep,
4563  void *pApp,
4564  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4565  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4566  void (*xFinal)(sqlite3_context*)
4567);
4568SQLITE_API int sqlite3_create_function16(
4569  sqlite3 *db,
4570  const void *zFunctionName,
4571  int nArg,
4572  int eTextRep,
4573  void *pApp,
4574  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4575  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4576  void (*xFinal)(sqlite3_context*)
4577);
4578SQLITE_API int sqlite3_create_function_v2(
4579  sqlite3 *db,
4580  const char *zFunctionName,
4581  int nArg,
4582  int eTextRep,
4583  void *pApp,
4584  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4585  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4586  void (*xFinal)(sqlite3_context*),
4587  void(*xDestroy)(void*)
4588);
4589
4590/*
4591** CAPI3REF: Text Encodings
4592**
4593** These constant define integer codes that represent the various
4594** text encodings supported by SQLite.
4595*/
4596#define SQLITE_UTF8           1
4597#define SQLITE_UTF16LE        2
4598#define SQLITE_UTF16BE        3
4599#define SQLITE_UTF16          4    /* Use native byte order */
4600#define SQLITE_ANY            5    /* sqlite3_create_function only */
4601#define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
4602
4603/*
4604** CAPI3REF: Deprecated Functions
4605** DEPRECATED
4606**
4607** These functions are [deprecated].  In order to maintain
4608** backwards compatibility with older code, these functions continue
4609** to be supported.  However, new applications should avoid
4610** the use of these functions.  To help encourage people to avoid
4611** using these functions, we are not going to tell you what they do.
4612*/
4613#ifndef SQLITE_OMIT_DEPRECATED
4614SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
4615SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
4616SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
4617SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
4618SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
4619SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),
4620                      void*,sqlite3_int64);
4621#endif
4622
4623/*
4624** CAPI3REF: Obtaining SQL Function Parameter Values
4625**
4626** The C-language implementation of SQL functions and aggregates uses
4627** this set of interface routines to access the parameter values on
4628** the function or aggregate.
4629**
4630** The xFunc (for scalar functions) or xStep (for aggregates) parameters
4631** to [sqlite3_create_function()] and [sqlite3_create_function16()]
4632** define callbacks that implement the SQL functions and aggregates.
4633** The 3rd parameter to these callbacks is an array of pointers to
4634** [protected sqlite3_value] objects.  There is one [sqlite3_value] object for
4635** each parameter to the SQL function.  These routines are used to
4636** extract values from the [sqlite3_value] objects.
4637**
4638** These routines work only with [protected sqlite3_value] objects.
4639** Any attempt to use these routines on an [unprotected sqlite3_value]
4640** object results in undefined behavior.
4641**
4642** ^These routines work just like the corresponding [column access functions]
4643** except that  these routines take a single [protected sqlite3_value] object
4644** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
4645**
4646** ^The sqlite3_value_text16() interface extracts a UTF-16 string
4647** in the native byte-order of the host machine.  ^The
4648** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
4649** extract UTF-16 strings as big-endian and little-endian respectively.
4650**
4651** ^(The sqlite3_value_numeric_type() interface attempts to apply
4652** numeric affinity to the value.  This means that an attempt is
4653** made to convert the value to an integer or floating point.  If
4654** such a conversion is possible without loss of information (in other
4655** words, if the value is a string that looks like a number)
4656** then the conversion is performed.  Otherwise no conversion occurs.
4657** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
4658**
4659** Please pay particular attention to the fact that the pointer returned
4660** from [sqlite3_value_blob()], [sqlite3_value_text()], or
4661** [sqlite3_value_text16()] can be invalidated by a subsequent call to
4662** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
4663** or [sqlite3_value_text16()].
4664**
4665** These routines must be called from the same thread as
4666** the SQL function that supplied the [sqlite3_value*] parameters.
4667*/
4668SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
4669SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
4670SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
4671SQLITE_API double sqlite3_value_double(sqlite3_value*);
4672SQLITE_API int sqlite3_value_int(sqlite3_value*);
4673SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
4674SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
4675SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
4676SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
4677SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
4678SQLITE_API int sqlite3_value_type(sqlite3_value*);
4679SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
4680
4681/*
4682** CAPI3REF: Obtain Aggregate Function Context
4683**
4684** Implementations of aggregate SQL functions use this
4685** routine to allocate memory for storing their state.
4686**
4687** ^The first time the sqlite3_aggregate_context(C,N) routine is called
4688** for a particular aggregate function, SQLite
4689** allocates N of memory, zeroes out that memory, and returns a pointer
4690** to the new memory. ^On second and subsequent calls to
4691** sqlite3_aggregate_context() for the same aggregate function instance,
4692** the same buffer is returned.  Sqlite3_aggregate_context() is normally
4693** called once for each invocation of the xStep callback and then one
4694** last time when the xFinal callback is invoked.  ^(When no rows match
4695** an aggregate query, the xStep() callback of the aggregate function
4696** implementation is never called and xFinal() is called exactly once.
4697** In those cases, sqlite3_aggregate_context() might be called for the
4698** first time from within xFinal().)^
4699**
4700** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer
4701** when first called if N is less than or equal to zero or if a memory
4702** allocate error occurs.
4703**
4704** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
4705** determined by the N parameter on first successful call.  Changing the
4706** value of N in subsequent call to sqlite3_aggregate_context() within
4707** the same aggregate function instance will not resize the memory
4708** allocation.)^  Within the xFinal callback, it is customary to set
4709** N=0 in calls to sqlite3_aggregate_context(C,N) so that no
4710** pointless memory allocations occur.
4711**
4712** ^SQLite automatically frees the memory allocated by
4713** sqlite3_aggregate_context() when the aggregate query concludes.
4714**
4715** The first parameter must be a copy of the
4716** [sqlite3_context | SQL function context] that is the first parameter
4717** to the xStep or xFinal callback routine that implements the aggregate
4718** function.
4719**
4720** This routine must be called from the same thread in which
4721** the aggregate SQL function is running.
4722*/
4723SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
4724
4725/*
4726** CAPI3REF: User Data For Functions
4727**
4728** ^The sqlite3_user_data() interface returns a copy of
4729** the pointer that was the pUserData parameter (the 5th parameter)
4730** of the [sqlite3_create_function()]
4731** and [sqlite3_create_function16()] routines that originally
4732** registered the application defined function.
4733**
4734** This routine must be called from the same thread in which
4735** the application-defined function is running.
4736*/
4737SQLITE_API void *sqlite3_user_data(sqlite3_context*);
4738
4739/*
4740** CAPI3REF: Database Connection For Functions
4741**
4742** ^The sqlite3_context_db_handle() interface returns a copy of
4743** the pointer to the [database connection] (the 1st parameter)
4744** of the [sqlite3_create_function()]
4745** and [sqlite3_create_function16()] routines that originally
4746** registered the application defined function.
4747*/
4748SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
4749
4750/*
4751** CAPI3REF: Function Auxiliary Data
4752**
4753** The following two functions may be used by scalar SQL functions to
4754** associate metadata with argument values. If the same value is passed to
4755** multiple invocations of the same SQL function during query execution, under
4756** some circumstances the associated metadata may be preserved. This may
4757** be used, for example, to add a regular-expression matching scalar
4758** function. The compiled version of the regular expression is stored as
4759** metadata associated with the SQL value passed as the regular expression
4760** pattern.  The compiled regular expression can be reused on multiple
4761** invocations of the same function so that the original pattern string
4762** does not need to be recompiled on each invocation.
4763**
4764** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
4765** associated by the sqlite3_set_auxdata() function with the Nth argument
4766** value to the application-defined function. ^If no metadata has been ever
4767** been set for the Nth argument of the function, or if the corresponding
4768** function parameter has changed since the meta-data was set,
4769** then sqlite3_get_auxdata() returns a NULL pointer.
4770**
4771** ^The sqlite3_set_auxdata() interface saves the metadata
4772** pointed to by its 3rd parameter as the metadata for the N-th
4773** argument of the application-defined function.  Subsequent
4774** calls to sqlite3_get_auxdata() might return this data, if it has
4775** not been destroyed.
4776** ^If it is not NULL, SQLite will invoke the destructor
4777** function given by the 4th parameter to sqlite3_set_auxdata() on
4778** the metadata when the corresponding function parameter changes
4779** or when the SQL statement completes, whichever comes first.
4780**
4781** SQLite is free to call the destructor and drop metadata on any
4782** parameter of any function at any time.  ^The only guarantee is that
4783** the destructor will be called before the metadata is dropped.
4784**
4785** ^(In practice, metadata is preserved between function calls for
4786** expressions that are constant at compile time. This includes literal
4787** values and [parameters].)^
4788**
4789** These routines must be called from the same thread in which
4790** the SQL function is running.
4791*/
4792SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
4793SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
4794
4795
4796/*
4797** CAPI3REF: Constants Defining Special Destructor Behavior
4798**
4799** These are special values for the destructor that is passed in as the
4800** final argument to routines like [sqlite3_result_blob()].  ^If the destructor
4801** argument is SQLITE_STATIC, it means that the content pointer is constant
4802** and will never change.  It does not need to be destroyed.  ^The
4803** SQLITE_TRANSIENT value means that the content will likely change in
4804** the near future and that SQLite should make its own private copy of
4805** the content before returning.
4806**
4807** The typedef is necessary to work around problems in certain
4808** C++ compilers.
4809*/
4810typedef void (*sqlite3_destructor_type)(void*);
4811#define SQLITE_STATIC      ((sqlite3_destructor_type)0)
4812#define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
4813
4814/*
4815** CAPI3REF: Setting The Result Of An SQL Function
4816**
4817** These routines are used by the xFunc or xFinal callbacks that
4818** implement SQL functions and aggregates.  See
4819** [sqlite3_create_function()] and [sqlite3_create_function16()]
4820** for additional information.
4821**
4822** These functions work very much like the [parameter binding] family of
4823** functions used to bind values to host parameters in prepared statements.
4824** Refer to the [SQL parameter] documentation for additional information.
4825**
4826** ^The sqlite3_result_blob() interface sets the result from
4827** an application-defined function to be the BLOB whose content is pointed
4828** to by the second parameter and which is N bytes long where N is the
4829** third parameter.
4830**
4831** ^The sqlite3_result_zeroblob() interfaces set the result of
4832** the application-defined function to be a BLOB containing all zero
4833** bytes and N bytes in size, where N is the value of the 2nd parameter.
4834**
4835** ^The sqlite3_result_double() interface sets the result from
4836** an application-defined function to be a floating point value specified
4837** by its 2nd argument.
4838**
4839** ^The sqlite3_result_error() and sqlite3_result_error16() functions
4840** cause the implemented SQL function to throw an exception.
4841** ^SQLite uses the string pointed to by the
4842** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
4843** as the text of an error message.  ^SQLite interprets the error
4844** message string from sqlite3_result_error() as UTF-8. ^SQLite
4845** interprets the string from sqlite3_result_error16() as UTF-16 in native
4846** byte order.  ^If the third parameter to sqlite3_result_error()
4847** or sqlite3_result_error16() is negative then SQLite takes as the error
4848** message all text up through the first zero character.
4849** ^If the third parameter to sqlite3_result_error() or
4850** sqlite3_result_error16() is non-negative then SQLite takes that many
4851** bytes (not characters) from the 2nd parameter as the error message.
4852** ^The sqlite3_result_error() and sqlite3_result_error16()
4853** routines make a private copy of the error message text before
4854** they return.  Hence, the calling function can deallocate or
4855** modify the text after they return without harm.
4856** ^The sqlite3_result_error_code() function changes the error code
4857** returned by SQLite as a result of an error in a function.  ^By default,
4858** the error code is SQLITE_ERROR.  ^A subsequent call to sqlite3_result_error()
4859** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
4860**
4861** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
4862** error indicating that a string or BLOB is too long to represent.
4863**
4864** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
4865** error indicating that a memory allocation failed.
4866**
4867** ^The sqlite3_result_int() interface sets the return value
4868** of the application-defined function to be the 32-bit signed integer
4869** value given in the 2nd argument.
4870** ^The sqlite3_result_int64() interface sets the return value
4871** of the application-defined function to be the 64-bit signed integer
4872** value given in the 2nd argument.
4873**
4874** ^The sqlite3_result_null() interface sets the return value
4875** of the application-defined function to be NULL.
4876**
4877** ^The sqlite3_result_text(), sqlite3_result_text16(),
4878** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
4879** set the return value of the application-defined function to be
4880** a text string which is represented as UTF-8, UTF-16 native byte order,
4881** UTF-16 little endian, or UTF-16 big endian, respectively.
4882** ^SQLite takes the text result from the application from
4883** the 2nd parameter of the sqlite3_result_text* interfaces.
4884** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4885** is negative, then SQLite takes result text from the 2nd parameter
4886** through the first zero character.
4887** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4888** is non-negative, then as many bytes (not characters) of the text
4889** pointed to by the 2nd parameter are taken as the application-defined
4890** function result.  If the 3rd parameter is non-negative, then it
4891** must be the byte offset into the string where the NUL terminator would
4892** appear if the string where NUL terminated.  If any NUL characters occur
4893** in the string at a byte offset that is less than the value of the 3rd
4894** parameter, then the resulting string will contain embedded NULs and the
4895** result of expressions operating on strings with embedded NULs is undefined.
4896** ^If the 4th parameter to the sqlite3_result_text* interfaces
4897** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
4898** function as the destructor on the text or BLOB result when it has
4899** finished using that result.
4900** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
4901** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
4902** assumes that the text or BLOB result is in constant space and does not
4903** copy the content of the parameter nor call a destructor on the content
4904** when it has finished using that result.
4905** ^If the 4th parameter to the sqlite3_result_text* interfaces
4906** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
4907** then SQLite makes a copy of the result into space obtained from
4908** from [sqlite3_malloc()] before it returns.
4909**
4910** ^The sqlite3_result_value() interface sets the result of
4911** the application-defined function to be a copy the
4912** [unprotected sqlite3_value] object specified by the 2nd parameter.  ^The
4913** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
4914** so that the [sqlite3_value] specified in the parameter may change or
4915** be deallocated after sqlite3_result_value() returns without harm.
4916** ^A [protected sqlite3_value] object may always be used where an
4917** [unprotected sqlite3_value] object is required, so either
4918** kind of [sqlite3_value] object can be used with this interface.
4919**
4920** If these routines are called from within the different thread
4921** than the one containing the application-defined function that received
4922** the [sqlite3_context] pointer, the results are undefined.
4923*/
4924SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
4925SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
4926SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
4927SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
4928SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
4929SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
4930SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
4931SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
4932SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
4933SQLITE_API void sqlite3_result_null(sqlite3_context*);
4934SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
4935SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
4936SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
4937SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
4938SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
4939SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
4940
4941/*
4942** CAPI3REF: Define New Collating Sequences
4943**
4944** ^These functions add, remove, or modify a [collation] associated
4945** with the [database connection] specified as the first argument.
4946**
4947** ^The name of the collation is a UTF-8 string
4948** for sqlite3_create_collation() and sqlite3_create_collation_v2()
4949** and a UTF-16 string in native byte order for sqlite3_create_collation16().
4950** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
4951** considered to be the same name.
4952**
4953** ^(The third argument (eTextRep) must be one of the constants:
4954** <ul>
4955** <li> [SQLITE_UTF8],
4956** <li> [SQLITE_UTF16LE],
4957** <li> [SQLITE_UTF16BE],
4958** <li> [SQLITE_UTF16], or
4959** <li> [SQLITE_UTF16_ALIGNED].
4960** </ul>)^
4961** ^The eTextRep argument determines the encoding of strings passed
4962** to the collating function callback, xCallback.
4963** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
4964** force strings to be UTF16 with native byte order.
4965** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
4966** on an even byte address.
4967**
4968** ^The fourth argument, pArg, is an application data pointer that is passed
4969** through as the first argument to the collating function callback.
4970**
4971** ^The fifth argument, xCallback, is a pointer to the collating function.
4972** ^Multiple collating functions can be registered using the same name but
4973** with different eTextRep parameters and SQLite will use whichever
4974** function requires the least amount of data transformation.
4975** ^If the xCallback argument is NULL then the collating function is
4976** deleted.  ^When all collating functions having the same name are deleted,
4977** that collation is no longer usable.
4978**
4979** ^The collating function callback is invoked with a copy of the pArg
4980** application data pointer and with two strings in the encoding specified
4981** by the eTextRep argument.  The collating function must return an
4982** integer that is negative, zero, or positive
4983** if the first string is less than, equal to, or greater than the second,
4984** respectively.  A collating function must always return the same answer
4985** given the same inputs.  If two or more collating functions are registered
4986** to the same collation name (using different eTextRep values) then all
4987** must give an equivalent answer when invoked with equivalent strings.
4988** The collating function must obey the following properties for all
4989** strings A, B, and C:
4990**
4991** <ol>
4992** <li> If A==B then B==A.
4993** <li> If A==B and B==C then A==C.
4994** <li> If A&lt;B THEN B&gt;A.
4995** <li> If A&lt;B and B&lt;C then A&lt;C.
4996** </ol>
4997**
4998** If a collating function fails any of the above constraints and that
4999** collating function is  registered and used, then the behavior of SQLite
5000** is undefined.
5001**
5002** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
5003** with the addition that the xDestroy callback is invoked on pArg when
5004** the collating function is deleted.
5005** ^Collating functions are deleted when they are overridden by later
5006** calls to the collation creation functions or when the
5007** [database connection] is closed using [sqlite3_close()].
5008**
5009** ^The xDestroy callback is <u>not</u> called if the
5010** sqlite3_create_collation_v2() function fails.  Applications that invoke
5011** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
5012** check the return code and dispose of the application data pointer
5013** themselves rather than expecting SQLite to deal with it for them.
5014** This is different from every other SQLite interface.  The inconsistency
5015** is unfortunate but cannot be changed without breaking backwards
5016** compatibility.
5017**
5018** See also:  [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
5019*/
5020SQLITE_API int sqlite3_create_collation(
5021  sqlite3*,
5022  const char *zName,
5023  int eTextRep,
5024  void *pArg,
5025  int(*xCompare)(void*,int,const void*,int,const void*)
5026);
5027SQLITE_API int sqlite3_create_collation_v2(
5028  sqlite3*,
5029  const char *zName,
5030  int eTextRep,
5031  void *pArg,
5032  int(*xCompare)(void*,int,const void*,int,const void*),
5033  void(*xDestroy)(void*)
5034);
5035SQLITE_API int sqlite3_create_collation16(
5036  sqlite3*,
5037  const void *zName,
5038  int eTextRep,
5039  void *pArg,
5040  int(*xCompare)(void*,int,const void*,int,const void*)
5041);
5042
5043/*
5044** CAPI3REF: Collation Needed Callbacks
5045**
5046** ^To avoid having to register all collation sequences before a database
5047** can be used, a single callback function may be registered with the
5048** [database connection] to be invoked whenever an undefined collation
5049** sequence is required.
5050**
5051** ^If the function is registered using the sqlite3_collation_needed() API,
5052** then it is passed the names of undefined collation sequences as strings
5053** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
5054** the names are passed as UTF-16 in machine native byte order.
5055** ^A call to either function replaces the existing collation-needed callback.
5056**
5057** ^(When the callback is invoked, the first argument passed is a copy
5058** of the second argument to sqlite3_collation_needed() or
5059** sqlite3_collation_needed16().  The second argument is the database
5060** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
5061** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
5062** sequence function required.  The fourth parameter is the name of the
5063** required collation sequence.)^
5064**
5065** The callback function should register the desired collation using
5066** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
5067** [sqlite3_create_collation_v2()].
5068*/
5069SQLITE_API int sqlite3_collation_needed(
5070  sqlite3*,
5071  void*,
5072  void(*)(void*,sqlite3*,int eTextRep,const char*)
5073);
5074SQLITE_API int sqlite3_collation_needed16(
5075  sqlite3*,
5076  void*,
5077  void(*)(void*,sqlite3*,int eTextRep,const void*)
5078);
5079
5080#ifdef SQLITE_HAS_CODEC
5081/*
5082** Specify the key for an encrypted database.  This routine should be
5083** called right after sqlite3_open().
5084**
5085** The code to implement this API is not available in the public release
5086** of SQLite.
5087*/
5088SQLITE_API int sqlite3_key(
5089  sqlite3 *db,                   /* Database to be rekeyed */
5090  const void *pKey, int nKey     /* The key */
5091);
5092
5093/*
5094** Change the key on an open database.  If the current database is not
5095** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
5096** database is decrypted.
5097**
5098** The code to implement this API is not available in the public release
5099** of SQLite.
5100*/
5101SQLITE_API int sqlite3_rekey(
5102  sqlite3 *db,                   /* Database to be rekeyed */
5103  const void *pKey, int nKey     /* The new key */
5104);
5105
5106/*
5107** Specify the activation key for a SEE database.  Unless
5108** activated, none of the SEE routines will work.
5109*/
5110SQLITE_API void sqlite3_activate_see(
5111  const char *zPassPhrase        /* Activation phrase */
5112);
5113#endif
5114
5115#ifdef SQLITE_ENABLE_CEROD
5116/*
5117** Specify the activation key for a CEROD database.  Unless
5118** activated, none of the CEROD routines will work.
5119*/
5120SQLITE_API void sqlite3_activate_cerod(
5121  const char *zPassPhrase        /* Activation phrase */
5122);
5123#endif
5124
5125/*
5126** CAPI3REF: Suspend Execution For A Short Time
5127**
5128** The sqlite3_sleep() function causes the current thread to suspend execution
5129** for at least a number of milliseconds specified in its parameter.
5130**
5131** If the operating system does not support sleep requests with
5132** millisecond time resolution, then the time will be rounded up to
5133** the nearest second. The number of milliseconds of sleep actually
5134** requested from the operating system is returned.
5135**
5136** ^SQLite implements this interface by calling the xSleep()
5137** method of the default [sqlite3_vfs] object.  If the xSleep() method
5138** of the default VFS is not implemented correctly, or not implemented at
5139** all, then the behavior of sqlite3_sleep() may deviate from the description
5140** in the previous paragraphs.
5141*/
5142SQLITE_API int sqlite3_sleep(int);
5143
5144/*
5145** CAPI3REF: Name Of The Folder Holding Temporary Files
5146**
5147** ^(If this global variable is made to point to a string which is
5148** the name of a folder (a.k.a. directory), then all temporary files
5149** created by SQLite when using a built-in [sqlite3_vfs | VFS]
5150** will be placed in that directory.)^  ^If this variable
5151** is a NULL pointer, then SQLite performs a search for an appropriate
5152** temporary file directory.
5153**
5154** It is not safe to read or modify this variable in more than one
5155** thread at a time.  It is not safe to read or modify this variable
5156** if a [database connection] is being used at the same time in a separate
5157** thread.
5158** It is intended that this variable be set once
5159** as part of process initialization and before any SQLite interface
5160** routines have been called and that this variable remain unchanged
5161** thereafter.
5162**
5163** ^The [temp_store_directory pragma] may modify this variable and cause
5164** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
5165** the [temp_store_directory pragma] always assumes that any string
5166** that this variable points to is held in memory obtained from
5167** [sqlite3_malloc] and the pragma may attempt to free that memory
5168** using [sqlite3_free].
5169** Hence, if this variable is modified directly, either it should be
5170** made NULL or made to point to memory obtained from [sqlite3_malloc]
5171** or else the use of the [temp_store_directory pragma] should be avoided.
5172**
5173** <b>Note to Windows Runtime users:</b>  The temporary directory must be set
5174** prior to calling [sqlite3_open] or [sqlite3_open_v2].  Otherwise, various
5175** features that require the use of temporary files may fail.  Here is an
5176** example of how to do this using C++ with the Windows Runtime:
5177**
5178** <blockquote><pre>
5179** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
5180** &nbsp;     TemporaryFolder->Path->Data();
5181** char zPathBuf&#91;MAX_PATH + 1&#93;;
5182** memset(zPathBuf, 0, sizeof(zPathBuf));
5183** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
5184** &nbsp;     NULL, NULL);
5185** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
5186** </pre></blockquote>
5187*/
5188SQLITE_API char *sqlite3_temp_directory;
5189
5190/*
5191** CAPI3REF: Name Of The Folder Holding Database Files
5192**
5193** ^(If this global variable is made to point to a string which is
5194** the name of a folder (a.k.a. directory), then all database files
5195** specified with a relative pathname and created or accessed by
5196** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
5197** to be relative to that directory.)^ ^If this variable is a NULL
5198** pointer, then SQLite assumes that all database files specified
5199** with a relative pathname are relative to the current directory
5200** for the process.  Only the windows VFS makes use of this global
5201** variable; it is ignored by the unix VFS.
5202**
5203** Changing the value of this variable while a database connection is
5204** open can result in a corrupt database.
5205**
5206** It is not safe to read or modify this variable in more than one
5207** thread at a time.  It is not safe to read or modify this variable
5208** if a [database connection] is being used at the same time in a separate
5209** thread.
5210** It is intended that this variable be set once
5211** as part of process initialization and before any SQLite interface
5212** routines have been called and that this variable remain unchanged
5213** thereafter.
5214**
5215** ^The [data_store_directory pragma] may modify this variable and cause
5216** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
5217** the [data_store_directory pragma] always assumes that any string
5218** that this variable points to is held in memory obtained from
5219** [sqlite3_malloc] and the pragma may attempt to free that memory
5220** using [sqlite3_free].
5221** Hence, if this variable is modified directly, either it should be
5222** made NULL or made to point to memory obtained from [sqlite3_malloc]
5223** or else the use of the [data_store_directory pragma] should be avoided.
5224*/
5225SQLITE_API char *sqlite3_data_directory;
5226
5227/*
5228** CAPI3REF: Test For Auto-Commit Mode
5229** KEYWORDS: {autocommit mode}
5230**
5231** ^The sqlite3_get_autocommit() interface returns non-zero or
5232** zero if the given database connection is or is not in autocommit mode,
5233** respectively.  ^Autocommit mode is on by default.
5234** ^Autocommit mode is disabled by a [BEGIN] statement.
5235** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
5236**
5237** If certain kinds of errors occur on a statement within a multi-statement
5238** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
5239** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
5240** transaction might be rolled back automatically.  The only way to
5241** find out whether SQLite automatically rolled back the transaction after
5242** an error is to use this function.
5243**
5244** If another thread changes the autocommit status of the database
5245** connection while this routine is running, then the return value
5246** is undefined.
5247*/
5248SQLITE_API int sqlite3_get_autocommit(sqlite3*);
5249
5250/*
5251** CAPI3REF: Find The Database Handle Of A Prepared Statement
5252**
5253** ^The sqlite3_db_handle interface returns the [database connection] handle
5254** to which a [prepared statement] belongs.  ^The [database connection]
5255** returned by sqlite3_db_handle is the same [database connection]
5256** that was the first argument
5257** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
5258** create the statement in the first place.
5259*/
5260SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
5261
5262/*
5263** CAPI3REF: Return The Filename For A Database Connection
5264**
5265** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
5266** associated with database N of connection D.  ^The main database file
5267** has the name "main".  If there is no attached database N on the database
5268** connection D, or if database N is a temporary or in-memory database, then
5269** a NULL pointer is returned.
5270**
5271** ^The filename returned by this function is the output of the
5272** xFullPathname method of the [VFS].  ^In other words, the filename
5273** will be an absolute pathname, even if the filename used
5274** to open the database originally was a URI or relative pathname.
5275*/
5276SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);
5277
5278/*
5279** CAPI3REF: Determine if a database is read-only
5280**
5281** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
5282** of connection D is read-only, 0 if it is read/write, or -1 if N is not
5283** the name of a database on connection D.
5284*/
5285SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
5286
5287/*
5288** CAPI3REF: Find the next prepared statement
5289**
5290** ^This interface returns a pointer to the next [prepared statement] after
5291** pStmt associated with the [database connection] pDb.  ^If pStmt is NULL
5292** then this interface returns a pointer to the first prepared statement
5293** associated with the database connection pDb.  ^If no prepared statement
5294** satisfies the conditions of this routine, it returns NULL.
5295**
5296** The [database connection] pointer D in a call to
5297** [sqlite3_next_stmt(D,S)] must refer to an open database
5298** connection and in particular must not be a NULL pointer.
5299*/
5300SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
5301
5302/*
5303** CAPI3REF: Commit And Rollback Notification Callbacks
5304**
5305** ^The sqlite3_commit_hook() interface registers a callback
5306** function to be invoked whenever a transaction is [COMMIT | committed].
5307** ^Any callback set by a previous call to sqlite3_commit_hook()
5308** for the same database connection is overridden.
5309** ^The sqlite3_rollback_hook() interface registers a callback
5310** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
5311** ^Any callback set by a previous call to sqlite3_rollback_hook()
5312** for the same database connection is overridden.
5313** ^The pArg argument is passed through to the callback.
5314** ^If the callback on a commit hook function returns non-zero,
5315** then the commit is converted into a rollback.
5316**
5317** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
5318** return the P argument from the previous call of the same function
5319** on the same [database connection] D, or NULL for
5320** the first call for each function on D.
5321**
5322** The commit and rollback hook callbacks are not reentrant.
5323** The callback implementation must not do anything that will modify
5324** the database connection that invoked the callback.  Any actions
5325** to modify the database connection must be deferred until after the
5326** completion of the [sqlite3_step()] call that triggered the commit
5327** or rollback hook in the first place.
5328** Note that running any other SQL statements, including SELECT statements,
5329** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
5330** the database connections for the meaning of "modify" in this paragraph.
5331**
5332** ^Registering a NULL function disables the callback.
5333**
5334** ^When the commit hook callback routine returns zero, the [COMMIT]
5335** operation is allowed to continue normally.  ^If the commit hook
5336** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
5337** ^The rollback hook is invoked on a rollback that results from a commit
5338** hook returning non-zero, just as it would be with any other rollback.
5339**
5340** ^For the purposes of this API, a transaction is said to have been
5341** rolled back if an explicit "ROLLBACK" statement is executed, or
5342** an error or constraint causes an implicit rollback to occur.
5343** ^The rollback callback is not invoked if a transaction is
5344** automatically rolled back because the database connection is closed.
5345**
5346** See also the [sqlite3_update_hook()] interface.
5347*/
5348SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
5349SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
5350
5351/*
5352** CAPI3REF: Data Change Notification Callbacks
5353**
5354** ^The sqlite3_update_hook() interface registers a callback function
5355** with the [database connection] identified by the first argument
5356** to be invoked whenever a row is updated, inserted or deleted.
5357** ^Any callback set by a previous call to this function
5358** for the same database connection is overridden.
5359**
5360** ^The second argument is a pointer to the function to invoke when a
5361** row is updated, inserted or deleted.
5362** ^The first argument to the callback is a copy of the third argument
5363** to sqlite3_update_hook().
5364** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
5365** or [SQLITE_UPDATE], depending on the operation that caused the callback
5366** to be invoked.
5367** ^The third and fourth arguments to the callback contain pointers to the
5368** database and table name containing the affected row.
5369** ^The final callback parameter is the [rowid] of the row.
5370** ^In the case of an update, this is the [rowid] after the update takes place.
5371**
5372** ^(The update hook is not invoked when internal system tables are
5373** modified (i.e. sqlite_master and sqlite_sequence).)^
5374**
5375** ^In the current implementation, the update hook
5376** is not invoked when duplication rows are deleted because of an
5377** [ON CONFLICT | ON CONFLICT REPLACE] clause.  ^Nor is the update hook
5378** invoked when rows are deleted using the [truncate optimization].
5379** The exceptions defined in this paragraph might change in a future
5380** release of SQLite.
5381**
5382** The update hook implementation must not do anything that will modify
5383** the database connection that invoked the update hook.  Any actions
5384** to modify the database connection must be deferred until after the
5385** completion of the [sqlite3_step()] call that triggered the update hook.
5386** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
5387** database connections for the meaning of "modify" in this paragraph.
5388**
5389** ^The sqlite3_update_hook(D,C,P) function
5390** returns the P argument from the previous call
5391** on the same [database connection] D, or NULL for
5392** the first call on D.
5393**
5394** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
5395** interfaces.
5396*/
5397SQLITE_API void *sqlite3_update_hook(
5398  sqlite3*,
5399  void(*)(void *,int ,char const *,char const *,sqlite3_int64),
5400  void*
5401);
5402
5403/*
5404** CAPI3REF: Enable Or Disable Shared Pager Cache
5405**
5406** ^(This routine enables or disables the sharing of the database cache
5407** and schema data structures between [database connection | connections]
5408** to the same database. Sharing is enabled if the argument is true
5409** and disabled if the argument is false.)^
5410**
5411** ^Cache sharing is enabled and disabled for an entire process.
5412** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
5413** sharing was enabled or disabled for each thread separately.
5414**
5415** ^(The cache sharing mode set by this interface effects all subsequent
5416** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
5417** Existing database connections continue use the sharing mode
5418** that was in effect at the time they were opened.)^
5419**
5420** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
5421** successfully.  An [error code] is returned otherwise.)^
5422**
5423** ^Shared cache is disabled by default. But this might change in
5424** future releases of SQLite.  Applications that care about shared
5425** cache setting should set it explicitly.
5426**
5427** This interface is threadsafe on processors where writing a
5428** 32-bit integer is atomic.
5429**
5430** See Also:  [SQLite Shared-Cache Mode]
5431*/
5432SQLITE_API int sqlite3_enable_shared_cache(int);
5433
5434/*
5435** CAPI3REF: Attempt To Free Heap Memory
5436**
5437** ^The sqlite3_release_memory() interface attempts to free N bytes
5438** of heap memory by deallocating non-essential memory allocations
5439** held by the database library.   Memory used to cache database
5440** pages to improve performance is an example of non-essential memory.
5441** ^sqlite3_release_memory() returns the number of bytes actually freed,
5442** which might be more or less than the amount requested.
5443** ^The sqlite3_release_memory() routine is a no-op returning zero
5444** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
5445**
5446** See also: [sqlite3_db_release_memory()]
5447*/
5448SQLITE_API int sqlite3_release_memory(int);
5449
5450/*
5451** CAPI3REF: Free Memory Used By A Database Connection
5452**
5453** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
5454** memory as possible from database connection D. Unlike the
5455** [sqlite3_release_memory()] interface, this interface is effect even
5456** when then [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
5457** omitted.
5458**
5459** See also: [sqlite3_release_memory()]
5460*/
5461SQLITE_API int sqlite3_db_release_memory(sqlite3*);
5462
5463/*
5464** CAPI3REF: Impose A Limit On Heap Size
5465**
5466** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
5467** soft limit on the amount of heap memory that may be allocated by SQLite.
5468** ^SQLite strives to keep heap memory utilization below the soft heap
5469** limit by reducing the number of pages held in the page cache
5470** as heap memory usages approaches the limit.
5471** ^The soft heap limit is "soft" because even though SQLite strives to stay
5472** below the limit, it will exceed the limit rather than generate
5473** an [SQLITE_NOMEM] error.  In other words, the soft heap limit
5474** is advisory only.
5475**
5476** ^The return value from sqlite3_soft_heap_limit64() is the size of
5477** the soft heap limit prior to the call, or negative in the case of an
5478** error.  ^If the argument N is negative
5479** then no change is made to the soft heap limit.  Hence, the current
5480** size of the soft heap limit can be determined by invoking
5481** sqlite3_soft_heap_limit64() with a negative argument.
5482**
5483** ^If the argument N is zero then the soft heap limit is disabled.
5484**
5485** ^(The soft heap limit is not enforced in the current implementation
5486** if one or more of following conditions are true:
5487**
5488** <ul>
5489** <li> The soft heap limit is set to zero.
5490** <li> Memory accounting is disabled using a combination of the
5491**      [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
5492**      the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
5493** <li> An alternative page cache implementation is specified using
5494**      [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
5495** <li> The page cache allocates from its own memory pool supplied
5496**      by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
5497**      from the heap.
5498** </ul>)^
5499**
5500** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
5501** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
5502** compile-time option is invoked.  With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
5503** the soft heap limit is enforced on every memory allocation.  Without
5504** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
5505** when memory is allocated by the page cache.  Testing suggests that because
5506** the page cache is the predominate memory user in SQLite, most
5507** applications will achieve adequate soft heap limit enforcement without
5508** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
5509**
5510** The circumstances under which SQLite will enforce the soft heap limit may
5511** changes in future releases of SQLite.
5512*/
5513SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
5514
5515/*
5516** CAPI3REF: Deprecated Soft Heap Limit Interface
5517** DEPRECATED
5518**
5519** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
5520** interface.  This routine is provided for historical compatibility
5521** only.  All new applications should use the
5522** [sqlite3_soft_heap_limit64()] interface rather than this one.
5523*/
5524SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
5525
5526
5527/*
5528** CAPI3REF: Extract Metadata About A Column Of A Table
5529**
5530** ^This routine returns metadata about a specific column of a specific
5531** database table accessible using the [database connection] handle
5532** passed as the first function argument.
5533**
5534** ^The column is identified by the second, third and fourth parameters to
5535** this function. ^The second parameter is either the name of the database
5536** (i.e. "main", "temp", or an attached database) containing the specified
5537** table or NULL. ^If it is NULL, then all attached databases are searched
5538** for the table using the same algorithm used by the database engine to
5539** resolve unqualified table references.
5540**
5541** ^The third and fourth parameters to this function are the table and column
5542** name of the desired column, respectively. Neither of these parameters
5543** may be NULL.
5544**
5545** ^Metadata is returned by writing to the memory locations passed as the 5th
5546** and subsequent parameters to this function. ^Any of these arguments may be
5547** NULL, in which case the corresponding element of metadata is omitted.
5548**
5549** ^(<blockquote>
5550** <table border="1">
5551** <tr><th> Parameter <th> Output<br>Type <th>  Description
5552**
5553** <tr><td> 5th <td> const char* <td> Data type
5554** <tr><td> 6th <td> const char* <td> Name of default collation sequence
5555** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint
5556** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY
5557** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]
5558** </table>
5559** </blockquote>)^
5560**
5561** ^The memory pointed to by the character pointers returned for the
5562** declaration type and collation sequence is valid only until the next
5563** call to any SQLite API function.
5564**
5565** ^If the specified table is actually a view, an [error code] is returned.
5566**
5567** ^If the specified column is "rowid", "oid" or "_rowid_" and an
5568** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
5569** parameters are set for the explicitly declared column. ^(If there is no
5570** explicitly declared [INTEGER PRIMARY KEY] column, then the output
5571** parameters are set as follows:
5572**
5573** <pre>
5574**     data type: "INTEGER"
5575**     collation sequence: "BINARY"
5576**     not null: 0
5577**     primary key: 1
5578**     auto increment: 0
5579** </pre>)^
5580**
5581** ^(This function may load one or more schemas from database files. If an
5582** error occurs during this process, or if the requested table or column
5583** cannot be found, an [error code] is returned and an error message left
5584** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^
5585**
5586** ^This API is only available if the library was compiled with the
5587** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
5588*/
5589SQLITE_API int sqlite3_table_column_metadata(
5590  sqlite3 *db,                /* Connection handle */
5591  const char *zDbName,        /* Database name or NULL */
5592  const char *zTableName,     /* Table name */
5593  const char *zColumnName,    /* Column name */
5594  char const **pzDataType,    /* OUTPUT: Declared data type */
5595  char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
5596  int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
5597  int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
5598  int *pAutoinc               /* OUTPUT: True if column is auto-increment */
5599);
5600
5601/*
5602** CAPI3REF: Load An Extension
5603**
5604** ^This interface loads an SQLite extension library from the named file.
5605**
5606** ^The sqlite3_load_extension() interface attempts to load an
5607** [SQLite extension] library contained in the file zFile.  If
5608** the file cannot be loaded directly, attempts are made to load
5609** with various operating-system specific extensions added.
5610** So for example, if "samplelib" cannot be loaded, then names like
5611** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
5612** be tried also.
5613**
5614** ^The entry point is zProc.
5615** ^(zProc may be 0, in which case SQLite will try to come up with an
5616** entry point name on its own.  It first tries "sqlite3_extension_init".
5617** If that does not work, it constructs a name "sqlite3_X_init" where the
5618** X is consists of the lower-case equivalent of all ASCII alphabetic
5619** characters in the filename from the last "/" to the first following
5620** "." and omitting any initial "lib".)^
5621** ^The sqlite3_load_extension() interface returns
5622** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
5623** ^If an error occurs and pzErrMsg is not 0, then the
5624** [sqlite3_load_extension()] interface shall attempt to
5625** fill *pzErrMsg with error message text stored in memory
5626** obtained from [sqlite3_malloc()]. The calling function
5627** should free this memory by calling [sqlite3_free()].
5628**
5629** ^Extension loading must be enabled using
5630** [sqlite3_enable_load_extension()] prior to calling this API,
5631** otherwise an error will be returned.
5632**
5633** See also the [load_extension() SQL function].
5634*/
5635SQLITE_API int sqlite3_load_extension(
5636  sqlite3 *db,          /* Load the extension into this database connection */
5637  const char *zFile,    /* Name of the shared library containing extension */
5638  const char *zProc,    /* Entry point.  Derived from zFile if 0 */
5639  char **pzErrMsg       /* Put error message here if not 0 */
5640);
5641
5642/*
5643** CAPI3REF: Enable Or Disable Extension Loading
5644**
5645** ^So as not to open security holes in older applications that are
5646** unprepared to deal with [extension loading], and as a means of disabling
5647** [extension loading] while evaluating user-entered SQL, the following API
5648** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
5649**
5650** ^Extension loading is off by default.
5651** ^Call the sqlite3_enable_load_extension() routine with onoff==1
5652** to turn extension loading on and call it with onoff==0 to turn
5653** it back off again.
5654*/
5655SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
5656
5657/*
5658** CAPI3REF: Automatically Load Statically Linked Extensions
5659**
5660** ^This interface causes the xEntryPoint() function to be invoked for
5661** each new [database connection] that is created.  The idea here is that
5662** xEntryPoint() is the entry point for a statically linked [SQLite extension]
5663** that is to be automatically loaded into all new database connections.
5664**
5665** ^(Even though the function prototype shows that xEntryPoint() takes
5666** no arguments and returns void, SQLite invokes xEntryPoint() with three
5667** arguments and expects and integer result as if the signature of the
5668** entry point where as follows:
5669**
5670** <blockquote><pre>
5671** &nbsp;  int xEntryPoint(
5672** &nbsp;    sqlite3 *db,
5673** &nbsp;    const char **pzErrMsg,
5674** &nbsp;    const struct sqlite3_api_routines *pThunk
5675** &nbsp;  );
5676** </pre></blockquote>)^
5677**
5678** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
5679** point to an appropriate error message (obtained from [sqlite3_mprintf()])
5680** and return an appropriate [error code].  ^SQLite ensures that *pzErrMsg
5681** is NULL before calling the xEntryPoint().  ^SQLite will invoke
5682** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns.  ^If any
5683** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
5684** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
5685**
5686** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
5687** on the list of automatic extensions is a harmless no-op. ^No entry point
5688** will be called more than once for each database connection that is opened.
5689**
5690** See also: [sqlite3_reset_auto_extension()].
5691*/
5692SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
5693
5694/*
5695** CAPI3REF: Reset Automatic Extension Loading
5696**
5697** ^This interface disables all automatic extensions previously
5698** registered using [sqlite3_auto_extension()].
5699*/
5700SQLITE_API void sqlite3_reset_auto_extension(void);
5701
5702/*
5703** The interface to the virtual-table mechanism is currently considered
5704** to be experimental.  The interface might change in incompatible ways.
5705** If this is a problem for you, do not use the interface at this time.
5706**
5707** When the virtual-table mechanism stabilizes, we will declare the
5708** interface fixed, support it indefinitely, and remove this comment.
5709*/
5710
5711/*
5712** Structures used by the virtual table interface
5713*/
5714typedef struct sqlite3_vtab sqlite3_vtab;
5715typedef struct sqlite3_index_info sqlite3_index_info;
5716typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
5717typedef struct sqlite3_module sqlite3_module;
5718
5719/*
5720** CAPI3REF: Virtual Table Object
5721** KEYWORDS: sqlite3_module {virtual table module}
5722**
5723** This structure, sometimes called a "virtual table module",
5724** defines the implementation of a [virtual tables].
5725** This structure consists mostly of methods for the module.
5726**
5727** ^A virtual table module is created by filling in a persistent
5728** instance of this structure and passing a pointer to that instance
5729** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
5730** ^The registration remains valid until it is replaced by a different
5731** module or until the [database connection] closes.  The content
5732** of this structure must not change while it is registered with
5733** any database connection.
5734*/
5735struct sqlite3_module {
5736  int iVersion;
5737  int (*xCreate)(sqlite3*, void *pAux,
5738               int argc, const char *const*argv,
5739               sqlite3_vtab **ppVTab, char**);
5740  int (*xConnect)(sqlite3*, void *pAux,
5741               int argc, const char *const*argv,
5742               sqlite3_vtab **ppVTab, char**);
5743  int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
5744  int (*xDisconnect)(sqlite3_vtab *pVTab);
5745  int (*xDestroy)(sqlite3_vtab *pVTab);
5746  int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
5747  int (*xClose)(sqlite3_vtab_cursor*);
5748  int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
5749                int argc, sqlite3_value **argv);
5750  int (*xNext)(sqlite3_vtab_cursor*);
5751  int (*xEof)(sqlite3_vtab_cursor*);
5752  int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
5753  int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
5754  int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
5755  int (*xBegin)(sqlite3_vtab *pVTab);
5756  int (*xSync)(sqlite3_vtab *pVTab);
5757  int (*xCommit)(sqlite3_vtab *pVTab);
5758  int (*xRollback)(sqlite3_vtab *pVTab);
5759  int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
5760                       void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
5761                       void **ppArg);
5762  int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
5763  /* The methods above are in version 1 of the sqlite_module object. Those
5764  ** below are for version 2 and greater. */
5765  int (*xSavepoint)(sqlite3_vtab *pVTab, int);
5766  int (*xRelease)(sqlite3_vtab *pVTab, int);
5767  int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
5768};
5769
5770/*
5771** CAPI3REF: Virtual Table Indexing Information
5772** KEYWORDS: sqlite3_index_info
5773**
5774** The sqlite3_index_info structure and its substructures is used as part
5775** of the [virtual table] interface to
5776** pass information into and receive the reply from the [xBestIndex]
5777** method of a [virtual table module].  The fields under **Inputs** are the
5778** inputs to xBestIndex and are read-only.  xBestIndex inserts its
5779** results into the **Outputs** fields.
5780**
5781** ^(The aConstraint[] array records WHERE clause constraints of the form:
5782**
5783** <blockquote>column OP expr</blockquote>
5784**
5785** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is
5786** stored in aConstraint[].op using one of the
5787** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
5788** ^(The index of the column is stored in
5789** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the
5790** expr on the right-hand side can be evaluated (and thus the constraint
5791** is usable) and false if it cannot.)^
5792**
5793** ^The optimizer automatically inverts terms of the form "expr OP column"
5794** and makes other simplifications to the WHERE clause in an attempt to
5795** get as many WHERE clause terms into the form shown above as possible.
5796** ^The aConstraint[] array only reports WHERE clause terms that are
5797** relevant to the particular virtual table being queried.
5798**
5799** ^Information about the ORDER BY clause is stored in aOrderBy[].
5800** ^Each term of aOrderBy records a column of the ORDER BY clause.
5801**
5802** The [xBestIndex] method must fill aConstraintUsage[] with information
5803** about what parameters to pass to xFilter.  ^If argvIndex>0 then
5804** the right-hand side of the corresponding aConstraint[] is evaluated
5805** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit
5806** is true, then the constraint is assumed to be fully handled by the
5807** virtual table and is not checked again by SQLite.)^
5808**
5809** ^The idxNum and idxPtr values are recorded and passed into the
5810** [xFilter] method.
5811** ^[sqlite3_free()] is used to free idxPtr if and only if
5812** needToFreeIdxPtr is true.
5813**
5814** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
5815** the correct order to satisfy the ORDER BY clause so that no separate
5816** sorting step is required.
5817**
5818** ^The estimatedCost value is an estimate of the cost of doing the
5819** particular lookup.  A full scan of a table with N entries should have
5820** a cost of N.  A binary search of a table of N entries should have a
5821** cost of approximately log(N).
5822*/
5823struct sqlite3_index_info {
5824  /* Inputs */
5825  int nConstraint;           /* Number of entries in aConstraint */
5826  struct sqlite3_index_constraint {
5827     int iColumn;              /* Column on left-hand side of constraint */
5828     unsigned char op;         /* Constraint operator */
5829     unsigned char usable;     /* True if this constraint is usable */
5830     int iTermOffset;          /* Used internally - xBestIndex should ignore */
5831  } *aConstraint;            /* Table of WHERE clause constraints */
5832  int nOrderBy;              /* Number of terms in the ORDER BY clause */
5833  struct sqlite3_index_orderby {
5834     int iColumn;              /* Column number */
5835     unsigned char desc;       /* True for DESC.  False for ASC. */
5836  } *aOrderBy;               /* The ORDER BY clause */
5837  /* Outputs */
5838  struct sqlite3_index_constraint_usage {
5839    int argvIndex;           /* if >0, constraint is part of argv to xFilter */
5840    unsigned char omit;      /* Do not code a test for this constraint */
5841  } *aConstraintUsage;
5842  int idxNum;                /* Number used to identify the index */
5843  char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
5844  int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
5845  int orderByConsumed;       /* True if output is already ordered */
5846  double estimatedCost;      /* Estimated cost of using this index */
5847};
5848
5849/*
5850** CAPI3REF: Virtual Table Constraint Operator Codes
5851**
5852** These macros defined the allowed values for the
5853** [sqlite3_index_info].aConstraint[].op field.  Each value represents
5854** an operator that is part of a constraint term in the wHERE clause of
5855** a query that uses a [virtual table].
5856*/
5857#define SQLITE_INDEX_CONSTRAINT_EQ    2
5858#define SQLITE_INDEX_CONSTRAINT_GT    4
5859#define SQLITE_INDEX_CONSTRAINT_LE    8
5860#define SQLITE_INDEX_CONSTRAINT_LT    16
5861#define SQLITE_INDEX_CONSTRAINT_GE    32
5862#define SQLITE_INDEX_CONSTRAINT_MATCH 64
5863
5864/*
5865** CAPI3REF: Register A Virtual Table Implementation
5866**
5867** ^These routines are used to register a new [virtual table module] name.
5868** ^Module names must be registered before
5869** creating a new [virtual table] using the module and before using a
5870** preexisting [virtual table] for the module.
5871**
5872** ^The module name is registered on the [database connection] specified
5873** by the first parameter.  ^The name of the module is given by the
5874** second parameter.  ^The third parameter is a pointer to
5875** the implementation of the [virtual table module].   ^The fourth
5876** parameter is an arbitrary client data pointer that is passed through
5877** into the [xCreate] and [xConnect] methods of the virtual table module
5878** when a new virtual table is be being created or reinitialized.
5879**
5880** ^The sqlite3_create_module_v2() interface has a fifth parameter which
5881** is a pointer to a destructor for the pClientData.  ^SQLite will
5882** invoke the destructor function (if it is not NULL) when SQLite
5883** no longer needs the pClientData pointer.  ^The destructor will also
5884** be invoked if the call to sqlite3_create_module_v2() fails.
5885** ^The sqlite3_create_module()
5886** interface is equivalent to sqlite3_create_module_v2() with a NULL
5887** destructor.
5888*/
5889SQLITE_API int sqlite3_create_module(
5890  sqlite3 *db,               /* SQLite connection to register module with */
5891  const char *zName,         /* Name of the module */
5892  const sqlite3_module *p,   /* Methods for the module */
5893  void *pClientData          /* Client data for xCreate/xConnect */
5894);
5895SQLITE_API int sqlite3_create_module_v2(
5896  sqlite3 *db,               /* SQLite connection to register module with */
5897  const char *zName,         /* Name of the module */
5898  const sqlite3_module *p,   /* Methods for the module */
5899  void *pClientData,         /* Client data for xCreate/xConnect */
5900  void(*xDestroy)(void*)     /* Module destructor function */
5901);
5902
5903/*
5904** CAPI3REF: Virtual Table Instance Object
5905** KEYWORDS: sqlite3_vtab
5906**
5907** Every [virtual table module] implementation uses a subclass
5908** of this object to describe a particular instance
5909** of the [virtual table].  Each subclass will
5910** be tailored to the specific needs of the module implementation.
5911** The purpose of this superclass is to define certain fields that are
5912** common to all module implementations.
5913**
5914** ^Virtual tables methods can set an error message by assigning a
5915** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should
5916** take care that any prior string is freed by a call to [sqlite3_free()]
5917** prior to assigning a new string to zErrMsg.  ^After the error message
5918** is delivered up to the client application, the string will be automatically
5919** freed by sqlite3_free() and the zErrMsg field will be zeroed.
5920*/
5921struct sqlite3_vtab {
5922  const sqlite3_module *pModule;  /* The module for this virtual table */
5923  int nRef;                       /* NO LONGER USED */
5924  char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
5925  /* Virtual table implementations will typically add additional fields */
5926};
5927
5928/*
5929** CAPI3REF: Virtual Table Cursor Object
5930** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
5931**
5932** Every [virtual table module] implementation uses a subclass of the
5933** following structure to describe cursors that point into the
5934** [virtual table] and are used
5935** to loop through the virtual table.  Cursors are created using the
5936** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
5937** by the [sqlite3_module.xClose | xClose] method.  Cursors are used
5938** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
5939** of the module.  Each module implementation will define
5940** the content of a cursor structure to suit its own needs.
5941**
5942** This superclass exists in order to define fields of the cursor that
5943** are common to all implementations.
5944*/
5945struct sqlite3_vtab_cursor {
5946  sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
5947  /* Virtual table implementations will typically add additional fields */
5948};
5949
5950/*
5951** CAPI3REF: Declare The Schema Of A Virtual Table
5952**
5953** ^The [xCreate] and [xConnect] methods of a
5954** [virtual table module] call this interface
5955** to declare the format (the names and datatypes of the columns) of
5956** the virtual tables they implement.
5957*/
5958SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
5959
5960/*
5961** CAPI3REF: Overload A Function For A Virtual Table
5962**
5963** ^(Virtual tables can provide alternative implementations of functions
5964** using the [xFindFunction] method of the [virtual table module].
5965** But global versions of those functions
5966** must exist in order to be overloaded.)^
5967**
5968** ^(This API makes sure a global version of a function with a particular
5969** name and number of parameters exists.  If no such function exists
5970** before this API is called, a new function is created.)^  ^The implementation
5971** of the new function always causes an exception to be thrown.  So
5972** the new function is not good for anything by itself.  Its only
5973** purpose is to be a placeholder function that can be overloaded
5974** by a [virtual table].
5975*/
5976SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
5977
5978/*
5979** The interface to the virtual-table mechanism defined above (back up
5980** to a comment remarkably similar to this one) is currently considered
5981** to be experimental.  The interface might change in incompatible ways.
5982** If this is a problem for you, do not use the interface at this time.
5983**
5984** When the virtual-table mechanism stabilizes, we will declare the
5985** interface fixed, support it indefinitely, and remove this comment.
5986*/
5987
5988/*
5989** CAPI3REF: A Handle To An Open BLOB
5990** KEYWORDS: {BLOB handle} {BLOB handles}
5991**
5992** An instance of this object represents an open BLOB on which
5993** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
5994** ^Objects of this type are created by [sqlite3_blob_open()]
5995** and destroyed by [sqlite3_blob_close()].
5996** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
5997** can be used to read or write small subsections of the BLOB.
5998** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
5999*/
6000typedef struct sqlite3_blob sqlite3_blob;
6001
6002/*
6003** CAPI3REF: Open A BLOB For Incremental I/O
6004**
6005** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
6006** in row iRow, column zColumn, table zTable in database zDb;
6007** in other words, the same BLOB that would be selected by:
6008**
6009** <pre>
6010**     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
6011** </pre>)^
6012**
6013** ^If the flags parameter is non-zero, then the BLOB is opened for read
6014** and write access. ^If it is zero, the BLOB is opened for read access.
6015** ^It is not possible to open a column that is part of an index or primary
6016** key for writing. ^If [foreign key constraints] are enabled, it is
6017** not possible to open a column that is part of a [child key] for writing.
6018**
6019** ^Note that the database name is not the filename that contains
6020** the database but rather the symbolic name of the database that
6021** appears after the AS keyword when the database is connected using [ATTACH].
6022** ^For the main database file, the database name is "main".
6023** ^For TEMP tables, the database name is "temp".
6024**
6025** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
6026** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set
6027** to be a null pointer.)^
6028** ^This function sets the [database connection] error code and message
6029** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related
6030** functions. ^Note that the *ppBlob variable is always initialized in a
6031** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob
6032** regardless of the success or failure of this routine.
6033**
6034** ^(If the row that a BLOB handle points to is modified by an
6035** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
6036** then the BLOB handle is marked as "expired".
6037** This is true if any column of the row is changed, even a column
6038** other than the one the BLOB handle is open on.)^
6039** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
6040** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
6041** ^(Changes written into a BLOB prior to the BLOB expiring are not
6042** rolled back by the expiration of the BLOB.  Such changes will eventually
6043** commit if the transaction continues to completion.)^
6044**
6045** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
6046** the opened blob.  ^The size of a blob may not be changed by this
6047** interface.  Use the [UPDATE] SQL command to change the size of a
6048** blob.
6049**
6050** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
6051** and the built-in [zeroblob] SQL function can be used, if desired,
6052** to create an empty, zero-filled blob in which to read or write using
6053** this interface.
6054**
6055** To avoid a resource leak, every open [BLOB handle] should eventually
6056** be released by a call to [sqlite3_blob_close()].
6057*/
6058SQLITE_API int sqlite3_blob_open(
6059  sqlite3*,
6060  const char *zDb,
6061  const char *zTable,
6062  const char *zColumn,
6063  sqlite3_int64 iRow,
6064  int flags,
6065  sqlite3_blob **ppBlob
6066);
6067
6068/*
6069** CAPI3REF: Move a BLOB Handle to a New Row
6070**
6071** ^This function is used to move an existing blob handle so that it points
6072** to a different row of the same database table. ^The new row is identified
6073** by the rowid value passed as the second argument. Only the row can be
6074** changed. ^The database, table and column on which the blob handle is open
6075** remain the same. Moving an existing blob handle to a new row can be
6076** faster than closing the existing handle and opening a new one.
6077**
6078** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
6079** it must exist and there must be either a blob or text value stored in
6080** the nominated column.)^ ^If the new row is not present in the table, or if
6081** it does not contain a blob or text value, or if another error occurs, an
6082** SQLite error code is returned and the blob handle is considered aborted.
6083** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
6084** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
6085** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
6086** always returns zero.
6087**
6088** ^This function sets the database handle error code and message.
6089*/
6090SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
6091
6092/*
6093** CAPI3REF: Close A BLOB Handle
6094**
6095** ^Closes an open [BLOB handle].
6096**
6097** ^Closing a BLOB shall cause the current transaction to commit
6098** if there are no other BLOBs, no pending prepared statements, and the
6099** database connection is in [autocommit mode].
6100** ^If any writes were made to the BLOB, they might be held in cache
6101** until the close operation if they will fit.
6102**
6103** ^(Closing the BLOB often forces the changes
6104** out to disk and so if any I/O errors occur, they will likely occur
6105** at the time when the BLOB is closed.  Any errors that occur during
6106** closing are reported as a non-zero return value.)^
6107**
6108** ^(The BLOB is closed unconditionally.  Even if this routine returns
6109** an error code, the BLOB is still closed.)^
6110**
6111** ^Calling this routine with a null pointer (such as would be returned
6112** by a failed call to [sqlite3_blob_open()]) is a harmless no-op.
6113*/
6114SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
6115
6116/*
6117** CAPI3REF: Return The Size Of An Open BLOB
6118**
6119** ^Returns the size in bytes of the BLOB accessible via the
6120** successfully opened [BLOB handle] in its only argument.  ^The
6121** incremental blob I/O routines can only read or overwriting existing
6122** blob content; they cannot change the size of a blob.
6123**
6124** This routine only works on a [BLOB handle] which has been created
6125** by a prior successful call to [sqlite3_blob_open()] and which has not
6126** been closed by [sqlite3_blob_close()].  Passing any other pointer in
6127** to this routine results in undefined and probably undesirable behavior.
6128*/
6129SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
6130
6131/*
6132** CAPI3REF: Read Data From A BLOB Incrementally
6133**
6134** ^(This function is used to read data from an open [BLOB handle] into a
6135** caller-supplied buffer. N bytes of data are copied into buffer Z
6136** from the open BLOB, starting at offset iOffset.)^
6137**
6138** ^If offset iOffset is less than N bytes from the end of the BLOB,
6139** [SQLITE_ERROR] is returned and no data is read.  ^If N or iOffset is
6140** less than zero, [SQLITE_ERROR] is returned and no data is read.
6141** ^The size of the blob (and hence the maximum value of N+iOffset)
6142** can be determined using the [sqlite3_blob_bytes()] interface.
6143**
6144** ^An attempt to read from an expired [BLOB handle] fails with an
6145** error code of [SQLITE_ABORT].
6146**
6147** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
6148** Otherwise, an [error code] or an [extended error code] is returned.)^
6149**
6150** This routine only works on a [BLOB handle] which has been created
6151** by a prior successful call to [sqlite3_blob_open()] and which has not
6152** been closed by [sqlite3_blob_close()].  Passing any other pointer in
6153** to this routine results in undefined and probably undesirable behavior.
6154**
6155** See also: [sqlite3_blob_write()].
6156*/
6157SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
6158
6159/*
6160** CAPI3REF: Write Data Into A BLOB Incrementally
6161**
6162** ^This function is used to write data into an open [BLOB handle] from a
6163** caller-supplied buffer. ^N bytes of data are copied from the buffer Z
6164** into the open BLOB, starting at offset iOffset.
6165**
6166** ^If the [BLOB handle] passed as the first argument was not opened for
6167** writing (the flags parameter to [sqlite3_blob_open()] was zero),
6168** this function returns [SQLITE_READONLY].
6169**
6170** ^This function may only modify the contents of the BLOB; it is
6171** not possible to increase the size of a BLOB using this API.
6172** ^If offset iOffset is less than N bytes from the end of the BLOB,
6173** [SQLITE_ERROR] is returned and no data is written.  ^If N is
6174** less than zero [SQLITE_ERROR] is returned and no data is written.
6175** The size of the BLOB (and hence the maximum value of N+iOffset)
6176** can be determined using the [sqlite3_blob_bytes()] interface.
6177**
6178** ^An attempt to write to an expired [BLOB handle] fails with an
6179** error code of [SQLITE_ABORT].  ^Writes to the BLOB that occurred
6180** before the [BLOB handle] expired are not rolled back by the
6181** expiration of the handle, though of course those changes might
6182** have been overwritten by the statement that expired the BLOB handle
6183** or by other independent statements.
6184**
6185** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
6186** Otherwise, an  [error code] or an [extended error code] is returned.)^
6187**
6188** This routine only works on a [BLOB handle] which has been created
6189** by a prior successful call to [sqlite3_blob_open()] and which has not
6190** been closed by [sqlite3_blob_close()].  Passing any other pointer in
6191** to this routine results in undefined and probably undesirable behavior.
6192**
6193** See also: [sqlite3_blob_read()].
6194*/
6195SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
6196
6197/*
6198** CAPI3REF: Virtual File System Objects
6199**
6200** A virtual filesystem (VFS) is an [sqlite3_vfs] object
6201** that SQLite uses to interact
6202** with the underlying operating system.  Most SQLite builds come with a
6203** single default VFS that is appropriate for the host computer.
6204** New VFSes can be registered and existing VFSes can be unregistered.
6205** The following interfaces are provided.
6206**
6207** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
6208** ^Names are case sensitive.
6209** ^Names are zero-terminated UTF-8 strings.
6210** ^If there is no match, a NULL pointer is returned.
6211** ^If zVfsName is NULL then the default VFS is returned.
6212**
6213** ^New VFSes are registered with sqlite3_vfs_register().
6214** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
6215** ^The same VFS can be registered multiple times without injury.
6216** ^To make an existing VFS into the default VFS, register it again
6217** with the makeDflt flag set.  If two different VFSes with the
6218** same name are registered, the behavior is undefined.  If a
6219** VFS is registered with a name that is NULL or an empty string,
6220** then the behavior is undefined.
6221**
6222** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
6223** ^(If the default VFS is unregistered, another VFS is chosen as
6224** the default.  The choice for the new VFS is arbitrary.)^
6225*/
6226SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
6227SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
6228SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
6229
6230/*
6231** CAPI3REF: Mutexes
6232**
6233** The SQLite core uses these routines for thread
6234** synchronization. Though they are intended for internal
6235** use by SQLite, code that links against SQLite is
6236** permitted to use any of these routines.
6237**
6238** The SQLite source code contains multiple implementations
6239** of these mutex routines.  An appropriate implementation
6240** is selected automatically at compile-time.  ^(The following
6241** implementations are available in the SQLite core:
6242**
6243** <ul>
6244** <li>   SQLITE_MUTEX_PTHREADS
6245** <li>   SQLITE_MUTEX_W32
6246** <li>   SQLITE_MUTEX_NOOP
6247** </ul>)^
6248**
6249** ^The SQLITE_MUTEX_NOOP implementation is a set of routines
6250** that does no real locking and is appropriate for use in
6251** a single-threaded application.  ^The SQLITE_MUTEX_PTHREADS and
6252** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
6253** and Windows.
6254**
6255** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
6256** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
6257** implementation is included with the library. In this case the
6258** application must supply a custom mutex implementation using the
6259** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
6260** before calling sqlite3_initialize() or any other public sqlite3_
6261** function that calls sqlite3_initialize().)^
6262**
6263** ^The sqlite3_mutex_alloc() routine allocates a new
6264** mutex and returns a pointer to it. ^If it returns NULL
6265** that means that a mutex could not be allocated.  ^SQLite
6266** will unwind its stack and return an error.  ^(The argument
6267** to sqlite3_mutex_alloc() is one of these integer constants:
6268**
6269** <ul>
6270** <li>  SQLITE_MUTEX_FAST
6271** <li>  SQLITE_MUTEX_RECURSIVE
6272** <li>  SQLITE_MUTEX_STATIC_MASTER
6273** <li>  SQLITE_MUTEX_STATIC_MEM
6274** <li>  SQLITE_MUTEX_STATIC_MEM2
6275** <li>  SQLITE_MUTEX_STATIC_PRNG
6276** <li>  SQLITE_MUTEX_STATIC_LRU
6277** <li>  SQLITE_MUTEX_STATIC_LRU2
6278** </ul>)^
6279**
6280** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
6281** cause sqlite3_mutex_alloc() to create
6282** a new mutex.  ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
6283** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
6284** The mutex implementation does not need to make a distinction
6285** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
6286** not want to.  ^SQLite will only request a recursive mutex in
6287** cases where it really needs one.  ^If a faster non-recursive mutex
6288** implementation is available on the host platform, the mutex subsystem
6289** might return such a mutex in response to SQLITE_MUTEX_FAST.
6290**
6291** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
6292** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
6293** a pointer to a static preexisting mutex.  ^Six static mutexes are
6294** used by the current version of SQLite.  Future versions of SQLite
6295** may add additional static mutexes.  Static mutexes are for internal
6296** use by SQLite only.  Applications that use SQLite mutexes should
6297** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
6298** SQLITE_MUTEX_RECURSIVE.
6299**
6300** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
6301** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
6302** returns a different mutex on every call.  ^But for the static
6303** mutex types, the same mutex is returned on every call that has
6304** the same type number.
6305**
6306** ^The sqlite3_mutex_free() routine deallocates a previously
6307** allocated dynamic mutex.  ^SQLite is careful to deallocate every
6308** dynamic mutex that it allocates.  The dynamic mutexes must not be in
6309** use when they are deallocated.  Attempting to deallocate a static
6310** mutex results in undefined behavior.  ^SQLite never deallocates
6311** a static mutex.
6312**
6313** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
6314** to enter a mutex.  ^If another thread is already within the mutex,
6315** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
6316** SQLITE_BUSY.  ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
6317** upon successful entry.  ^(Mutexes created using
6318** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
6319** In such cases the,
6320** mutex must be exited an equal number of times before another thread
6321** can enter.)^  ^(If the same thread tries to enter any other
6322** kind of mutex more than once, the behavior is undefined.
6323** SQLite will never exhibit
6324** such behavior in its own use of mutexes.)^
6325**
6326** ^(Some systems (for example, Windows 95) do not support the operation
6327** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
6328** will always return SQLITE_BUSY.  The SQLite core only ever uses
6329** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^
6330**
6331** ^The sqlite3_mutex_leave() routine exits a mutex that was
6332** previously entered by the same thread.   ^(The behavior
6333** is undefined if the mutex is not currently entered by the
6334** calling thread or is not currently allocated.  SQLite will
6335** never do either.)^
6336**
6337** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
6338** sqlite3_mutex_leave() is a NULL pointer, then all three routines
6339** behave as no-ops.
6340**
6341** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
6342*/
6343SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
6344SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
6345SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
6346SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
6347SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
6348
6349/*
6350** CAPI3REF: Mutex Methods Object
6351**
6352** An instance of this structure defines the low-level routines
6353** used to allocate and use mutexes.
6354**
6355** Usually, the default mutex implementations provided by SQLite are
6356** sufficient, however the user has the option of substituting a custom
6357** implementation for specialized deployments or systems for which SQLite
6358** does not provide a suitable implementation. In this case, the user
6359** creates and populates an instance of this structure to pass
6360** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
6361** Additionally, an instance of this structure can be used as an
6362** output variable when querying the system for the current mutex
6363** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
6364**
6365** ^The xMutexInit method defined by this structure is invoked as
6366** part of system initialization by the sqlite3_initialize() function.
6367** ^The xMutexInit routine is called by SQLite exactly once for each
6368** effective call to [sqlite3_initialize()].
6369**
6370** ^The xMutexEnd method defined by this structure is invoked as
6371** part of system shutdown by the sqlite3_shutdown() function. The
6372** implementation of this method is expected to release all outstanding
6373** resources obtained by the mutex methods implementation, especially
6374** those obtained by the xMutexInit method.  ^The xMutexEnd()
6375** interface is invoked exactly once for each call to [sqlite3_shutdown()].
6376**
6377** ^(The remaining seven methods defined by this structure (xMutexAlloc,
6378** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
6379** xMutexNotheld) implement the following interfaces (respectively):
6380**
6381** <ul>
6382**   <li>  [sqlite3_mutex_alloc()] </li>
6383**   <li>  [sqlite3_mutex_free()] </li>
6384**   <li>  [sqlite3_mutex_enter()] </li>
6385**   <li>  [sqlite3_mutex_try()] </li>
6386**   <li>  [sqlite3_mutex_leave()] </li>
6387**   <li>  [sqlite3_mutex_held()] </li>
6388**   <li>  [sqlite3_mutex_notheld()] </li>
6389** </ul>)^
6390**
6391** The only difference is that the public sqlite3_XXX functions enumerated
6392** above silently ignore any invocations that pass a NULL pointer instead
6393** of a valid mutex handle. The implementations of the methods defined
6394** by this structure are not required to handle this case, the results
6395** of passing a NULL pointer instead of a valid mutex handle are undefined
6396** (i.e. it is acceptable to provide an implementation that segfaults if
6397** it is passed a NULL pointer).
6398**
6399** The xMutexInit() method must be threadsafe.  ^It must be harmless to
6400** invoke xMutexInit() multiple times within the same process and without
6401** intervening calls to xMutexEnd().  Second and subsequent calls to
6402** xMutexInit() must be no-ops.
6403**
6404** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
6405** and its associates).  ^Similarly, xMutexAlloc() must not use SQLite memory
6406** allocation for a static mutex.  ^However xMutexAlloc() may use SQLite
6407** memory allocation for a fast or recursive mutex.
6408**
6409** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
6410** called, but only if the prior call to xMutexInit returned SQLITE_OK.
6411** If xMutexInit fails in any way, it is expected to clean up after itself
6412** prior to returning.
6413*/
6414typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
6415struct sqlite3_mutex_methods {
6416  int (*xMutexInit)(void);
6417  int (*xMutexEnd)(void);
6418  sqlite3_mutex *(*xMutexAlloc)(int);
6419  void (*xMutexFree)(sqlite3_mutex *);
6420  void (*xMutexEnter)(sqlite3_mutex *);
6421  int (*xMutexTry)(sqlite3_mutex *);
6422  void (*xMutexLeave)(sqlite3_mutex *);
6423  int (*xMutexHeld)(sqlite3_mutex *);
6424  int (*xMutexNotheld)(sqlite3_mutex *);
6425};
6426
6427/*
6428** CAPI3REF: Mutex Verification Routines
6429**
6430** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
6431** are intended for use inside assert() statements.  ^The SQLite core
6432** never uses these routines except inside an assert() and applications
6433** are advised to follow the lead of the core.  ^The SQLite core only
6434** provides implementations for these routines when it is compiled
6435** with the SQLITE_DEBUG flag.  ^External mutex implementations
6436** are only required to provide these routines if SQLITE_DEBUG is
6437** defined and if NDEBUG is not defined.
6438**
6439** ^These routines should return true if the mutex in their argument
6440** is held or not held, respectively, by the calling thread.
6441**
6442** ^The implementation is not required to provide versions of these
6443** routines that actually work. If the implementation does not provide working
6444** versions of these routines, it should at least provide stubs that always
6445** return true so that one does not get spurious assertion failures.
6446**
6447** ^If the argument to sqlite3_mutex_held() is a NULL pointer then
6448** the routine should return 1.   This seems counter-intuitive since
6449** clearly the mutex cannot be held if it does not exist.  But
6450** the reason the mutex does not exist is because the build is not
6451** using mutexes.  And we do not want the assert() containing the
6452** call to sqlite3_mutex_held() to fail, so a non-zero return is
6453** the appropriate thing to do.  ^The sqlite3_mutex_notheld()
6454** interface should also return 1 when given a NULL pointer.
6455*/
6456#ifndef NDEBUG
6457SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
6458SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
6459#endif
6460
6461/*
6462** CAPI3REF: Mutex Types
6463**
6464** The [sqlite3_mutex_alloc()] interface takes a single argument
6465** which is one of these integer constants.
6466**
6467** The set of static mutexes may change from one SQLite release to the
6468** next.  Applications that override the built-in mutex logic must be
6469** prepared to accommodate additional static mutexes.
6470*/
6471#define SQLITE_MUTEX_FAST             0
6472#define SQLITE_MUTEX_RECURSIVE        1
6473#define SQLITE_MUTEX_STATIC_MASTER    2
6474#define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
6475#define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */
6476#define SQLITE_MUTEX_STATIC_OPEN      4  /* sqlite3BtreeOpen() */
6477#define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
6478#define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
6479#define SQLITE_MUTEX_STATIC_LRU2      7  /* NOT USED */
6480#define SQLITE_MUTEX_STATIC_PMEM      7  /* sqlite3PageMalloc() */
6481
6482/*
6483** CAPI3REF: Retrieve the mutex for a database connection
6484**
6485** ^This interface returns a pointer the [sqlite3_mutex] object that
6486** serializes access to the [database connection] given in the argument
6487** when the [threading mode] is Serialized.
6488** ^If the [threading mode] is Single-thread or Multi-thread then this
6489** routine returns a NULL pointer.
6490*/
6491SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
6492
6493/*
6494** CAPI3REF: Low-Level Control Of Database Files
6495**
6496** ^The [sqlite3_file_control()] interface makes a direct call to the
6497** xFileControl method for the [sqlite3_io_methods] object associated
6498** with a particular database identified by the second argument. ^The
6499** name of the database is "main" for the main database or "temp" for the
6500** TEMP database, or the name that appears after the AS keyword for
6501** databases that are added using the [ATTACH] SQL command.
6502** ^A NULL pointer can be used in place of "main" to refer to the
6503** main database file.
6504** ^The third and fourth parameters to this routine
6505** are passed directly through to the second and third parameters of
6506** the xFileControl method.  ^The return value of the xFileControl
6507** method becomes the return value of this routine.
6508**
6509** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
6510** a pointer to the underlying [sqlite3_file] object to be written into
6511** the space pointed to by the 4th parameter.  ^The SQLITE_FCNTL_FILE_POINTER
6512** case is a short-circuit path which does not actually invoke the
6513** underlying sqlite3_io_methods.xFileControl method.
6514**
6515** ^If the second parameter (zDbName) does not match the name of any
6516** open database file, then SQLITE_ERROR is returned.  ^This error
6517** code is not remembered and will not be recalled by [sqlite3_errcode()]
6518** or [sqlite3_errmsg()].  The underlying xFileControl method might
6519** also return SQLITE_ERROR.  There is no way to distinguish between
6520** an incorrect zDbName and an SQLITE_ERROR return from the underlying
6521** xFileControl method.
6522**
6523** See also: [SQLITE_FCNTL_LOCKSTATE]
6524*/
6525SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
6526
6527/*
6528** CAPI3REF: Testing Interface
6529**
6530** ^The sqlite3_test_control() interface is used to read out internal
6531** state of SQLite and to inject faults into SQLite for testing
6532** purposes.  ^The first parameter is an operation code that determines
6533** the number, meaning, and operation of all subsequent parameters.
6534**
6535** This interface is not for use by applications.  It exists solely
6536** for verifying the correct operation of the SQLite library.  Depending
6537** on how the SQLite library is compiled, this interface might not exist.
6538**
6539** The details of the operation codes, their meanings, the parameters
6540** they take, and what they do are all subject to change without notice.
6541** Unlike most of the SQLite API, this function is not guaranteed to
6542** operate consistently from one release to the next.
6543*/
6544SQLITE_API int sqlite3_test_control(int op, ...);
6545
6546/*
6547** CAPI3REF: Testing Interface Operation Codes
6548**
6549** These constants are the valid operation code parameters used
6550** as the first argument to [sqlite3_test_control()].
6551**
6552** These parameters and their meanings are subject to change
6553** without notice.  These values are for testing purposes only.
6554** Applications should not use any of these parameters or the
6555** [sqlite3_test_control()] interface.
6556*/
6557#define SQLITE_TESTCTRL_FIRST                    5
6558#define SQLITE_TESTCTRL_PRNG_SAVE                5
6559#define SQLITE_TESTCTRL_PRNG_RESTORE             6
6560#define SQLITE_TESTCTRL_PRNG_RESET               7
6561#define SQLITE_TESTCTRL_BITVEC_TEST              8
6562#define SQLITE_TESTCTRL_FAULT_INSTALL            9
6563#define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
6564#define SQLITE_TESTCTRL_PENDING_BYTE            11
6565#define SQLITE_TESTCTRL_ASSERT                  12
6566#define SQLITE_TESTCTRL_ALWAYS                  13
6567#define SQLITE_TESTCTRL_RESERVE                 14
6568#define SQLITE_TESTCTRL_OPTIMIZATIONS           15
6569#define SQLITE_TESTCTRL_ISKEYWORD               16
6570#define SQLITE_TESTCTRL_SCRATCHMALLOC           17
6571#define SQLITE_TESTCTRL_LOCALTIME_FAULT         18
6572#define SQLITE_TESTCTRL_EXPLAIN_STMT            19
6573#define SQLITE_TESTCTRL_LAST                    19
6574
6575/*
6576** CAPI3REF: SQLite Runtime Status
6577**
6578** ^This interface is used to retrieve runtime status information
6579** about the performance of SQLite, and optionally to reset various
6580** highwater marks.  ^The first argument is an integer code for
6581** the specific parameter to measure.  ^(Recognized integer codes
6582** are of the form [status parameters | SQLITE_STATUS_...].)^
6583** ^The current value of the parameter is returned into *pCurrent.
6584** ^The highest recorded value is returned in *pHighwater.  ^If the
6585** resetFlag is true, then the highest record value is reset after
6586** *pHighwater is written.  ^(Some parameters do not record the highest
6587** value.  For those parameters
6588** nothing is written into *pHighwater and the resetFlag is ignored.)^
6589** ^(Other parameters record only the highwater mark and not the current
6590** value.  For these latter parameters nothing is written into *pCurrent.)^
6591**
6592** ^The sqlite3_status() routine returns SQLITE_OK on success and a
6593** non-zero [error code] on failure.
6594**
6595** This routine is threadsafe but is not atomic.  This routine can be
6596** called while other threads are running the same or different SQLite
6597** interfaces.  However the values returned in *pCurrent and
6598** *pHighwater reflect the status of SQLite at different points in time
6599** and it is possible that another thread might change the parameter
6600** in between the times when *pCurrent and *pHighwater are written.
6601**
6602** See also: [sqlite3_db_status()]
6603*/
6604SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
6605
6606
6607/*
6608** CAPI3REF: Status Parameters
6609** KEYWORDS: {status parameters}
6610**
6611** These integer constants designate various run-time status parameters
6612** that can be returned by [sqlite3_status()].
6613**
6614** <dl>
6615** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
6616** <dd>This parameter is the current amount of memory checked out
6617** using [sqlite3_malloc()], either directly or indirectly.  The
6618** figure includes calls made to [sqlite3_malloc()] by the application
6619** and internal memory usage by the SQLite library.  Scratch memory
6620** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
6621** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
6622** this parameter.  The amount returned is the sum of the allocation
6623** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
6624**
6625** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
6626** <dd>This parameter records the largest memory allocation request
6627** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
6628** internal equivalents).  Only the value returned in the
6629** *pHighwater parameter to [sqlite3_status()] is of interest.
6630** The value written into the *pCurrent parameter is undefined.</dd>)^
6631**
6632** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
6633** <dd>This parameter records the number of separate memory allocations
6634** currently checked out.</dd>)^
6635**
6636** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
6637** <dd>This parameter returns the number of pages used out of the
6638** [pagecache memory allocator] that was configured using
6639** [SQLITE_CONFIG_PAGECACHE].  The
6640** value returned is in pages, not in bytes.</dd>)^
6641**
6642** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
6643** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
6644** <dd>This parameter returns the number of bytes of page cache
6645** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
6646** buffer and where forced to overflow to [sqlite3_malloc()].  The
6647** returned value includes allocations that overflowed because they
6648** where too large (they were larger than the "sz" parameter to
6649** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
6650** no space was left in the page cache.</dd>)^
6651**
6652** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
6653** <dd>This parameter records the largest memory allocation request
6654** handed to [pagecache memory allocator].  Only the value returned in the
6655** *pHighwater parameter to [sqlite3_status()] is of interest.
6656** The value written into the *pCurrent parameter is undefined.</dd>)^
6657**
6658** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
6659** <dd>This parameter returns the number of allocations used out of the
6660** [scratch memory allocator] configured using
6661** [SQLITE_CONFIG_SCRATCH].  The value returned is in allocations, not
6662** in bytes.  Since a single thread may only have one scratch allocation
6663** outstanding at time, this parameter also reports the number of threads
6664** using scratch memory at the same time.</dd>)^
6665**
6666** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
6667** <dd>This parameter returns the number of bytes of scratch memory
6668** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
6669** buffer and where forced to overflow to [sqlite3_malloc()].  The values
6670** returned include overflows because the requested allocation was too
6671** larger (that is, because the requested allocation was larger than the
6672** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
6673** slots were available.
6674** </dd>)^
6675**
6676** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
6677** <dd>This parameter records the largest memory allocation request
6678** handed to [scratch memory allocator].  Only the value returned in the
6679** *pHighwater parameter to [sqlite3_status()] is of interest.
6680** The value written into the *pCurrent parameter is undefined.</dd>)^
6681**
6682** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
6683** <dd>This parameter records the deepest parser stack.  It is only
6684** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
6685** </dl>
6686**
6687** New status parameters may be added from time to time.
6688*/
6689#define SQLITE_STATUS_MEMORY_USED          0
6690#define SQLITE_STATUS_PAGECACHE_USED       1
6691#define SQLITE_STATUS_PAGECACHE_OVERFLOW   2
6692#define SQLITE_STATUS_SCRATCH_USED         3
6693#define SQLITE_STATUS_SCRATCH_OVERFLOW     4
6694#define SQLITE_STATUS_MALLOC_SIZE          5
6695#define SQLITE_STATUS_PARSER_STACK         6
6696#define SQLITE_STATUS_PAGECACHE_SIZE       7
6697#define SQLITE_STATUS_SCRATCH_SIZE         8
6698#define SQLITE_STATUS_MALLOC_COUNT         9
6699
6700/*
6701** CAPI3REF: Database Connection Status
6702**
6703** ^This interface is used to retrieve runtime status information
6704** about a single [database connection].  ^The first argument is the
6705** database connection object to be interrogated.  ^The second argument
6706** is an integer constant, taken from the set of
6707** [SQLITE_DBSTATUS options], that
6708** determines the parameter to interrogate.  The set of
6709** [SQLITE_DBSTATUS options] is likely
6710** to grow in future releases of SQLite.
6711**
6712** ^The current value of the requested parameter is written into *pCur
6713** and the highest instantaneous value is written into *pHiwtr.  ^If
6714** the resetFlg is true, then the highest instantaneous value is
6715** reset back down to the current value.
6716**
6717** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
6718** non-zero [error code] on failure.
6719**
6720** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
6721*/
6722SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
6723
6724/*
6725** CAPI3REF: Status Parameters for database connections
6726** KEYWORDS: {SQLITE_DBSTATUS options}
6727**
6728** These constants are the available integer "verbs" that can be passed as
6729** the second argument to the [sqlite3_db_status()] interface.
6730**
6731** New verbs may be added in future releases of SQLite. Existing verbs
6732** might be discontinued. Applications should check the return code from
6733** [sqlite3_db_status()] to make sure that the call worked.
6734** The [sqlite3_db_status()] interface will return a non-zero error code
6735** if a discontinued or unsupported verb is invoked.
6736**
6737** <dl>
6738** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
6739** <dd>This parameter returns the number of lookaside memory slots currently
6740** checked out.</dd>)^
6741**
6742** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
6743** <dd>This parameter returns the number malloc attempts that were
6744** satisfied using lookaside memory. Only the high-water value is meaningful;
6745** the current value is always zero.)^
6746**
6747** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
6748** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
6749** <dd>This parameter returns the number malloc attempts that might have
6750** been satisfied using lookaside memory but failed due to the amount of
6751** memory requested being larger than the lookaside slot size.
6752** Only the high-water value is meaningful;
6753** the current value is always zero.)^
6754**
6755** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
6756** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
6757** <dd>This parameter returns the number malloc attempts that might have
6758** been satisfied using lookaside memory but failed due to all lookaside
6759** memory already being in use.
6760** Only the high-water value is meaningful;
6761** the current value is always zero.)^
6762**
6763** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
6764** <dd>This parameter returns the approximate number of of bytes of heap
6765** memory used by all pager caches associated with the database connection.)^
6766** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
6767**
6768** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
6769** <dd>This parameter returns the approximate number of of bytes of heap
6770** memory used to store the schema for all databases associated
6771** with the connection - main, temp, and any [ATTACH]-ed databases.)^
6772** ^The full amount of memory used by the schemas is reported, even if the
6773** schema memory is shared with other database connections due to
6774** [shared cache mode] being enabled.
6775** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
6776**
6777** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
6778** <dd>This parameter returns the approximate number of of bytes of heap
6779** and lookaside memory used by all prepared statements associated with
6780** the database connection.)^
6781** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
6782** </dd>
6783**
6784** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
6785** <dd>This parameter returns the number of pager cache hits that have
6786** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
6787** is always 0.
6788** </dd>
6789**
6790** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
6791** <dd>This parameter returns the number of pager cache misses that have
6792** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
6793** is always 0.
6794** </dd>
6795**
6796** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
6797** <dd>This parameter returns the number of dirty cache entries that have
6798** been written to disk. Specifically, the number of pages written to the
6799** wal file in wal mode databases, or the number of pages written to the
6800** database file in rollback mode databases. Any pages written as part of
6801** transaction rollback or database recovery operations are not included.
6802** If an IO or other error occurs while writing a page to disk, the effect
6803** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
6804** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
6805** </dd>
6806** </dl>
6807*/
6808#define SQLITE_DBSTATUS_LOOKASIDE_USED       0
6809#define SQLITE_DBSTATUS_CACHE_USED           1
6810#define SQLITE_DBSTATUS_SCHEMA_USED          2
6811#define SQLITE_DBSTATUS_STMT_USED            3
6812#define SQLITE_DBSTATUS_LOOKASIDE_HIT        4
6813#define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE  5
6814#define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL  6
6815#define SQLITE_DBSTATUS_CACHE_HIT            7
6816#define SQLITE_DBSTATUS_CACHE_MISS           8
6817#define SQLITE_DBSTATUS_CACHE_WRITE          9
6818#define SQLITE_DBSTATUS_MAX                  9   /* Largest defined DBSTATUS */
6819
6820
6821/*
6822** CAPI3REF: Prepared Statement Status
6823**
6824** ^(Each prepared statement maintains various
6825** [SQLITE_STMTSTATUS counters] that measure the number
6826** of times it has performed specific operations.)^  These counters can
6827** be used to monitor the performance characteristics of the prepared
6828** statements.  For example, if the number of table steps greatly exceeds
6829** the number of table searches or result rows, that would tend to indicate
6830** that the prepared statement is using a full table scan rather than
6831** an index.
6832**
6833** ^(This interface is used to retrieve and reset counter values from
6834** a [prepared statement].  The first argument is the prepared statement
6835** object to be interrogated.  The second argument
6836** is an integer code for a specific [SQLITE_STMTSTATUS counter]
6837** to be interrogated.)^
6838** ^The current value of the requested counter is returned.
6839** ^If the resetFlg is true, then the counter is reset to zero after this
6840** interface call returns.
6841**
6842** See also: [sqlite3_status()] and [sqlite3_db_status()].
6843*/
6844SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
6845
6846/*
6847** CAPI3REF: Status Parameters for prepared statements
6848** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
6849**
6850** These preprocessor macros define integer codes that name counter
6851** values associated with the [sqlite3_stmt_status()] interface.
6852** The meanings of the various counters are as follows:
6853**
6854** <dl>
6855** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
6856** <dd>^This is the number of times that SQLite has stepped forward in
6857** a table as part of a full table scan.  Large numbers for this counter
6858** may indicate opportunities for performance improvement through
6859** careful use of indices.</dd>
6860**
6861** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
6862** <dd>^This is the number of sort operations that have occurred.
6863** A non-zero value in this counter may indicate an opportunity to
6864** improvement performance through careful use of indices.</dd>
6865**
6866** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
6867** <dd>^This is the number of rows inserted into transient indices that
6868** were created automatically in order to help joins run faster.
6869** A non-zero value in this counter may indicate an opportunity to
6870** improvement performance by adding permanent indices that do not
6871** need to be reinitialized each time the statement is run.</dd>
6872** </dl>
6873*/
6874#define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
6875#define SQLITE_STMTSTATUS_SORT              2
6876#define SQLITE_STMTSTATUS_AUTOINDEX         3
6877
6878/*
6879** CAPI3REF: Custom Page Cache Object
6880**
6881** The sqlite3_pcache type is opaque.  It is implemented by
6882** the pluggable module.  The SQLite core has no knowledge of
6883** its size or internal structure and never deals with the
6884** sqlite3_pcache object except by holding and passing pointers
6885** to the object.
6886**
6887** See [sqlite3_pcache_methods2] for additional information.
6888*/
6889typedef struct sqlite3_pcache sqlite3_pcache;
6890
6891/*
6892** CAPI3REF: Custom Page Cache Object
6893**
6894** The sqlite3_pcache_page object represents a single page in the
6895** page cache.  The page cache will allocate instances of this
6896** object.  Various methods of the page cache use pointers to instances
6897** of this object as parameters or as their return value.
6898**
6899** See [sqlite3_pcache_methods2] for additional information.
6900*/
6901typedef struct sqlite3_pcache_page sqlite3_pcache_page;
6902struct sqlite3_pcache_page {
6903  void *pBuf;        /* The content of the page */
6904  void *pExtra;      /* Extra information associated with the page */
6905};
6906
6907/*
6908** CAPI3REF: Application Defined Page Cache.
6909** KEYWORDS: {page cache}
6910**
6911** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
6912** register an alternative page cache implementation by passing in an
6913** instance of the sqlite3_pcache_methods2 structure.)^
6914** In many applications, most of the heap memory allocated by
6915** SQLite is used for the page cache.
6916** By implementing a
6917** custom page cache using this API, an application can better control
6918** the amount of memory consumed by SQLite, the way in which
6919** that memory is allocated and released, and the policies used to
6920** determine exactly which parts of a database file are cached and for
6921** how long.
6922**
6923** The alternative page cache mechanism is an
6924** extreme measure that is only needed by the most demanding applications.
6925** The built-in page cache is recommended for most uses.
6926**
6927** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
6928** internal buffer by SQLite within the call to [sqlite3_config].  Hence
6929** the application may discard the parameter after the call to
6930** [sqlite3_config()] returns.)^
6931**
6932** [[the xInit() page cache method]]
6933** ^(The xInit() method is called once for each effective
6934** call to [sqlite3_initialize()])^
6935** (usually only once during the lifetime of the process). ^(The xInit()
6936** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
6937** The intent of the xInit() method is to set up global data structures
6938** required by the custom page cache implementation.
6939** ^(If the xInit() method is NULL, then the
6940** built-in default page cache is used instead of the application defined
6941** page cache.)^
6942**
6943** [[the xShutdown() page cache method]]
6944** ^The xShutdown() method is called by [sqlite3_shutdown()].
6945** It can be used to clean up
6946** any outstanding resources before process shutdown, if required.
6947** ^The xShutdown() method may be NULL.
6948**
6949** ^SQLite automatically serializes calls to the xInit method,
6950** so the xInit method need not be threadsafe.  ^The
6951** xShutdown method is only called from [sqlite3_shutdown()] so it does
6952** not need to be threadsafe either.  All other methods must be threadsafe
6953** in multithreaded applications.
6954**
6955** ^SQLite will never invoke xInit() more than once without an intervening
6956** call to xShutdown().
6957**
6958** [[the xCreate() page cache methods]]
6959** ^SQLite invokes the xCreate() method to construct a new cache instance.
6960** SQLite will typically create one cache instance for each open database file,
6961** though this is not guaranteed. ^The
6962** first parameter, szPage, is the size in bytes of the pages that must
6963** be allocated by the cache.  ^szPage will always a power of two.  ^The
6964** second parameter szExtra is a number of bytes of extra storage
6965** associated with each page cache entry.  ^The szExtra parameter will
6966** a number less than 250.  SQLite will use the
6967** extra szExtra bytes on each page to store metadata about the underlying
6968** database page on disk.  The value passed into szExtra depends
6969** on the SQLite version, the target platform, and how SQLite was compiled.
6970** ^The third argument to xCreate(), bPurgeable, is true if the cache being
6971** created will be used to cache database pages of a file stored on disk, or
6972** false if it is used for an in-memory database. The cache implementation
6973** does not have to do anything special based with the value of bPurgeable;
6974** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will
6975** never invoke xUnpin() except to deliberately delete a page.
6976** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
6977** false will always have the "discard" flag set to true.
6978** ^Hence, a cache created with bPurgeable false will
6979** never contain any unpinned pages.
6980**
6981** [[the xCachesize() page cache method]]
6982** ^(The xCachesize() method may be called at any time by SQLite to set the
6983** suggested maximum cache-size (number of pages stored by) the cache
6984** instance passed as the first argument. This is the value configured using
6985** the SQLite "[PRAGMA cache_size]" command.)^  As with the bPurgeable
6986** parameter, the implementation is not required to do anything with this
6987** value; it is advisory only.
6988**
6989** [[the xPagecount() page cache methods]]
6990** The xPagecount() method must return the number of pages currently
6991** stored in the cache, both pinned and unpinned.
6992**
6993** [[the xFetch() page cache methods]]
6994** The xFetch() method locates a page in the cache and returns a pointer to
6995** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
6996** The pBuf element of the returned sqlite3_pcache_page object will be a
6997** pointer to a buffer of szPage bytes used to store the content of a
6998** single database page.  The pExtra element of sqlite3_pcache_page will be
6999** a pointer to the szExtra bytes of extra storage that SQLite has requested
7000** for each entry in the page cache.
7001**
7002** The page to be fetched is determined by the key. ^The minimum key value
7003** is 1.  After it has been retrieved using xFetch, the page is considered
7004** to be "pinned".
7005**
7006** If the requested page is already in the page cache, then the page cache
7007** implementation must return a pointer to the page buffer with its content
7008** intact.  If the requested page is not already in the cache, then the
7009** cache implementation should use the value of the createFlag
7010** parameter to help it determined what action to take:
7011**
7012** <table border=1 width=85% align=center>
7013** <tr><th> createFlag <th> Behavior when page is not already in cache
7014** <tr><td> 0 <td> Do not allocate a new page.  Return NULL.
7015** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
7016**                 Otherwise return NULL.
7017** <tr><td> 2 <td> Make every effort to allocate a new page.  Only return
7018**                 NULL if allocating a new page is effectively impossible.
7019** </table>
7020**
7021** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  SQLite
7022** will only use a createFlag of 2 after a prior call with a createFlag of 1
7023** failed.)^  In between the to xFetch() calls, SQLite may
7024** attempt to unpin one or more cache pages by spilling the content of
7025** pinned pages to disk and synching the operating system disk cache.
7026**
7027** [[the xUnpin() page cache method]]
7028** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
7029** as its second argument.  If the third parameter, discard, is non-zero,
7030** then the page must be evicted from the cache.
7031** ^If the discard parameter is
7032** zero, then the page may be discarded or retained at the discretion of
7033** page cache implementation. ^The page cache implementation
7034** may choose to evict unpinned pages at any time.
7035**
7036** The cache must not perform any reference counting. A single
7037** call to xUnpin() unpins the page regardless of the number of prior calls
7038** to xFetch().
7039**
7040** [[the xRekey() page cache methods]]
7041** The xRekey() method is used to change the key value associated with the
7042** page passed as the second argument. If the cache
7043** previously contains an entry associated with newKey, it must be
7044** discarded. ^Any prior cache entry associated with newKey is guaranteed not
7045** to be pinned.
7046**
7047** When SQLite calls the xTruncate() method, the cache must discard all
7048** existing cache entries with page numbers (keys) greater than or equal
7049** to the value of the iLimit parameter passed to xTruncate(). If any
7050** of these pages are pinned, they are implicitly unpinned, meaning that
7051** they can be safely discarded.
7052**
7053** [[the xDestroy() page cache method]]
7054** ^The xDestroy() method is used to delete a cache allocated by xCreate().
7055** All resources associated with the specified cache should be freed. ^After
7056** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
7057** handle invalid, and will not use it with any other sqlite3_pcache_methods2
7058** functions.
7059**
7060** [[the xShrink() page cache method]]
7061** ^SQLite invokes the xShrink() method when it wants the page cache to
7062** free up as much of heap memory as possible.  The page cache implementation
7063** is not obligated to free any memory, but well-behaved implementations should
7064** do their best.
7065*/
7066typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
7067struct sqlite3_pcache_methods2 {
7068  int iVersion;
7069  void *pArg;
7070  int (*xInit)(void*);
7071  void (*xShutdown)(void*);
7072  sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
7073  void (*xCachesize)(sqlite3_pcache*, int nCachesize);
7074  int (*xPagecount)(sqlite3_pcache*);
7075  sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
7076  void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
7077  void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
7078      unsigned oldKey, unsigned newKey);
7079  void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
7080  void (*xDestroy)(sqlite3_pcache*);
7081  void (*xShrink)(sqlite3_pcache*);
7082};
7083
7084/*
7085** This is the obsolete pcache_methods object that has now been replaced
7086** by sqlite3_pcache_methods2.  This object is not used by SQLite.  It is
7087** retained in the header file for backwards compatibility only.
7088*/
7089typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
7090struct sqlite3_pcache_methods {
7091  void *pArg;
7092  int (*xInit)(void*);
7093  void (*xShutdown)(void*);
7094  sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
7095  void (*xCachesize)(sqlite3_pcache*, int nCachesize);
7096  int (*xPagecount)(sqlite3_pcache*);
7097  void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
7098  void (*xUnpin)(sqlite3_pcache*, void*, int discard);
7099  void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
7100  void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
7101  void (*xDestroy)(sqlite3_pcache*);
7102};
7103
7104
7105/*
7106** CAPI3REF: Online Backup Object
7107**
7108** The sqlite3_backup object records state information about an ongoing
7109** online backup operation.  ^The sqlite3_backup object is created by
7110** a call to [sqlite3_backup_init()] and is destroyed by a call to
7111** [sqlite3_backup_finish()].
7112**
7113** See Also: [Using the SQLite Online Backup API]
7114*/
7115typedef struct sqlite3_backup sqlite3_backup;
7116
7117/*
7118** CAPI3REF: Online Backup API.
7119**
7120** The backup API copies the content of one database into another.
7121** It is useful either for creating backups of databases or
7122** for copying in-memory databases to or from persistent files.
7123**
7124** See Also: [Using the SQLite Online Backup API]
7125**
7126** ^SQLite holds a write transaction open on the destination database file
7127** for the duration of the backup operation.
7128** ^The source database is read-locked only while it is being read;
7129** it is not locked continuously for the entire backup operation.
7130** ^Thus, the backup may be performed on a live source database without
7131** preventing other database connections from
7132** reading or writing to the source database while the backup is underway.
7133**
7134** ^(To perform a backup operation:
7135**   <ol>
7136**     <li><b>sqlite3_backup_init()</b> is called once to initialize the
7137**         backup,
7138**     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
7139**         the data between the two databases, and finally
7140**     <li><b>sqlite3_backup_finish()</b> is called to release all resources
7141**         associated with the backup operation.
7142**   </ol>)^
7143** There should be exactly one call to sqlite3_backup_finish() for each
7144** successful call to sqlite3_backup_init().
7145**
7146** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
7147**
7148** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
7149** [database connection] associated with the destination database
7150** and the database name, respectively.
7151** ^The database name is "main" for the main database, "temp" for the
7152** temporary database, or the name specified after the AS keyword in
7153** an [ATTACH] statement for an attached database.
7154** ^The S and M arguments passed to
7155** sqlite3_backup_init(D,N,S,M) identify the [database connection]
7156** and database name of the source database, respectively.
7157** ^The source and destination [database connections] (parameters S and D)
7158** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
7159** an error.
7160**
7161** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
7162** returned and an error code and error message are stored in the
7163** destination [database connection] D.
7164** ^The error code and message for the failed call to sqlite3_backup_init()
7165** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
7166** [sqlite3_errmsg16()] functions.
7167** ^A successful call to sqlite3_backup_init() returns a pointer to an
7168** [sqlite3_backup] object.
7169** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
7170** sqlite3_backup_finish() functions to perform the specified backup
7171** operation.
7172**
7173** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
7174**
7175** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
7176** the source and destination databases specified by [sqlite3_backup] object B.
7177** ^If N is negative, all remaining source pages are copied.
7178** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
7179** are still more pages to be copied, then the function returns [SQLITE_OK].
7180** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
7181** from source to destination, then it returns [SQLITE_DONE].
7182** ^If an error occurs while running sqlite3_backup_step(B,N),
7183** then an [error code] is returned. ^As well as [SQLITE_OK] and
7184** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
7185** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
7186** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
7187**
7188** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
7189** <ol>
7190** <li> the destination database was opened read-only, or
7191** <li> the destination database is using write-ahead-log journaling
7192** and the destination and source page sizes differ, or
7193** <li> the destination database is an in-memory database and the
7194** destination and source page sizes differ.
7195** </ol>)^
7196**
7197** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
7198** the [sqlite3_busy_handler | busy-handler function]
7199** is invoked (if one is specified). ^If the
7200** busy-handler returns non-zero before the lock is available, then
7201** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
7202** sqlite3_backup_step() can be retried later. ^If the source
7203** [database connection]
7204** is being used to write to the source database when sqlite3_backup_step()
7205** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
7206** case the call to sqlite3_backup_step() can be retried later on. ^(If
7207** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
7208** [SQLITE_READONLY] is returned, then
7209** there is no point in retrying the call to sqlite3_backup_step(). These
7210** errors are considered fatal.)^  The application must accept
7211** that the backup operation has failed and pass the backup operation handle
7212** to the sqlite3_backup_finish() to release associated resources.
7213**
7214** ^The first call to sqlite3_backup_step() obtains an exclusive lock
7215** on the destination file. ^The exclusive lock is not released until either
7216** sqlite3_backup_finish() is called or the backup operation is complete
7217** and sqlite3_backup_step() returns [SQLITE_DONE].  ^Every call to
7218** sqlite3_backup_step() obtains a [shared lock] on the source database that
7219** lasts for the duration of the sqlite3_backup_step() call.
7220** ^Because the source database is not locked between calls to
7221** sqlite3_backup_step(), the source database may be modified mid-way
7222** through the backup process.  ^If the source database is modified by an
7223** external process or via a database connection other than the one being
7224** used by the backup operation, then the backup will be automatically
7225** restarted by the next call to sqlite3_backup_step(). ^If the source
7226** database is modified by the using the same database connection as is used
7227** by the backup operation, then the backup database is automatically
7228** updated at the same time.
7229**
7230** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
7231**
7232** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
7233** application wishes to abandon the backup operation, the application
7234** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
7235** ^The sqlite3_backup_finish() interfaces releases all
7236** resources associated with the [sqlite3_backup] object.
7237** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
7238** active write-transaction on the destination database is rolled back.
7239** The [sqlite3_backup] object is invalid
7240** and may not be used following a call to sqlite3_backup_finish().
7241**
7242** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
7243** sqlite3_backup_step() errors occurred, regardless or whether or not
7244** sqlite3_backup_step() completed.
7245** ^If an out-of-memory condition or IO error occurred during any prior
7246** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
7247** sqlite3_backup_finish() returns the corresponding [error code].
7248**
7249** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
7250** is not a permanent error and does not affect the return value of
7251** sqlite3_backup_finish().
7252**
7253** [[sqlite3_backup__remaining()]] [[sqlite3_backup_pagecount()]]
7254** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
7255**
7256** ^Each call to sqlite3_backup_step() sets two values inside
7257** the [sqlite3_backup] object: the number of pages still to be backed
7258** up and the total number of pages in the source database file.
7259** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
7260** retrieve these two values, respectively.
7261**
7262** ^The values returned by these functions are only updated by
7263** sqlite3_backup_step(). ^If the source database is modified during a backup
7264** operation, then the values are not updated to account for any extra
7265** pages that need to be updated or the size of the source database file
7266** changing.
7267**
7268** <b>Concurrent Usage of Database Handles</b>
7269**
7270** ^The source [database connection] may be used by the application for other
7271** purposes while a backup operation is underway or being initialized.
7272** ^If SQLite is compiled and configured to support threadsafe database
7273** connections, then the source database connection may be used concurrently
7274** from within other threads.
7275**
7276** However, the application must guarantee that the destination
7277** [database connection] is not passed to any other API (by any thread) after
7278** sqlite3_backup_init() is called and before the corresponding call to
7279** sqlite3_backup_finish().  SQLite does not currently check to see
7280** if the application incorrectly accesses the destination [database connection]
7281** and so no error code is reported, but the operations may malfunction
7282** nevertheless.  Use of the destination database connection while a
7283** backup is in progress might also also cause a mutex deadlock.
7284**
7285** If running in [shared cache mode], the application must
7286** guarantee that the shared cache used by the destination database
7287** is not accessed while the backup is running. In practice this means
7288** that the application must guarantee that the disk file being
7289** backed up to is not accessed by any connection within the process,
7290** not just the specific connection that was passed to sqlite3_backup_init().
7291**
7292** The [sqlite3_backup] object itself is partially threadsafe. Multiple
7293** threads may safely make multiple concurrent calls to sqlite3_backup_step().
7294** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
7295** APIs are not strictly speaking threadsafe. If they are invoked at the
7296** same time as another thread is invoking sqlite3_backup_step() it is
7297** possible that they return invalid values.
7298*/
7299SQLITE_API sqlite3_backup *sqlite3_backup_init(
7300  sqlite3 *pDest,                        /* Destination database handle */
7301  const char *zDestName,                 /* Destination database name */
7302  sqlite3 *pSource,                      /* Source database handle */
7303  const char *zSourceName                /* Source database name */
7304);
7305SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
7306SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
7307SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
7308SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
7309
7310/*
7311** CAPI3REF: Unlock Notification
7312**
7313** ^When running in shared-cache mode, a database operation may fail with
7314** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
7315** individual tables within the shared-cache cannot be obtained. See
7316** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
7317** ^This API may be used to register a callback that SQLite will invoke
7318** when the connection currently holding the required lock relinquishes it.
7319** ^This API is only available if the library was compiled with the
7320** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
7321**
7322** See Also: [Using the SQLite Unlock Notification Feature].
7323**
7324** ^Shared-cache locks are released when a database connection concludes
7325** its current transaction, either by committing it or rolling it back.
7326**
7327** ^When a connection (known as the blocked connection) fails to obtain a
7328** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
7329** identity of the database connection (the blocking connection) that
7330** has locked the required resource is stored internally. ^After an
7331** application receives an SQLITE_LOCKED error, it may call the
7332** sqlite3_unlock_notify() method with the blocked connection handle as
7333** the first argument to register for a callback that will be invoked
7334** when the blocking connections current transaction is concluded. ^The
7335** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
7336** call that concludes the blocking connections transaction.
7337**
7338** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
7339** there is a chance that the blocking connection will have already
7340** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
7341** If this happens, then the specified callback is invoked immediately,
7342** from within the call to sqlite3_unlock_notify().)^
7343**
7344** ^If the blocked connection is attempting to obtain a write-lock on a
7345** shared-cache table, and more than one other connection currently holds
7346** a read-lock on the same table, then SQLite arbitrarily selects one of
7347** the other connections to use as the blocking connection.
7348**
7349** ^(There may be at most one unlock-notify callback registered by a
7350** blocked connection. If sqlite3_unlock_notify() is called when the
7351** blocked connection already has a registered unlock-notify callback,
7352** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
7353** called with a NULL pointer as its second argument, then any existing
7354** unlock-notify callback is canceled. ^The blocked connections
7355** unlock-notify callback may also be canceled by closing the blocked
7356** connection using [sqlite3_close()].
7357**
7358** The unlock-notify callback is not reentrant. If an application invokes
7359** any sqlite3_xxx API functions from within an unlock-notify callback, a
7360** crash or deadlock may be the result.
7361**
7362** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
7363** returns SQLITE_OK.
7364**
7365** <b>Callback Invocation Details</b>
7366**
7367** When an unlock-notify callback is registered, the application provides a
7368** single void* pointer that is passed to the callback when it is invoked.
7369** However, the signature of the callback function allows SQLite to pass
7370** it an array of void* context pointers. The first argument passed to
7371** an unlock-notify callback is a pointer to an array of void* pointers,
7372** and the second is the number of entries in the array.
7373**
7374** When a blocking connections transaction is concluded, there may be
7375** more than one blocked connection that has registered for an unlock-notify
7376** callback. ^If two or more such blocked connections have specified the
7377** same callback function, then instead of invoking the callback function
7378** multiple times, it is invoked once with the set of void* context pointers
7379** specified by the blocked connections bundled together into an array.
7380** This gives the application an opportunity to prioritize any actions
7381** related to the set of unblocked database connections.
7382**
7383** <b>Deadlock Detection</b>
7384**
7385** Assuming that after registering for an unlock-notify callback a
7386** database waits for the callback to be issued before taking any further
7387** action (a reasonable assumption), then using this API may cause the
7388** application to deadlock. For example, if connection X is waiting for
7389** connection Y's transaction to be concluded, and similarly connection
7390** Y is waiting on connection X's transaction, then neither connection
7391** will proceed and the system may remain deadlocked indefinitely.
7392**
7393** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
7394** detection. ^If a given call to sqlite3_unlock_notify() would put the
7395** system in a deadlocked state, then SQLITE_LOCKED is returned and no
7396** unlock-notify callback is registered. The system is said to be in
7397** a deadlocked state if connection A has registered for an unlock-notify
7398** callback on the conclusion of connection B's transaction, and connection
7399** B has itself registered for an unlock-notify callback when connection
7400** A's transaction is concluded. ^Indirect deadlock is also detected, so
7401** the system is also considered to be deadlocked if connection B has
7402** registered for an unlock-notify callback on the conclusion of connection
7403** C's transaction, where connection C is waiting on connection A. ^Any
7404** number of levels of indirection are allowed.
7405**
7406** <b>The "DROP TABLE" Exception</b>
7407**
7408** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
7409** always appropriate to call sqlite3_unlock_notify(). There is however,
7410** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
7411** SQLite checks if there are any currently executing SELECT statements
7412** that belong to the same connection. If there are, SQLITE_LOCKED is
7413** returned. In this case there is no "blocking connection", so invoking
7414** sqlite3_unlock_notify() results in the unlock-notify callback being
7415** invoked immediately. If the application then re-attempts the "DROP TABLE"
7416** or "DROP INDEX" query, an infinite loop might be the result.
7417**
7418** One way around this problem is to check the extended error code returned
7419** by an sqlite3_step() call. ^(If there is a blocking connection, then the
7420** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
7421** the special "DROP TABLE/INDEX" case, the extended error code is just
7422** SQLITE_LOCKED.)^
7423*/
7424SQLITE_API int sqlite3_unlock_notify(
7425  sqlite3 *pBlocked,                          /* Waiting connection */
7426  void (*xNotify)(void **apArg, int nArg),    /* Callback function to invoke */
7427  void *pNotifyArg                            /* Argument to pass to xNotify */
7428);
7429
7430
7431/*
7432** CAPI3REF: String Comparison
7433**
7434** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
7435** and extensions to compare the contents of two buffers containing UTF-8
7436** strings in a case-independent fashion, using the same definition of "case
7437** independence" that SQLite uses internally when comparing identifiers.
7438*/
7439SQLITE_API int sqlite3_stricmp(const char *, const char *);
7440SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
7441
7442/*
7443** CAPI3REF: String Globbing
7444*
7445** ^The [sqlite3_strglob(P,X)] interface returns zero if string X matches
7446** the glob pattern P, and it returns non-zero if string X does not match
7447** the glob pattern P.  ^The definition of glob pattern matching used in
7448** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the
7449** SQL dialect used by SQLite.  ^The sqlite3_strglob(P,X) function is case
7450** sensitive.
7451**
7452** Note that this routine returns zero on a match and non-zero if the strings
7453** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
7454*/
7455SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr);
7456
7457/*
7458** CAPI3REF: Error Logging Interface
7459**
7460** ^The [sqlite3_log()] interface writes a message into the [error log]
7461** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
7462** ^If logging is enabled, the zFormat string and subsequent arguments are
7463** used with [sqlite3_snprintf()] to generate the final output string.
7464**
7465** The sqlite3_log() interface is intended for use by extensions such as
7466** virtual tables, collating functions, and SQL functions.  While there is
7467** nothing to prevent an application from calling sqlite3_log(), doing so
7468** is considered bad form.
7469**
7470** The zFormat string must not be NULL.
7471**
7472** To avoid deadlocks and other threading problems, the sqlite3_log() routine
7473** will not use dynamically allocated memory.  The log message is stored in
7474** a fixed-length buffer on the stack.  If the log message is longer than
7475** a few hundred characters, it will be truncated to the length of the
7476** buffer.
7477*/
7478SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
7479
7480/*
7481** CAPI3REF: Write-Ahead Log Commit Hook
7482**
7483** ^The [sqlite3_wal_hook()] function is used to register a callback that
7484** will be invoked each time a database connection commits data to a
7485** [write-ahead log] (i.e. whenever a transaction is committed in
7486** [journal_mode | journal_mode=WAL mode]).
7487**
7488** ^The callback is invoked by SQLite after the commit has taken place and
7489** the associated write-lock on the database released, so the implementation
7490** may read, write or [checkpoint] the database as required.
7491**
7492** ^The first parameter passed to the callback function when it is invoked
7493** is a copy of the third parameter passed to sqlite3_wal_hook() when
7494** registering the callback. ^The second is a copy of the database handle.
7495** ^The third parameter is the name of the database that was written to -
7496** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
7497** is the number of pages currently in the write-ahead log file,
7498** including those that were just committed.
7499**
7500** The callback function should normally return [SQLITE_OK].  ^If an error
7501** code is returned, that error will propagate back up through the
7502** SQLite code base to cause the statement that provoked the callback
7503** to report an error, though the commit will have still occurred. If the
7504** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
7505** that does not correspond to any valid SQLite error code, the results
7506** are undefined.
7507**
7508** A single database handle may have at most a single write-ahead log callback
7509** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
7510** previously registered write-ahead log callback. ^Note that the
7511** [sqlite3_wal_autocheckpoint()] interface and the
7512** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
7513** those overwrite any prior [sqlite3_wal_hook()] settings.
7514*/
7515SQLITE_API void *sqlite3_wal_hook(
7516  sqlite3*,
7517  int(*)(void *,sqlite3*,const char*,int),
7518  void*
7519);
7520
7521/*
7522** CAPI3REF: Configure an auto-checkpoint
7523**
7524** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
7525** [sqlite3_wal_hook()] that causes any database on [database connection] D
7526** to automatically [checkpoint]
7527** after committing a transaction if there are N or
7528** more frames in the [write-ahead log] file.  ^Passing zero or
7529** a negative value as the nFrame parameter disables automatic
7530** checkpoints entirely.
7531**
7532** ^The callback registered by this function replaces any existing callback
7533** registered using [sqlite3_wal_hook()].  ^Likewise, registering a callback
7534** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
7535** configured by this function.
7536**
7537** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
7538** from SQL.
7539**
7540** ^Every new [database connection] defaults to having the auto-checkpoint
7541** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
7542** pages.  The use of this interface
7543** is only necessary if the default setting is found to be suboptimal
7544** for a particular application.
7545*/
7546SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
7547
7548/*
7549** CAPI3REF: Checkpoint a database
7550**
7551** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X
7552** on [database connection] D to be [checkpointed].  ^If X is NULL or an
7553** empty string, then a checkpoint is run on all databases of
7554** connection D.  ^If the database connection D is not in
7555** [WAL | write-ahead log mode] then this interface is a harmless no-op.
7556**
7557** ^The [wal_checkpoint pragma] can be used to invoke this interface
7558** from SQL.  ^The [sqlite3_wal_autocheckpoint()] interface and the
7559** [wal_autocheckpoint pragma] can be used to cause this interface to be
7560** run whenever the WAL reaches a certain size threshold.
7561**
7562** See also: [sqlite3_wal_checkpoint_v2()]
7563*/
7564SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
7565
7566/*
7567** CAPI3REF: Checkpoint a database
7568**
7569** Run a checkpoint operation on WAL database zDb attached to database
7570** handle db. The specific operation is determined by the value of the
7571** eMode parameter:
7572**
7573** <dl>
7574** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
7575**   Checkpoint as many frames as possible without waiting for any database
7576**   readers or writers to finish. Sync the db file if all frames in the log
7577**   are checkpointed. This mode is the same as calling
7578**   sqlite3_wal_checkpoint(). The busy-handler callback is never invoked.
7579**
7580** <dt>SQLITE_CHECKPOINT_FULL<dd>
7581**   This mode blocks (calls the busy-handler callback) until there is no
7582**   database writer and all readers are reading from the most recent database
7583**   snapshot. It then checkpoints all frames in the log file and syncs the
7584**   database file. This call blocks database writers while it is running,
7585**   but not database readers.
7586**
7587** <dt>SQLITE_CHECKPOINT_RESTART<dd>
7588**   This mode works the same way as SQLITE_CHECKPOINT_FULL, except after
7589**   checkpointing the log file it blocks (calls the busy-handler callback)
7590**   until all readers are reading from the database file only. This ensures
7591**   that the next client to write to the database file restarts the log file
7592**   from the beginning. This call blocks database writers while it is running,
7593**   but not database readers.
7594** </dl>
7595**
7596** If pnLog is not NULL, then *pnLog is set to the total number of frames in
7597** the log file before returning. If pnCkpt is not NULL, then *pnCkpt is set to
7598** the total number of checkpointed frames (including any that were already
7599** checkpointed when this function is called). *pnLog and *pnCkpt may be
7600** populated even if sqlite3_wal_checkpoint_v2() returns other than SQLITE_OK.
7601** If no values are available because of an error, they are both set to -1
7602** before returning to communicate this to the caller.
7603**
7604** All calls obtain an exclusive "checkpoint" lock on the database file. If
7605** any other process is running a checkpoint operation at the same time, the
7606** lock cannot be obtained and SQLITE_BUSY is returned. Even if there is a
7607** busy-handler configured, it will not be invoked in this case.
7608**
7609** The SQLITE_CHECKPOINT_FULL and RESTART modes also obtain the exclusive
7610** "writer" lock on the database file. If the writer lock cannot be obtained
7611** immediately, and a busy-handler is configured, it is invoked and the writer
7612** lock retried until either the busy-handler returns 0 or the lock is
7613** successfully obtained. The busy-handler is also invoked while waiting for
7614** database readers as described above. If the busy-handler returns 0 before
7615** the writer lock is obtained or while waiting for database readers, the
7616** checkpoint operation proceeds from that point in the same way as
7617** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
7618** without blocking any further. SQLITE_BUSY is returned in this case.
7619**
7620** If parameter zDb is NULL or points to a zero length string, then the
7621** specified operation is attempted on all WAL databases. In this case the
7622** values written to output parameters *pnLog and *pnCkpt are undefined. If
7623** an SQLITE_BUSY error is encountered when processing one or more of the
7624** attached WAL databases, the operation is still attempted on any remaining
7625** attached databases and SQLITE_BUSY is returned to the caller. If any other
7626** error occurs while processing an attached database, processing is abandoned
7627** and the error code returned to the caller immediately. If no error
7628** (SQLITE_BUSY or otherwise) is encountered while processing the attached
7629** databases, SQLITE_OK is returned.
7630**
7631** If database zDb is the name of an attached database that is not in WAL
7632** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. If
7633** zDb is not NULL (or a zero length string) and is not the name of any
7634** attached database, SQLITE_ERROR is returned to the caller.
7635*/
7636SQLITE_API int sqlite3_wal_checkpoint_v2(
7637  sqlite3 *db,                    /* Database handle */
7638  const char *zDb,                /* Name of attached database (or NULL) */
7639  int eMode,                      /* SQLITE_CHECKPOINT_* value */
7640  int *pnLog,                     /* OUT: Size of WAL log in frames */
7641  int *pnCkpt                     /* OUT: Total number of frames checkpointed */
7642);
7643
7644/*
7645** CAPI3REF: Checkpoint operation parameters
7646**
7647** These constants can be used as the 3rd parameter to
7648** [sqlite3_wal_checkpoint_v2()].  See the [sqlite3_wal_checkpoint_v2()]
7649** documentation for additional information about the meaning and use of
7650** each of these values.
7651*/
7652#define SQLITE_CHECKPOINT_PASSIVE 0
7653#define SQLITE_CHECKPOINT_FULL    1
7654#define SQLITE_CHECKPOINT_RESTART 2
7655
7656/*
7657** CAPI3REF: Virtual Table Interface Configuration
7658**
7659** This function may be called by either the [xConnect] or [xCreate] method
7660** of a [virtual table] implementation to configure
7661** various facets of the virtual table interface.
7662**
7663** If this interface is invoked outside the context of an xConnect or
7664** xCreate virtual table method then the behavior is undefined.
7665**
7666** At present, there is only one option that may be configured using
7667** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].)  Further options
7668** may be added in the future.
7669*/
7670SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
7671
7672/*
7673** CAPI3REF: Virtual Table Configuration Options
7674**
7675** These macros define the various options to the
7676** [sqlite3_vtab_config()] interface that [virtual table] implementations
7677** can use to customize and optimize their behavior.
7678**
7679** <dl>
7680** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
7681** <dd>Calls of the form
7682** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
7683** where X is an integer.  If X is zero, then the [virtual table] whose
7684** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
7685** support constraints.  In this configuration (which is the default) if
7686** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
7687** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
7688** specified as part of the users SQL statement, regardless of the actual
7689** ON CONFLICT mode specified.
7690**
7691** If X is non-zero, then the virtual table implementation guarantees
7692** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
7693** any modifications to internal or persistent data structures have been made.
7694** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
7695** is able to roll back a statement or database transaction, and abandon
7696** or continue processing the current SQL statement as appropriate.
7697** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
7698** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
7699** had been ABORT.
7700**
7701** Virtual table implementations that are required to handle OR REPLACE
7702** must do so within the [xUpdate] method. If a call to the
7703** [sqlite3_vtab_on_conflict()] function indicates that the current ON
7704** CONFLICT policy is REPLACE, the virtual table implementation should
7705** silently replace the appropriate rows within the xUpdate callback and
7706** return SQLITE_OK. Or, if this is not possible, it may return
7707** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
7708** constraint handling.
7709** </dl>
7710*/
7711#define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
7712
7713/*
7714** CAPI3REF: Determine The Virtual Table Conflict Policy
7715**
7716** This function may only be called from within a call to the [xUpdate] method
7717** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
7718** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
7719** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
7720** of the SQL statement that triggered the call to the [xUpdate] method of the
7721** [virtual table].
7722*/
7723SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
7724
7725/*
7726** CAPI3REF: Conflict resolution modes
7727**
7728** These constants are returned by [sqlite3_vtab_on_conflict()] to
7729** inform a [virtual table] implementation what the [ON CONFLICT] mode
7730** is for the SQL statement being evaluated.
7731**
7732** Note that the [SQLITE_IGNORE] constant is also used as a potential
7733** return value from the [sqlite3_set_authorizer()] callback and that
7734** [SQLITE_ABORT] is also a [result code].
7735*/
7736#define SQLITE_ROLLBACK 1
7737/* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
7738#define SQLITE_FAIL     3
7739/* #define SQLITE_ABORT 4  // Also an error code */
7740#define SQLITE_REPLACE  5
7741
7742
7743
7744/*
7745** Undo the hack that converts floating point types to integer for
7746** builds on processors without floating point support.
7747*/
7748#ifdef SQLITE_OMIT_FLOATING_POINT
7749# undef double
7750#endif
7751
7752#if 0
7753}  /* End of the 'extern "C"' block */
7754#endif
7755#endif
7756
7757/*
7758** 2010 August 30
7759**
7760** The author disclaims copyright to this source code.  In place of
7761** a legal notice, here is a blessing:
7762**
7763**    May you do good and not evil.
7764**    May you find forgiveness for yourself and forgive others.
7765**    May you share freely, never taking more than you give.
7766**
7767*************************************************************************
7768*/
7769
7770#ifndef _SQLITE3RTREE_H_
7771#define _SQLITE3RTREE_H_
7772
7773
7774#if 0
7775extern "C" {
7776#endif
7777
7778typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
7779
7780/*
7781** Register a geometry callback named zGeom that can be used as part of an
7782** R-Tree geometry query as follows:
7783**
7784**   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
7785*/
7786SQLITE_API int sqlite3_rtree_geometry_callback(
7787  sqlite3 *db,
7788  const char *zGeom,
7789#ifdef SQLITE_RTREE_INT_ONLY
7790  int (*xGeom)(sqlite3_rtree_geometry*, int n, sqlite3_int64 *a, int *pRes),
7791#else
7792  int (*xGeom)(sqlite3_rtree_geometry*, int n, double *a, int *pRes),
7793#endif
7794  void *pContext
7795);
7796
7797
7798/*
7799** A pointer to a structure of the following type is passed as the first
7800** argument to callbacks registered using rtree_geometry_callback().
7801*/
7802struct sqlite3_rtree_geometry {
7803  void *pContext;                 /* Copy of pContext passed to s_r_g_c() */
7804  int nParam;                     /* Size of array aParam[] */
7805  double *aParam;                 /* Parameters passed to SQL geom function */
7806  void *pUser;                    /* Callback implementation user data */
7807  void (*xDelUser)(void *);       /* Called by SQLite to clean up pUser */
7808};
7809
7810
7811#if 0
7812}  /* end of the 'extern "C"' block */
7813#endif
7814
7815#endif  /* ifndef _SQLITE3RTREE_H_ */
7816
7817
7818/************** End of sqlite3.h *********************************************/
7819/************** Continuing where we left off in sqliteInt.h ******************/
7820/************** Include hash.h in the middle of sqliteInt.h ******************/
7821/************** Begin file hash.h ********************************************/
7822/*
7823** 2001 September 22
7824**
7825** The author disclaims copyright to this source code.  In place of
7826** a legal notice, here is a blessing:
7827**
7828**    May you do good and not evil.
7829**    May you find forgiveness for yourself and forgive others.
7830**    May you share freely, never taking more than you give.
7831**
7832*************************************************************************
7833** This is the header file for the generic hash-table implementation
7834** used in SQLite.
7835*/
7836#ifndef _SQLITE_HASH_H_
7837#define _SQLITE_HASH_H_
7838
7839/* Forward declarations of structures. */
7840typedef struct Hash Hash;
7841typedef struct HashElem HashElem;
7842
7843/* A complete hash table is an instance of the following structure.
7844** The internals of this structure are intended to be opaque -- client
7845** code should not attempt to access or modify the fields of this structure
7846** directly.  Change this structure only by using the routines below.
7847** However, some of the "procedures" and "functions" for modifying and
7848** accessing this structure are really macros, so we can't really make
7849** this structure opaque.
7850**
7851** All elements of the hash table are on a single doubly-linked list.
7852** Hash.first points to the head of this list.
7853**
7854** There are Hash.htsize buckets.  Each bucket points to a spot in
7855** the global doubly-linked list.  The contents of the bucket are the
7856** element pointed to plus the next _ht.count-1 elements in the list.
7857**
7858** Hash.htsize and Hash.ht may be zero.  In that case lookup is done
7859** by a linear search of the global list.  For small tables, the
7860** Hash.ht table is never allocated because if there are few elements
7861** in the table, it is faster to do a linear search than to manage
7862** the hash table.
7863*/
7864struct Hash {
7865  unsigned int htsize;      /* Number of buckets in the hash table */
7866  unsigned int count;       /* Number of entries in this table */
7867  HashElem *first;          /* The first element of the array */
7868  struct _ht {              /* the hash table */
7869    int count;                 /* Number of entries with this hash */
7870    HashElem *chain;           /* Pointer to first entry with this hash */
7871  } *ht;
7872};
7873
7874/* Each element in the hash table is an instance of the following
7875** structure.  All elements are stored on a single doubly-linked list.
7876**
7877** Again, this structure is intended to be opaque, but it can't really
7878** be opaque because it is used by macros.
7879*/
7880struct HashElem {
7881  HashElem *next, *prev;       /* Next and previous elements in the table */
7882  void *data;                  /* Data associated with this element */
7883  const char *pKey; int nKey;  /* Key associated with this element */
7884};
7885
7886/*
7887** Access routines.  To delete, insert a NULL pointer.
7888*/
7889SQLITE_PRIVATE void sqlite3HashInit(Hash*);
7890SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData);
7891SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey);
7892SQLITE_PRIVATE void sqlite3HashClear(Hash*);
7893
7894/*
7895** Macros for looping over all elements of a hash table.  The idiom is
7896** like this:
7897**
7898**   Hash h;
7899**   HashElem *p;
7900**   ...
7901**   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
7902**     SomeStructure *pData = sqliteHashData(p);
7903**     // do something with pData
7904**   }
7905*/
7906#define sqliteHashFirst(H)  ((H)->first)
7907#define sqliteHashNext(E)   ((E)->next)
7908#define sqliteHashData(E)   ((E)->data)
7909/* #define sqliteHashKey(E)    ((E)->pKey) // NOT USED */
7910/* #define sqliteHashKeysize(E) ((E)->nKey)  // NOT USED */
7911
7912/*
7913** Number of entries in a hash table
7914*/
7915/* #define sqliteHashCount(H)  ((H)->count) // NOT USED */
7916
7917#endif /* _SQLITE_HASH_H_ */
7918
7919/************** End of hash.h ************************************************/
7920/************** Continuing where we left off in sqliteInt.h ******************/
7921/************** Include parse.h in the middle of sqliteInt.h *****************/
7922/************** Begin file parse.h *******************************************/
7923#define TK_SEMI                            1
7924#define TK_EXPLAIN                         2
7925#define TK_QUERY                           3
7926#define TK_PLAN                            4
7927#define TK_BEGIN                           5
7928#define TK_TRANSACTION                     6
7929#define TK_DEFERRED                        7
7930#define TK_IMMEDIATE                       8
7931#define TK_EXCLUSIVE                       9
7932#define TK_COMMIT                         10
7933#define TK_END                            11
7934#define TK_ROLLBACK                       12
7935#define TK_SAVEPOINT                      13
7936#define TK_RELEASE                        14
7937#define TK_TO                             15
7938#define TK_TABLE                          16
7939#define TK_CREATE                         17
7940#define TK_IF                             18
7941#define TK_NOT                            19
7942#define TK_EXISTS                         20
7943#define TK_TEMP                           21
7944#define TK_LP                             22
7945#define TK_RP                             23
7946#define TK_AS                             24
7947#define TK_COMMA                          25
7948#define TK_ID                             26
7949#define TK_INDEXED                        27
7950#define TK_ABORT                          28
7951#define TK_ACTION                         29
7952#define TK_AFTER                          30
7953#define TK_ANALYZE                        31
7954#define TK_ASC                            32
7955#define TK_ATTACH                         33
7956#define TK_BEFORE                         34
7957#define TK_BY                             35
7958#define TK_CASCADE                        36
7959#define TK_CAST                           37
7960#define TK_COLUMNKW                       38
7961#define TK_CONFLICT                       39
7962#define TK_DATABASE                       40
7963#define TK_DESC                           41
7964#define TK_DETACH                         42
7965#define TK_EACH                           43
7966#define TK_FAIL                           44
7967#define TK_FOR                            45
7968#define TK_IGNORE                         46
7969#define TK_INITIALLY                      47
7970#define TK_INSTEAD                        48
7971#define TK_LIKE_KW                        49
7972#define TK_MATCH                          50
7973#define TK_NO                             51
7974#define TK_KEY                            52
7975#define TK_OF                             53
7976#define TK_OFFSET                         54
7977#define TK_PRAGMA                         55
7978#define TK_RAISE                          56
7979#define TK_REPLACE                        57
7980#define TK_RESTRICT                       58
7981#define TK_ROW                            59
7982#define TK_TRIGGER                        60
7983#define TK_VACUUM                         61
7984#define TK_VIEW                           62
7985#define TK_VIRTUAL                        63
7986#define TK_REINDEX                        64
7987#define TK_RENAME                         65
7988#define TK_CTIME_KW                       66
7989#define TK_ANY                            67
7990#define TK_OR                             68
7991#define TK_AND                            69
7992#define TK_IS                             70
7993#define TK_BETWEEN                        71
7994#define TK_IN                             72
7995#define TK_ISNULL                         73
7996#define TK_NOTNULL                        74
7997#define TK_NE                             75
7998#define TK_EQ                             76
7999#define TK_GT                             77
8000#define TK_LE                             78
8001#define TK_LT                             79
8002#define TK_GE                             80
8003#define TK_ESCAPE                         81
8004#define TK_BITAND                         82
8005#define TK_BITOR                          83
8006#define TK_LSHIFT                         84
8007#define TK_RSHIFT                         85
8008#define TK_PLUS                           86
8009#define TK_MINUS                          87
8010#define TK_STAR                           88
8011#define TK_SLASH                          89
8012#define TK_REM                            90
8013#define TK_CONCAT                         91
8014#define TK_COLLATE                        92
8015#define TK_BITNOT                         93
8016#define TK_STRING                         94
8017#define TK_JOIN_KW                        95
8018#define TK_CONSTRAINT                     96
8019#define TK_DEFAULT                        97
8020#define TK_NULL                           98
8021#define TK_PRIMARY                        99
8022#define TK_UNIQUE                         100
8023#define TK_CHECK                          101
8024#define TK_REFERENCES                     102
8025#define TK_AUTOINCR                       103
8026#define TK_ON                             104
8027#define TK_INSERT                         105
8028#define TK_DELETE                         106
8029#define TK_UPDATE                         107
8030#define TK_SET                            108
8031#define TK_DEFERRABLE                     109
8032#define TK_FOREIGN                        110
8033#define TK_DROP                           111
8034#define TK_UNION                          112
8035#define TK_ALL                            113
8036#define TK_EXCEPT                         114
8037#define TK_INTERSECT                      115
8038#define TK_SELECT                         116
8039#define TK_DISTINCT                       117
8040#define TK_DOT                            118
8041#define TK_FROM                           119
8042#define TK_JOIN                           120
8043#define TK_USING                          121
8044#define TK_ORDER                          122
8045#define TK_GROUP                          123
8046#define TK_HAVING                         124
8047#define TK_LIMIT                          125
8048#define TK_WHERE                          126
8049#define TK_INTO                           127
8050#define TK_VALUES                         128
8051#define TK_INTEGER                        129
8052#define TK_FLOAT                          130
8053#define TK_BLOB                           131
8054#define TK_REGISTER                       132
8055#define TK_VARIABLE                       133
8056#define TK_CASE                           134
8057#define TK_WHEN                           135
8058#define TK_THEN                           136
8059#define TK_ELSE                           137
8060#define TK_INDEX                          138
8061#define TK_ALTER                          139
8062#define TK_ADD                            140
8063#define TK_TO_TEXT                        141
8064#define TK_TO_BLOB                        142
8065#define TK_TO_NUMERIC                     143
8066#define TK_TO_INT                         144
8067#define TK_TO_REAL                        145
8068#define TK_ISNOT                          146
8069#define TK_END_OF_FILE                    147
8070#define TK_ILLEGAL                        148
8071#define TK_SPACE                          149
8072#define TK_UNCLOSED_STRING                150
8073#define TK_FUNCTION                       151
8074#define TK_COLUMN                         152
8075#define TK_AGG_FUNCTION                   153
8076#define TK_AGG_COLUMN                     154
8077#define TK_CONST_FUNC                     155
8078#define TK_UMINUS                         156
8079#define TK_UPLUS                          157
8080
8081/************** End of parse.h ***********************************************/
8082/************** Continuing where we left off in sqliteInt.h ******************/
8083#include <stdio.h>
8084#include <stdlib.h>
8085#include <string.h>
8086#include <assert.h>
8087#include <stddef.h>
8088
8089/*
8090** If compiling for a processor that lacks floating point support,
8091** substitute integer for floating-point
8092*/
8093#ifdef SQLITE_OMIT_FLOATING_POINT
8094# define double sqlite_int64
8095# define float sqlite_int64
8096# define LONGDOUBLE_TYPE sqlite_int64
8097# ifndef SQLITE_BIG_DBL
8098#   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
8099# endif
8100# define SQLITE_OMIT_DATETIME_FUNCS 1
8101# define SQLITE_OMIT_TRACE 1
8102# undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
8103# undef SQLITE_HAVE_ISNAN
8104#endif
8105#ifndef SQLITE_BIG_DBL
8106# define SQLITE_BIG_DBL (1e99)
8107#endif
8108
8109/*
8110** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
8111** afterward. Having this macro allows us to cause the C compiler
8112** to omit code used by TEMP tables without messy #ifndef statements.
8113*/
8114#ifdef SQLITE_OMIT_TEMPDB
8115#define OMIT_TEMPDB 1
8116#else
8117#define OMIT_TEMPDB 0
8118#endif
8119
8120/*
8121** The "file format" number is an integer that is incremented whenever
8122** the VDBE-level file format changes.  The following macros define the
8123** the default file format for new databases and the maximum file format
8124** that the library can read.
8125*/
8126#define SQLITE_MAX_FILE_FORMAT 4
8127#ifndef SQLITE_DEFAULT_FILE_FORMAT
8128# define SQLITE_DEFAULT_FILE_FORMAT 4
8129#endif
8130
8131/*
8132** Determine whether triggers are recursive by default.  This can be
8133** changed at run-time using a pragma.
8134*/
8135#ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
8136# define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
8137#endif
8138
8139/*
8140** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
8141** on the command-line
8142*/
8143#ifndef SQLITE_TEMP_STORE
8144# define SQLITE_TEMP_STORE 1
8145# define SQLITE_TEMP_STORE_xc 1  /* Exclude from ctime.c */
8146#endif
8147
8148/*
8149** GCC does not define the offsetof() macro so we'll have to do it
8150** ourselves.
8151*/
8152#ifndef offsetof
8153#define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
8154#endif
8155
8156/*
8157** Check to see if this machine uses EBCDIC.  (Yes, believe it or
8158** not, there are still machines out there that use EBCDIC.)
8159*/
8160#if 'A' == '\301'
8161# define SQLITE_EBCDIC 1
8162#else
8163# define SQLITE_ASCII 1
8164#endif
8165
8166/*
8167** Integers of known sizes.  These typedefs might change for architectures
8168** where the sizes very.  Preprocessor macros are available so that the
8169** types can be conveniently redefined at compile-type.  Like this:
8170**
8171**         cc '-DUINTPTR_TYPE=long long int' ...
8172*/
8173#ifndef UINT32_TYPE
8174# ifdef HAVE_UINT32_T
8175#  define UINT32_TYPE uint32_t
8176# else
8177#  define UINT32_TYPE unsigned int
8178# endif
8179#endif
8180#ifndef UINT16_TYPE
8181# ifdef HAVE_UINT16_T
8182#  define UINT16_TYPE uint16_t
8183# else
8184#  define UINT16_TYPE unsigned short int
8185# endif
8186#endif
8187#ifndef INT16_TYPE
8188# ifdef HAVE_INT16_T
8189#  define INT16_TYPE int16_t
8190# else
8191#  define INT16_TYPE short int
8192# endif
8193#endif
8194#ifndef UINT8_TYPE
8195# ifdef HAVE_UINT8_T
8196#  define UINT8_TYPE uint8_t
8197# else
8198#  define UINT8_TYPE unsigned char
8199# endif
8200#endif
8201#ifndef INT8_TYPE
8202# ifdef HAVE_INT8_T
8203#  define INT8_TYPE int8_t
8204# else
8205#  define INT8_TYPE signed char
8206# endif
8207#endif
8208#ifndef LONGDOUBLE_TYPE
8209# define LONGDOUBLE_TYPE long double
8210#endif
8211typedef sqlite_int64 i64;          /* 8-byte signed integer */
8212typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
8213typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
8214typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
8215typedef INT16_TYPE i16;            /* 2-byte signed integer */
8216typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
8217typedef INT8_TYPE i8;              /* 1-byte signed integer */
8218
8219/*
8220** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
8221** that can be stored in a u32 without loss of data.  The value
8222** is 0x00000000ffffffff.  But because of quirks of some compilers, we
8223** have to specify the value in the less intuitive manner shown:
8224*/
8225#define SQLITE_MAX_U32  ((((u64)1)<<32)-1)
8226
8227/*
8228** The datatype used to store estimates of the number of rows in a
8229** table or index.  This is an unsigned integer type.  For 99.9% of
8230** the world, a 32-bit integer is sufficient.  But a 64-bit integer
8231** can be used at compile-time if desired.
8232*/
8233#ifdef SQLITE_64BIT_STATS
8234 typedef u64 tRowcnt;    /* 64-bit only if requested at compile-time */
8235#else
8236 typedef u32 tRowcnt;    /* 32-bit is the default */
8237#endif
8238
8239/*
8240** Macros to determine whether the machine is big or little endian,
8241** evaluated at runtime.
8242*/
8243#ifdef SQLITE_AMALGAMATION
8244SQLITE_PRIVATE const int sqlite3one = 1;
8245#else
8246SQLITE_PRIVATE const int sqlite3one;
8247#endif
8248#if defined(i386) || defined(__i386__) || defined(_M_IX86)\
8249                             || defined(__x86_64) || defined(__x86_64__)
8250# define SQLITE_BIGENDIAN    0
8251# define SQLITE_LITTLEENDIAN 1
8252# define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
8253#else
8254# define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
8255# define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
8256# define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
8257#endif
8258
8259/*
8260** Constants for the largest and smallest possible 64-bit signed integers.
8261** These macros are designed to work correctly on both 32-bit and 64-bit
8262** compilers.
8263*/
8264#define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
8265#define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
8266
8267/*
8268** Round up a number to the next larger multiple of 8.  This is used
8269** to force 8-byte alignment on 64-bit architectures.
8270*/
8271#define ROUND8(x)     (((x)+7)&~7)
8272
8273/*
8274** Round down to the nearest multiple of 8
8275*/
8276#define ROUNDDOWN8(x) ((x)&~7)
8277
8278/*
8279** Assert that the pointer X is aligned to an 8-byte boundary.  This
8280** macro is used only within assert() to verify that the code gets
8281** all alignment restrictions correct.
8282**
8283** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
8284** underlying malloc() implemention might return us 4-byte aligned
8285** pointers.  In that case, only verify 4-byte alignment.
8286*/
8287#ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
8288# define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&3)==0)
8289#else
8290# define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&7)==0)
8291#endif
8292
8293/*
8294** Disable MMAP on platforms where it is known to not work
8295*/
8296#if defined(__OpenBSD__) || defined(__QNXNTO__)
8297# undef SQLITE_MAX_MMAP_SIZE
8298# define SQLITE_MAX_MMAP_SIZE 0
8299#endif
8300
8301/*
8302** Default maximum size of memory used by memory-mapped I/O in the VFS
8303*/
8304#ifdef __APPLE__
8305# include <TargetConditionals.h>
8306# if TARGET_OS_IPHONE
8307#   undef SQLITE_MAX_MMAP_SIZE
8308#   define SQLITE_MAX_MMAP_SIZE 0
8309# endif
8310#endif
8311#ifndef SQLITE_MAX_MMAP_SIZE
8312# if defined(__linux__) \
8313  || defined(_WIN32) \
8314  || (defined(__APPLE__) && defined(__MACH__)) \
8315  || defined(__sun)
8316#   define SQLITE_MAX_MMAP_SIZE 0x7fff0000  /* 2147418112 */
8317# else
8318#   define SQLITE_MAX_MMAP_SIZE 0
8319# endif
8320# define SQLITE_MAX_MMAP_SIZE_xc 1 /* exclude from ctime.c */
8321#endif
8322
8323/*
8324** The default MMAP_SIZE is zero on all platforms.  Or, even if a larger
8325** default MMAP_SIZE is specified at compile-time, make sure that it does
8326** not exceed the maximum mmap size.
8327*/
8328#ifndef SQLITE_DEFAULT_MMAP_SIZE
8329# define SQLITE_DEFAULT_MMAP_SIZE 0
8330# define SQLITE_DEFAULT_MMAP_SIZE_xc 1  /* Exclude from ctime.c */
8331#endif
8332#if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
8333# undef SQLITE_DEFAULT_MMAP_SIZE
8334# define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
8335#endif
8336
8337/*
8338** An instance of the following structure is used to store the busy-handler
8339** callback for a given sqlite handle.
8340**
8341** The sqlite.busyHandler member of the sqlite struct contains the busy
8342** callback for the database handle. Each pager opened via the sqlite
8343** handle is passed a pointer to sqlite.busyHandler. The busy-handler
8344** callback is currently invoked only from within pager.c.
8345*/
8346typedef struct BusyHandler BusyHandler;
8347struct BusyHandler {
8348  int (*xFunc)(void *,int);  /* The busy callback */
8349  void *pArg;                /* First arg to busy callback */
8350  int nBusy;                 /* Incremented with each busy call */
8351};
8352
8353/*
8354** Name of the master database table.  The master database table
8355** is a special table that holds the names and attributes of all
8356** user tables and indices.
8357*/
8358#define MASTER_NAME       "sqlite_master"
8359#define TEMP_MASTER_NAME  "sqlite_temp_master"
8360
8361/*
8362** The root-page of the master database table.
8363*/
8364#define MASTER_ROOT       1
8365
8366/*
8367** The name of the schema table.
8368*/
8369#define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
8370
8371/*
8372** A convenience macro that returns the number of elements in
8373** an array.
8374*/
8375#define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
8376
8377/*
8378** Determine if the argument is a power of two
8379*/
8380#define IsPowerOfTwo(X) (((X)&((X)-1))==0)
8381
8382/*
8383** The following value as a destructor means to use sqlite3DbFree().
8384** The sqlite3DbFree() routine requires two parameters instead of the
8385** one parameter that destructors normally want.  So we have to introduce
8386** this magic value that the code knows to handle differently.  Any
8387** pointer will work here as long as it is distinct from SQLITE_STATIC
8388** and SQLITE_TRANSIENT.
8389*/
8390#define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3MallocSize)
8391
8392/*
8393** When SQLITE_OMIT_WSD is defined, it means that the target platform does
8394** not support Writable Static Data (WSD) such as global and static variables.
8395** All variables must either be on the stack or dynamically allocated from
8396** the heap.  When WSD is unsupported, the variable declarations scattered
8397** throughout the SQLite code must become constants instead.  The SQLITE_WSD
8398** macro is used for this purpose.  And instead of referencing the variable
8399** directly, we use its constant as a key to lookup the run-time allocated
8400** buffer that holds real variable.  The constant is also the initializer
8401** for the run-time allocated buffer.
8402**
8403** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
8404** macros become no-ops and have zero performance impact.
8405*/
8406#ifdef SQLITE_OMIT_WSD
8407  #define SQLITE_WSD const
8408  #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
8409  #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
8410SQLITE_API   int sqlite3_wsd_init(int N, int J);
8411SQLITE_API   void *sqlite3_wsd_find(void *K, int L);
8412#else
8413  #define SQLITE_WSD
8414  #define GLOBAL(t,v) v
8415  #define sqlite3GlobalConfig sqlite3Config
8416#endif
8417
8418/*
8419** The following macros are used to suppress compiler warnings and to
8420** make it clear to human readers when a function parameter is deliberately
8421** left unused within the body of a function. This usually happens when
8422** a function is called via a function pointer. For example the
8423** implementation of an SQL aggregate step callback may not use the
8424** parameter indicating the number of arguments passed to the aggregate,
8425** if it knows that this is enforced elsewhere.
8426**
8427** When a function parameter is not used at all within the body of a function,
8428** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
8429** However, these macros may also be used to suppress warnings related to
8430** parameters that may or may not be used depending on compilation options.
8431** For example those parameters only used in assert() statements. In these
8432** cases the parameters are named as per the usual conventions.
8433*/
8434#define UNUSED_PARAMETER(x) (void)(x)
8435#define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
8436
8437/*
8438** Forward references to structures
8439*/
8440typedef struct AggInfo AggInfo;
8441typedef struct AuthContext AuthContext;
8442typedef struct AutoincInfo AutoincInfo;
8443typedef struct Bitvec Bitvec;
8444typedef struct CollSeq CollSeq;
8445typedef struct Column Column;
8446typedef struct Db Db;
8447typedef struct Schema Schema;
8448typedef struct Expr Expr;
8449typedef struct ExprList ExprList;
8450typedef struct ExprSpan ExprSpan;
8451typedef struct FKey FKey;
8452typedef struct FuncDestructor FuncDestructor;
8453typedef struct FuncDef FuncDef;
8454typedef struct FuncDefHash FuncDefHash;
8455typedef struct IdList IdList;
8456typedef struct Index Index;
8457typedef struct IndexSample IndexSample;
8458typedef struct KeyClass KeyClass;
8459typedef struct KeyInfo KeyInfo;
8460typedef struct Lookaside Lookaside;
8461typedef struct LookasideSlot LookasideSlot;
8462typedef struct Module Module;
8463typedef struct NameContext NameContext;
8464typedef struct Parse Parse;
8465typedef struct RowSet RowSet;
8466typedef struct Savepoint Savepoint;
8467typedef struct Select Select;
8468typedef struct SelectDest SelectDest;
8469typedef struct SrcList SrcList;
8470typedef struct StrAccum StrAccum;
8471typedef struct Table Table;
8472typedef struct TableLock TableLock;
8473typedef struct Token Token;
8474typedef struct Trigger Trigger;
8475typedef struct TriggerPrg TriggerPrg;
8476typedef struct TriggerStep TriggerStep;
8477typedef struct UnpackedRecord UnpackedRecord;
8478typedef struct VTable VTable;
8479typedef struct VtabCtx VtabCtx;
8480typedef struct Walker Walker;
8481typedef struct WherePlan WherePlan;
8482typedef struct WhereInfo WhereInfo;
8483typedef struct WhereLevel WhereLevel;
8484
8485/*
8486** Defer sourcing vdbe.h and btree.h until after the "u8" and
8487** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
8488** pointer types (i.e. FuncDef) defined above.
8489*/
8490/************** Include btree.h in the middle of sqliteInt.h *****************/
8491/************** Begin file btree.h *******************************************/
8492/*
8493** 2001 September 15
8494**
8495** The author disclaims copyright to this source code.  In place of
8496** a legal notice, here is a blessing:
8497**
8498**    May you do good and not evil.
8499**    May you find forgiveness for yourself and forgive others.
8500**    May you share freely, never taking more than you give.
8501**
8502*************************************************************************
8503** This header file defines the interface that the sqlite B-Tree file
8504** subsystem.  See comments in the source code for a detailed description
8505** of what each interface routine does.
8506*/
8507#ifndef _BTREE_H_
8508#define _BTREE_H_
8509
8510/* TODO: This definition is just included so other modules compile. It
8511** needs to be revisited.
8512*/
8513#define SQLITE_N_BTREE_META 10
8514
8515/*
8516** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
8517** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
8518*/
8519#ifndef SQLITE_DEFAULT_AUTOVACUUM
8520  #define SQLITE_DEFAULT_AUTOVACUUM 0
8521#endif
8522
8523#define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
8524#define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
8525#define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
8526
8527/*
8528** Forward declarations of structure
8529*/
8530typedef struct Btree Btree;
8531typedef struct BtCursor BtCursor;
8532typedef struct BtShared BtShared;
8533
8534
8535SQLITE_PRIVATE int sqlite3BtreeOpen(
8536  sqlite3_vfs *pVfs,       /* VFS to use with this b-tree */
8537  const char *zFilename,   /* Name of database file to open */
8538  sqlite3 *db,             /* Associated database connection */
8539  Btree **ppBtree,         /* Return open Btree* here */
8540  int flags,               /* Flags */
8541  int vfsFlags             /* Flags passed through to VFS open */
8542);
8543
8544/* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
8545** following values.
8546**
8547** NOTE:  These values must match the corresponding PAGER_ values in
8548** pager.h.
8549*/
8550#define BTREE_OMIT_JOURNAL  1  /* Do not create or use a rollback journal */
8551#define BTREE_MEMORY        2  /* This is an in-memory DB */
8552#define BTREE_SINGLE        4  /* The file contains at most 1 b-tree */
8553#define BTREE_UNORDERED     8  /* Use of a hash implementation is OK */
8554
8555SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
8556SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
8557SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
8558SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int,int);
8559SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
8560SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
8561SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
8562SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
8563SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
8564SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
8565SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
8566#if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG)
8567SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
8568#endif
8569SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
8570SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
8571SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
8572SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
8573SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
8574SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
8575SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int);
8576SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
8577SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
8578SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
8579SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
8580SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
8581SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
8582SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
8583SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
8584SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
8585
8586SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
8587SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
8588SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
8589
8590SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
8591
8592/* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
8593** of the flags shown below.
8594**
8595** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
8596** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
8597** is stored in the leaves.  (BTREE_INTKEY is used for SQL tables.)  With
8598** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
8599** anywhere - the key is the content.  (BTREE_BLOBKEY is used for SQL
8600** indices.)
8601*/
8602#define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
8603#define BTREE_BLOBKEY    2    /* Table has keys only - no data */
8604
8605SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
8606SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
8607SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
8608
8609SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
8610SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
8611
8612SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
8613
8614/*
8615** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
8616** should be one of the following values. The integer values are assigned
8617** to constants so that the offset of the corresponding field in an
8618** SQLite database header may be found using the following formula:
8619**
8620**   offset = 36 + (idx * 4)
8621**
8622** For example, the free-page-count field is located at byte offset 36 of
8623** the database file header. The incr-vacuum-flag field is located at
8624** byte offset 64 (== 36+4*7).
8625*/
8626#define BTREE_FREE_PAGE_COUNT     0
8627#define BTREE_SCHEMA_VERSION      1
8628#define BTREE_FILE_FORMAT         2
8629#define BTREE_DEFAULT_CACHE_SIZE  3
8630#define BTREE_LARGEST_ROOT_PAGE   4
8631#define BTREE_TEXT_ENCODING       5
8632#define BTREE_USER_VERSION        6
8633#define BTREE_INCR_VACUUM         7
8634#define BTREE_APPLICATION_ID      8
8635
8636/*
8637** Values that may be OR'd together to form the second argument of an
8638** sqlite3BtreeCursorHints() call.
8639*/
8640#define BTREE_BULKLOAD 0x00000001
8641
8642SQLITE_PRIVATE int sqlite3BtreeCursor(
8643  Btree*,                              /* BTree containing table to open */
8644  int iTable,                          /* Index of root page */
8645  int wrFlag,                          /* 1 for writing.  0 for read-only */
8646  struct KeyInfo*,                     /* First argument to compare function */
8647  BtCursor *pCursor                    /* Space to write cursor structure */
8648);
8649SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
8650SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
8651
8652SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
8653SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
8654  BtCursor*,
8655  UnpackedRecord *pUnKey,
8656  i64 intKey,
8657  int bias,
8658  int *pRes
8659);
8660SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
8661SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
8662SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
8663                                  const void *pData, int nData,
8664                                  int nZero, int bias, int seekResult);
8665SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
8666SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
8667SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
8668SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
8669SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
8670SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
8671SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
8672SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
8673SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
8674SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
8675SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
8676SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64);
8677SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*);
8678
8679SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
8680SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
8681
8682SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
8683SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
8684SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
8685SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
8686SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *, unsigned int mask);
8687
8688#ifndef NDEBUG
8689SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
8690#endif
8691
8692#ifndef SQLITE_OMIT_BTREECOUNT
8693SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
8694#endif
8695
8696#ifdef SQLITE_TEST
8697SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
8698SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
8699#endif
8700
8701#ifndef SQLITE_OMIT_WAL
8702SQLITE_PRIVATE   int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
8703#endif
8704
8705/*
8706** If we are not using shared cache, then there is no need to
8707** use mutexes to access the BtShared structures.  So make the
8708** Enter and Leave procedures no-ops.
8709*/
8710#ifndef SQLITE_OMIT_SHARED_CACHE
8711SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
8712SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
8713#else
8714# define sqlite3BtreeEnter(X)
8715# define sqlite3BtreeEnterAll(X)
8716#endif
8717
8718#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
8719SQLITE_PRIVATE   int sqlite3BtreeSharable(Btree*);
8720SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
8721SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
8722SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
8723SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
8724#ifndef NDEBUG
8725  /* These routines are used inside assert() statements only. */
8726SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
8727SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
8728SQLITE_PRIVATE   int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
8729#endif
8730#else
8731
8732# define sqlite3BtreeSharable(X) 0
8733# define sqlite3BtreeLeave(X)
8734# define sqlite3BtreeEnterCursor(X)
8735# define sqlite3BtreeLeaveCursor(X)
8736# define sqlite3BtreeLeaveAll(X)
8737
8738# define sqlite3BtreeHoldsMutex(X) 1
8739# define sqlite3BtreeHoldsAllMutexes(X) 1
8740# define sqlite3SchemaMutexHeld(X,Y,Z) 1
8741#endif
8742
8743
8744#endif /* _BTREE_H_ */
8745
8746/************** End of btree.h ***********************************************/
8747/************** Continuing where we left off in sqliteInt.h ******************/
8748/************** Include vdbe.h in the middle of sqliteInt.h ******************/
8749/************** Begin file vdbe.h ********************************************/
8750/*
8751** 2001 September 15
8752**
8753** The author disclaims copyright to this source code.  In place of
8754** a legal notice, here is a blessing:
8755**
8756**    May you do good and not evil.
8757**    May you find forgiveness for yourself and forgive others.
8758**    May you share freely, never taking more than you give.
8759**
8760*************************************************************************
8761** Header file for the Virtual DataBase Engine (VDBE)
8762**
8763** This header defines the interface to the virtual database engine
8764** or VDBE.  The VDBE implements an abstract machine that runs a
8765** simple program to access and modify the underlying database.
8766*/
8767#ifndef _SQLITE_VDBE_H_
8768#define _SQLITE_VDBE_H_
8769/* #include <stdio.h> */
8770
8771/*
8772** A single VDBE is an opaque structure named "Vdbe".  Only routines
8773** in the source file sqliteVdbe.c are allowed to see the insides
8774** of this structure.
8775*/
8776typedef struct Vdbe Vdbe;
8777
8778/*
8779** The names of the following types declared in vdbeInt.h are required
8780** for the VdbeOp definition.
8781*/
8782typedef struct VdbeFunc VdbeFunc;
8783typedef struct Mem Mem;
8784typedef struct SubProgram SubProgram;
8785
8786/*
8787** A single instruction of the virtual machine has an opcode
8788** and as many as three operands.  The instruction is recorded
8789** as an instance of the following structure:
8790*/
8791struct VdbeOp {
8792  u8 opcode;          /* What operation to perform */
8793  signed char p4type; /* One of the P4_xxx constants for p4 */
8794  u8 opflags;         /* Mask of the OPFLG_* flags in opcodes.h */
8795  u8 p5;              /* Fifth parameter is an unsigned character */
8796  int p1;             /* First operand */
8797  int p2;             /* Second parameter (often the jump destination) */
8798  int p3;             /* The third parameter */
8799  union {             /* fourth parameter */
8800    int i;                 /* Integer value if p4type==P4_INT32 */
8801    void *p;               /* Generic pointer */
8802    char *z;               /* Pointer to data for string (char array) types */
8803    i64 *pI64;             /* Used when p4type is P4_INT64 */
8804    double *pReal;         /* Used when p4type is P4_REAL */
8805    FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
8806    VdbeFunc *pVdbeFunc;   /* Used when p4type is P4_VDBEFUNC */
8807    CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
8808    Mem *pMem;             /* Used when p4type is P4_MEM */
8809    VTable *pVtab;         /* Used when p4type is P4_VTAB */
8810    KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
8811    int *ai;               /* Used when p4type is P4_INTARRAY */
8812    SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */
8813    int (*xAdvance)(BtCursor *, int *);
8814  } p4;
8815#ifdef SQLITE_DEBUG
8816  char *zComment;          /* Comment to improve readability */
8817#endif
8818#ifdef VDBE_PROFILE
8819  int cnt;                 /* Number of times this instruction was executed */
8820  u64 cycles;              /* Total time spent executing this instruction */
8821#endif
8822};
8823typedef struct VdbeOp VdbeOp;
8824
8825
8826/*
8827** A sub-routine used to implement a trigger program.
8828*/
8829struct SubProgram {
8830  VdbeOp *aOp;                  /* Array of opcodes for sub-program */
8831  int nOp;                      /* Elements in aOp[] */
8832  int nMem;                     /* Number of memory cells required */
8833  int nCsr;                     /* Number of cursors required */
8834  int nOnce;                    /* Number of OP_Once instructions */
8835  void *token;                  /* id that may be used to recursive triggers */
8836  SubProgram *pNext;            /* Next sub-program already visited */
8837};
8838
8839/*
8840** A smaller version of VdbeOp used for the VdbeAddOpList() function because
8841** it takes up less space.
8842*/
8843struct VdbeOpList {
8844  u8 opcode;          /* What operation to perform */
8845  signed char p1;     /* First operand */
8846  signed char p2;     /* Second parameter (often the jump destination) */
8847  signed char p3;     /* Third parameter */
8848};
8849typedef struct VdbeOpList VdbeOpList;
8850
8851/*
8852** Allowed values of VdbeOp.p4type
8853*/
8854#define P4_NOTUSED    0   /* The P4 parameter is not used */
8855#define P4_DYNAMIC  (-1)  /* Pointer to a string obtained from sqliteMalloc() */
8856#define P4_STATIC   (-2)  /* Pointer to a static string */
8857#define P4_COLLSEQ  (-4)  /* P4 is a pointer to a CollSeq structure */
8858#define P4_FUNCDEF  (-5)  /* P4 is a pointer to a FuncDef structure */
8859#define P4_KEYINFO  (-6)  /* P4 is a pointer to a KeyInfo structure */
8860#define P4_VDBEFUNC (-7)  /* P4 is a pointer to a VdbeFunc structure */
8861#define P4_MEM      (-8)  /* P4 is a pointer to a Mem*    structure */
8862#define P4_TRANSIENT  0   /* P4 is a pointer to a transient string */
8863#define P4_VTAB     (-10) /* P4 is a pointer to an sqlite3_vtab structure */
8864#define P4_MPRINTF  (-11) /* P4 is a string obtained from sqlite3_mprintf() */
8865#define P4_REAL     (-12) /* P4 is a 64-bit floating point value */
8866#define P4_INT64    (-13) /* P4 is a 64-bit signed integer */
8867#define P4_INT32    (-14) /* P4 is a 32-bit signed integer */
8868#define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
8869#define P4_SUBPROGRAM  (-18) /* P4 is a pointer to a SubProgram structure */
8870#define P4_ADVANCE  (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */
8871
8872/* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
8873** is made.  That copy is freed when the Vdbe is finalized.  But if the
8874** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used.  It still
8875** gets freed when the Vdbe is finalized so it still should be obtained
8876** from a single sqliteMalloc().  But no copy is made and the calling
8877** function should *not* try to free the KeyInfo.
8878*/
8879#define P4_KEYINFO_HANDOFF (-16)
8880#define P4_KEYINFO_STATIC  (-17)
8881
8882/*
8883** The Vdbe.aColName array contains 5n Mem structures, where n is the
8884** number of columns of data returned by the statement.
8885*/
8886#define COLNAME_NAME     0
8887#define COLNAME_DECLTYPE 1
8888#define COLNAME_DATABASE 2
8889#define COLNAME_TABLE    3
8890#define COLNAME_COLUMN   4
8891#ifdef SQLITE_ENABLE_COLUMN_METADATA
8892# define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
8893#else
8894# ifdef SQLITE_OMIT_DECLTYPE
8895#   define COLNAME_N      1      /* Store only the name */
8896# else
8897#   define COLNAME_N      2      /* Store the name and decltype */
8898# endif
8899#endif
8900
8901/*
8902** The following macro converts a relative address in the p2 field
8903** of a VdbeOp structure into a negative number so that
8904** sqlite3VdbeAddOpList() knows that the address is relative.  Calling
8905** the macro again restores the address.
8906*/
8907#define ADDR(X)  (-1-(X))
8908
8909/*
8910** The makefile scans the vdbe.c source file and creates the "opcodes.h"
8911** header file that defines a number for each opcode used by the VDBE.
8912*/
8913/************** Include opcodes.h in the middle of vdbe.h ********************/
8914/************** Begin file opcodes.h *****************************************/
8915/* Automatically generated.  Do not edit */
8916/* See the mkopcodeh.awk script for details */
8917#define OP_Goto                                 1
8918#define OP_Gosub                                2
8919#define OP_Return                               3
8920#define OP_Yield                                4
8921#define OP_HaltIfNull                           5
8922#define OP_Halt                                 6
8923#define OP_Integer                              7
8924#define OP_Int64                                8
8925#define OP_Real                               130   /* same as TK_FLOAT    */
8926#define OP_String8                             94   /* same as TK_STRING   */
8927#define OP_String                               9
8928#define OP_Null                                10
8929#define OP_Blob                                11
8930#define OP_Variable                            12
8931#define OP_Move                                13
8932#define OP_Copy                                14
8933#define OP_SCopy                               15
8934#define OP_ResultRow                           16
8935#define OP_Concat                              91   /* same as TK_CONCAT   */
8936#define OP_Add                                 86   /* same as TK_PLUS     */
8937#define OP_Subtract                            87   /* same as TK_MINUS    */
8938#define OP_Multiply                            88   /* same as TK_STAR     */
8939#define OP_Divide                              89   /* same as TK_SLASH    */
8940#define OP_Remainder                           90   /* same as TK_REM      */
8941#define OP_CollSeq                             17
8942#define OP_Function                            18
8943#define OP_BitAnd                              82   /* same as TK_BITAND   */
8944#define OP_BitOr                               83   /* same as TK_BITOR    */
8945#define OP_ShiftLeft                           84   /* same as TK_LSHIFT   */
8946#define OP_ShiftRight                          85   /* same as TK_RSHIFT   */
8947#define OP_AddImm                              20
8948#define OP_MustBeInt                           21
8949#define OP_RealAffinity                        22
8950#define OP_ToText                             141   /* same as TK_TO_TEXT  */
8951#define OP_ToBlob                             142   /* same as TK_TO_BLOB  */
8952#define OP_ToNumeric                          143   /* same as TK_TO_NUMERIC*/
8953#define OP_ToInt                              144   /* same as TK_TO_INT   */
8954#define OP_ToReal                             145   /* same as TK_TO_REAL  */
8955#define OP_Eq                                  76   /* same as TK_EQ       */
8956#define OP_Ne                                  75   /* same as TK_NE       */
8957#define OP_Lt                                  79   /* same as TK_LT       */
8958#define OP_Le                                  78   /* same as TK_LE       */
8959#define OP_Gt                                  77   /* same as TK_GT       */
8960#define OP_Ge                                  80   /* same as TK_GE       */
8961#define OP_Permutation                         23
8962#define OP_Compare                             24
8963#define OP_Jump                                25
8964#define OP_And                                 69   /* same as TK_AND      */
8965#define OP_Or                                  68   /* same as TK_OR       */
8966#define OP_Not                                 19   /* same as TK_NOT      */
8967#define OP_BitNot                              93   /* same as TK_BITNOT   */
8968#define OP_Once                                26
8969#define OP_If                                  27
8970#define OP_IfNot                               28
8971#define OP_IsNull                              73   /* same as TK_ISNULL   */
8972#define OP_NotNull                             74   /* same as TK_NOTNULL  */
8973#define OP_Column                              29
8974#define OP_Affinity                            30
8975#define OP_MakeRecord                          31
8976#define OP_Count                               32
8977#define OP_Savepoint                           33
8978#define OP_AutoCommit                          34
8979#define OP_Transaction                         35
8980#define OP_ReadCookie                          36
8981#define OP_SetCookie                           37
8982#define OP_VerifyCookie                        38
8983#define OP_OpenRead                            39
8984#define OP_OpenWrite                           40
8985#define OP_OpenAutoindex                       41
8986#define OP_OpenEphemeral                       42
8987#define OP_SorterOpen                          43
8988#define OP_OpenPseudo                          44
8989#define OP_Close                               45
8990#define OP_SeekLt                              46
8991#define OP_SeekLe                              47
8992#define OP_SeekGe                              48
8993#define OP_SeekGt                              49
8994#define OP_Seek                                50
8995#define OP_NotFound                            51
8996#define OP_Found                               52
8997#define OP_IsUnique                            53
8998#define OP_NotExists                           54
8999#define OP_Sequence                            55
9000#define OP_NewRowid                            56
9001#define OP_Insert                              57
9002#define OP_InsertInt                           58
9003#define OP_Delete                              59
9004#define OP_ResetCount                          60
9005#define OP_SorterCompare                       61
9006#define OP_SorterData                          62
9007#define OP_RowKey                              63
9008#define OP_RowData                             64
9009#define OP_Rowid                               65
9010#define OP_NullRow                             66
9011#define OP_Last                                67
9012#define OP_SorterSort                          70
9013#define OP_Sort                                71
9014#define OP_Rewind                              72
9015#define OP_SorterNext                          81
9016#define OP_Prev                                92
9017#define OP_Next                                95
9018#define OP_SorterInsert                        96
9019#define OP_IdxInsert                           97
9020#define OP_IdxDelete                           98
9021#define OP_IdxRowid                            99
9022#define OP_IdxLT                              100
9023#define OP_IdxGE                              101
9024#define OP_Destroy                            102
9025#define OP_Clear                              103
9026#define OP_CreateIndex                        104
9027#define OP_CreateTable                        105
9028#define OP_ParseSchema                        106
9029#define OP_LoadAnalysis                       107
9030#define OP_DropTable                          108
9031#define OP_DropIndex                          109
9032#define OP_DropTrigger                        110
9033#define OP_IntegrityCk                        111
9034#define OP_RowSetAdd                          112
9035#define OP_RowSetRead                         113
9036#define OP_RowSetTest                         114
9037#define OP_Program                            115
9038#define OP_Param                              116
9039#define OP_FkCounter                          117
9040#define OP_FkIfZero                           118
9041#define OP_MemMax                             119
9042#define OP_IfPos                              120
9043#define OP_IfNeg                              121
9044#define OP_IfZero                             122
9045#define OP_AggStep                            123
9046#define OP_AggFinal                           124
9047#define OP_Checkpoint                         125
9048#define OP_JournalMode                        126
9049#define OP_Vacuum                             127
9050#define OP_IncrVacuum                         128
9051#define OP_Expire                             129
9052#define OP_TableLock                          131
9053#define OP_VBegin                             132
9054#define OP_VCreate                            133
9055#define OP_VDestroy                           134
9056#define OP_VOpen                              135
9057#define OP_VFilter                            136
9058#define OP_VColumn                            137
9059#define OP_VNext                              138
9060#define OP_VRename                            139
9061#define OP_VUpdate                            140
9062#define OP_Pagecount                          146
9063#define OP_MaxPgcnt                           147
9064#define OP_Trace                              148
9065#define OP_Noop                               149
9066#define OP_Explain                            150
9067
9068
9069/* Properties such as "out2" or "jump" that are specified in
9070** comments following the "case" for each opcode in the vdbe.c
9071** are encoded into bitvectors as follows:
9072*/
9073#define OPFLG_JUMP            0x0001  /* jump:  P2 holds jmp target */
9074#define OPFLG_OUT2_PRERELEASE 0x0002  /* out2-prerelease: */
9075#define OPFLG_IN1             0x0004  /* in1:   P1 is an input */
9076#define OPFLG_IN2             0x0008  /* in2:   P2 is an input */
9077#define OPFLG_IN3             0x0010  /* in3:   P3 is an input */
9078#define OPFLG_OUT2            0x0020  /* out2:  P2 is an output */
9079#define OPFLG_OUT3            0x0040  /* out3:  P3 is an output */
9080#define OPFLG_INITIALIZER {\
9081/*   0 */ 0x00, 0x01, 0x01, 0x04, 0x04, 0x10, 0x00, 0x02,\
9082/*   8 */ 0x02, 0x02, 0x02, 0x02, 0x02, 0x00, 0x00, 0x24,\
9083/*  16 */ 0x00, 0x00, 0x00, 0x24, 0x04, 0x05, 0x04, 0x00,\
9084/*  24 */ 0x00, 0x01, 0x01, 0x05, 0x05, 0x00, 0x00, 0x00,\
9085/*  32 */ 0x02, 0x00, 0x00, 0x00, 0x02, 0x10, 0x00, 0x00,\
9086/*  40 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x11,\
9087/*  48 */ 0x11, 0x11, 0x08, 0x11, 0x11, 0x11, 0x11, 0x02,\
9088/*  56 */ 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
9089/*  64 */ 0x00, 0x02, 0x00, 0x01, 0x4c, 0x4c, 0x01, 0x01,\
9090/*  72 */ 0x01, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\
9091/*  80 */ 0x15, 0x01, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\
9092/*  88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x01, 0x24, 0x02, 0x01,\
9093/*  96 */ 0x08, 0x08, 0x00, 0x02, 0x01, 0x01, 0x02, 0x00,\
9094/* 104 */ 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
9095/* 112 */ 0x0c, 0x45, 0x15, 0x01, 0x02, 0x00, 0x01, 0x08,\
9096/* 120 */ 0x05, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02, 0x00,\
9097/* 128 */ 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,\
9098/* 136 */ 0x01, 0x00, 0x01, 0x00, 0x00, 0x04, 0x04, 0x04,\
9099/* 144 */ 0x04, 0x04, 0x02, 0x02, 0x00, 0x00, 0x00,}
9100
9101/************** End of opcodes.h *********************************************/
9102/************** Continuing where we left off in vdbe.h ***********************/
9103
9104/*
9105** Prototypes for the VDBE interface.  See comments on the implementation
9106** for a description of what each of these routines does.
9107*/
9108SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
9109SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
9110SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
9111SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
9112SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
9113SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
9114SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
9115SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
9116SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
9117SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
9118SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
9119SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
9120SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
9121SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
9122SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr);
9123SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
9124SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
9125SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
9126SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
9127SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
9128SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
9129SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);
9130SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
9131SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
9132SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
9133SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
9134#ifdef SQLITE_DEBUG
9135SQLITE_PRIVATE   int sqlite3VdbeAssertMayAbort(Vdbe *, int);
9136SQLITE_PRIVATE   void sqlite3VdbeTrace(Vdbe*,FILE*);
9137#endif
9138SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
9139SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
9140SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
9141SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
9142SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
9143SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
9144SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
9145SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
9146SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
9147SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
9148SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe*, int, u8);
9149SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
9150#ifndef SQLITE_OMIT_TRACE
9151SQLITE_PRIVATE   char *sqlite3VdbeExpandSql(Vdbe*, const char*);
9152#endif
9153
9154SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
9155SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
9156SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **);
9157
9158#ifndef SQLITE_OMIT_TRIGGER
9159SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
9160#endif
9161
9162
9163#ifndef NDEBUG
9164SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
9165# define VdbeComment(X)  sqlite3VdbeComment X
9166SQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
9167# define VdbeNoopComment(X)  sqlite3VdbeNoopComment X
9168#else
9169# define VdbeComment(X)
9170# define VdbeNoopComment(X)
9171#endif
9172
9173#endif
9174
9175/************** End of vdbe.h ************************************************/
9176/************** Continuing where we left off in sqliteInt.h ******************/
9177/************** Include pager.h in the middle of sqliteInt.h *****************/
9178/************** Begin file pager.h *******************************************/
9179/*
9180** 2001 September 15
9181**
9182** The author disclaims copyright to this source code.  In place of
9183** a legal notice, here is a blessing:
9184**
9185**    May you do good and not evil.
9186**    May you find forgiveness for yourself and forgive others.
9187**    May you share freely, never taking more than you give.
9188**
9189*************************************************************************
9190** This header file defines the interface that the sqlite page cache
9191** subsystem.  The page cache subsystem reads and writes a file a page
9192** at a time and provides a journal for rollback.
9193*/
9194
9195#ifndef _PAGER_H_
9196#define _PAGER_H_
9197
9198/*
9199** Default maximum size for persistent journal files. A negative
9200** value means no limit. This value may be overridden using the
9201** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
9202*/
9203#ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
9204  #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
9205#endif
9206
9207/*
9208** The type used to represent a page number.  The first page in a file
9209** is called page 1.  0 is used to represent "not a page".
9210*/
9211typedef u32 Pgno;
9212
9213/*
9214** Each open file is managed by a separate instance of the "Pager" structure.
9215*/
9216typedef struct Pager Pager;
9217
9218/*
9219** Handle type for pages.
9220*/
9221typedef struct PgHdr DbPage;
9222
9223/*
9224** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
9225** reserved for working around a windows/posix incompatibility). It is
9226** used in the journal to signify that the remainder of the journal file
9227** is devoted to storing a master journal name - there are no more pages to
9228** roll back. See comments for function writeMasterJournal() in pager.c
9229** for details.
9230*/
9231#define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
9232
9233/*
9234** Allowed values for the flags parameter to sqlite3PagerOpen().
9235**
9236** NOTE: These values must match the corresponding BTREE_ values in btree.h.
9237*/
9238#define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
9239#define PAGER_MEMORY        0x0002    /* In-memory database */
9240
9241/*
9242** Valid values for the second argument to sqlite3PagerLockingMode().
9243*/
9244#define PAGER_LOCKINGMODE_QUERY      -1
9245#define PAGER_LOCKINGMODE_NORMAL      0
9246#define PAGER_LOCKINGMODE_EXCLUSIVE   1
9247
9248/*
9249** Numeric constants that encode the journalmode.
9250*/
9251#define PAGER_JOURNALMODE_QUERY     (-1)  /* Query the value of journalmode */
9252#define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
9253#define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
9254#define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
9255#define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
9256#define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
9257#define PAGER_JOURNALMODE_WAL         5   /* Use write-ahead logging */
9258
9259/*
9260** Flags that make up the mask passed to sqlite3PagerAcquire().
9261*/
9262#define PAGER_ACQUIRE_NOCONTENT     0x01  /* Do not load data from disk */
9263#define PAGER_ACQUIRE_READONLY      0x02  /* Read-only page is acceptable */
9264
9265/*
9266** The remainder of this file contains the declarations of the functions
9267** that make up the Pager sub-system API. See source code comments for
9268** a detailed description of each routine.
9269*/
9270
9271/* Open and close a Pager connection. */
9272SQLITE_PRIVATE int sqlite3PagerOpen(
9273  sqlite3_vfs*,
9274  Pager **ppPager,
9275  const char*,
9276  int,
9277  int,
9278  int,
9279  void(*)(DbPage*)
9280);
9281SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
9282SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
9283
9284/* Functions used to configure a Pager object. */
9285SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
9286SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
9287SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
9288SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
9289SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
9290SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
9291SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int,int);
9292SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
9293SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
9294SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
9295SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
9296SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
9297SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
9298
9299/* Functions used to obtain and release page references. */
9300SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
9301#define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
9302SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
9303SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
9304SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
9305
9306/* Operations on page references. */
9307SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
9308SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
9309SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
9310SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
9311SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
9312SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
9313
9314/* Functions used to manage pager transactions and savepoints. */
9315SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
9316SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
9317SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
9318SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
9319SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
9320SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
9321SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
9322SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
9323SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
9324SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
9325
9326#ifndef SQLITE_OMIT_WAL
9327SQLITE_PRIVATE   int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*);
9328SQLITE_PRIVATE   int sqlite3PagerWalSupported(Pager *pPager);
9329SQLITE_PRIVATE   int sqlite3PagerWalCallback(Pager *pPager);
9330SQLITE_PRIVATE   int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
9331SQLITE_PRIVATE   int sqlite3PagerCloseWal(Pager *pPager);
9332#endif
9333
9334#ifdef SQLITE_ENABLE_ZIPVFS
9335SQLITE_PRIVATE   int sqlite3PagerWalFramesize(Pager *pPager);
9336#endif
9337
9338/* Functions used to query pager state and configuration. */
9339SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
9340SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
9341SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
9342SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
9343SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
9344SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
9345SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
9346SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
9347SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
9348SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
9349SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
9350SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *);
9351SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
9352
9353/* Functions used to truncate the database file. */
9354SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
9355
9356#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
9357SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
9358#endif
9359
9360/* Functions to support testing and debugging. */
9361#if !defined(NDEBUG) || defined(SQLITE_TEST)
9362SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
9363SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
9364#endif
9365#ifdef SQLITE_TEST
9366SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
9367SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
9368  void disable_simulated_io_errors(void);
9369  void enable_simulated_io_errors(void);
9370#else
9371# define disable_simulated_io_errors()
9372# define enable_simulated_io_errors()
9373#endif
9374
9375#endif /* _PAGER_H_ */
9376
9377/************** End of pager.h ***********************************************/
9378/************** Continuing where we left off in sqliteInt.h ******************/
9379/************** Include pcache.h in the middle of sqliteInt.h ****************/
9380/************** Begin file pcache.h ******************************************/
9381/*
9382** 2008 August 05
9383**
9384** The author disclaims copyright to this source code.  In place of
9385** a legal notice, here is a blessing:
9386**
9387**    May you do good and not evil.
9388**    May you find forgiveness for yourself and forgive others.
9389**    May you share freely, never taking more than you give.
9390**
9391*************************************************************************
9392** This header file defines the interface that the sqlite page cache
9393** subsystem.
9394*/
9395
9396#ifndef _PCACHE_H_
9397
9398typedef struct PgHdr PgHdr;
9399typedef struct PCache PCache;
9400
9401/*
9402** Every page in the cache is controlled by an instance of the following
9403** structure.
9404*/
9405struct PgHdr {
9406  sqlite3_pcache_page *pPage;    /* Pcache object page handle */
9407  void *pData;                   /* Page data */
9408  void *pExtra;                  /* Extra content */
9409  PgHdr *pDirty;                 /* Transient list of dirty pages */
9410  Pager *pPager;                 /* The pager this page is part of */
9411  Pgno pgno;                     /* Page number for this page */
9412#ifdef SQLITE_CHECK_PAGES
9413  u32 pageHash;                  /* Hash of page content */
9414#endif
9415  u16 flags;                     /* PGHDR flags defined below */
9416
9417  /**********************************************************************
9418  ** Elements above are public.  All that follows is private to pcache.c
9419  ** and should not be accessed by other modules.
9420  */
9421  i16 nRef;                      /* Number of users of this page */
9422  PCache *pCache;                /* Cache that owns this page */
9423
9424  PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
9425  PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
9426};
9427
9428/* Bit values for PgHdr.flags */
9429#define PGHDR_DIRTY             0x002  /* Page has changed */
9430#define PGHDR_NEED_SYNC         0x004  /* Fsync the rollback journal before
9431                                       ** writing this page to the database */
9432#define PGHDR_NEED_READ         0x008  /* Content is unread */
9433#define PGHDR_REUSE_UNLIKELY    0x010  /* A hint that reuse is unlikely */
9434#define PGHDR_DONT_WRITE        0x020  /* Do not write content to disk */
9435
9436#define PGHDR_MMAP              0x040  /* This is an mmap page object */
9437
9438/* Initialize and shutdown the page cache subsystem */
9439SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
9440SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
9441
9442/* Page cache buffer management:
9443** These routines implement SQLITE_CONFIG_PAGECACHE.
9444*/
9445SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
9446
9447/* Create a new pager cache.
9448** Under memory stress, invoke xStress to try to make pages clean.
9449** Only clean and unpinned pages can be reclaimed.
9450*/
9451SQLITE_PRIVATE void sqlite3PcacheOpen(
9452  int szPage,                    /* Size of every page */
9453  int szExtra,                   /* Extra space associated with each page */
9454  int bPurgeable,                /* True if pages are on backing store */
9455  int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
9456  void *pStress,                 /* Argument to xStress */
9457  PCache *pToInit                /* Preallocated space for the PCache */
9458);
9459
9460/* Modify the page-size after the cache has been created. */
9461SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
9462
9463/* Return the size in bytes of a PCache object.  Used to preallocate
9464** storage space.
9465*/
9466SQLITE_PRIVATE int sqlite3PcacheSize(void);
9467
9468/* One release per successful fetch.  Page is pinned until released.
9469** Reference counted.
9470*/
9471SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
9472SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
9473
9474SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */
9475SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
9476SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
9477SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */
9478
9479/* Change a page number.  Used by incr-vacuum. */
9480SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
9481
9482/* Remove all pages with pgno>x.  Reset the cache if x==0 */
9483SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
9484
9485/* Get a list of all dirty pages in the cache, sorted by page number */
9486SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
9487
9488/* Reset and close the cache object */
9489SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
9490
9491/* Clear flags from pages of the page cache */
9492SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
9493
9494/* Discard the contents of the cache */
9495SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
9496
9497/* Return the total number of outstanding page references */
9498SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
9499
9500/* Increment the reference count of an existing page */
9501SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
9502
9503SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
9504
9505/* Return the total number of pages stored in the cache */
9506SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
9507
9508#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
9509/* Iterate through all dirty pages currently stored in the cache. This
9510** interface is only available if SQLITE_CHECK_PAGES is defined when the
9511** library is built.
9512*/
9513SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
9514#endif
9515
9516/* Set and get the suggested cache-size for the specified pager-cache.
9517**
9518** If no global maximum is configured, then the system attempts to limit
9519** the total number of pages cached by purgeable pager-caches to the sum
9520** of the suggested cache-sizes.
9521*/
9522SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
9523#ifdef SQLITE_TEST
9524SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
9525#endif
9526
9527/* Free up as much memory as possible from the page cache */
9528SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
9529
9530#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
9531/* Try to return memory used by the pcache module to the main memory heap */
9532SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
9533#endif
9534
9535#ifdef SQLITE_TEST
9536SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
9537#endif
9538
9539SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
9540
9541#endif /* _PCACHE_H_ */
9542
9543/************** End of pcache.h **********************************************/
9544/************** Continuing where we left off in sqliteInt.h ******************/
9545
9546/************** Include os.h in the middle of sqliteInt.h ********************/
9547/************** Begin file os.h **********************************************/
9548/*
9549** 2001 September 16
9550**
9551** The author disclaims copyright to this source code.  In place of
9552** a legal notice, here is a blessing:
9553**
9554**    May you do good and not evil.
9555**    May you find forgiveness for yourself and forgive others.
9556**    May you share freely, never taking more than you give.
9557**
9558******************************************************************************
9559**
9560** This header file (together with is companion C source-code file
9561** "os.c") attempt to abstract the underlying operating system so that
9562** the SQLite library will work on both POSIX and windows systems.
9563**
9564** This header file is #include-ed by sqliteInt.h and thus ends up
9565** being included by every source file.
9566*/
9567#ifndef _SQLITE_OS_H_
9568#define _SQLITE_OS_H_
9569
9570/*
9571** Figure out if we are dealing with Unix, Windows, or some other
9572** operating system.  After the following block of preprocess macros,
9573** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, and SQLITE_OS_OTHER
9574** will defined to either 1 or 0.  One of the four will be 1.  The other
9575** three will be 0.
9576*/
9577#if defined(SQLITE_OS_OTHER)
9578# if SQLITE_OS_OTHER==1
9579#   undef SQLITE_OS_UNIX
9580#   define SQLITE_OS_UNIX 0
9581#   undef SQLITE_OS_WIN
9582#   define SQLITE_OS_WIN 0
9583# else
9584#   undef SQLITE_OS_OTHER
9585# endif
9586#endif
9587#if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
9588# define SQLITE_OS_OTHER 0
9589# ifndef SQLITE_OS_WIN
9590#   if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
9591#     define SQLITE_OS_WIN 1
9592#     define SQLITE_OS_UNIX 0
9593#   else
9594#     define SQLITE_OS_WIN 0
9595#     define SQLITE_OS_UNIX 1
9596#  endif
9597# else
9598#  define SQLITE_OS_UNIX 0
9599# endif
9600#else
9601# ifndef SQLITE_OS_WIN
9602#  define SQLITE_OS_WIN 0
9603# endif
9604#endif
9605
9606#if SQLITE_OS_WIN
9607# include <windows.h>
9608#endif
9609
9610/*
9611** Determine if we are dealing with Windows NT.
9612**
9613** We ought to be able to determine if we are compiling for win98 or winNT
9614** using the _WIN32_WINNT macro as follows:
9615**
9616** #if defined(_WIN32_WINNT)
9617** # define SQLITE_OS_WINNT 1
9618** #else
9619** # define SQLITE_OS_WINNT 0
9620** #endif
9621**
9622** However, vs2005 does not set _WIN32_WINNT by default, as it ought to,
9623** so the above test does not work.  We'll just assume that everything is
9624** winNT unless the programmer explicitly says otherwise by setting
9625** SQLITE_OS_WINNT to 0.
9626*/
9627#if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
9628# define SQLITE_OS_WINNT 1
9629#endif
9630
9631/*
9632** Determine if we are dealing with WindowsCE - which has a much
9633** reduced API.
9634*/
9635#if defined(_WIN32_WCE)
9636# define SQLITE_OS_WINCE 1
9637#else
9638# define SQLITE_OS_WINCE 0
9639#endif
9640
9641/*
9642** Determine if we are dealing with WinRT, which provides only a subset of
9643** the full Win32 API.
9644*/
9645#if !defined(SQLITE_OS_WINRT)
9646# define SQLITE_OS_WINRT 0
9647#endif
9648
9649/* If the SET_FULLSYNC macro is not defined above, then make it
9650** a no-op
9651*/
9652#ifndef SET_FULLSYNC
9653# define SET_FULLSYNC(x,y)
9654#endif
9655
9656/*
9657** The default size of a disk sector
9658*/
9659#ifndef SQLITE_DEFAULT_SECTOR_SIZE
9660# define SQLITE_DEFAULT_SECTOR_SIZE 4096
9661#endif
9662
9663/*
9664** Temporary files are named starting with this prefix followed by 16 random
9665** alphanumeric characters, and no file extension. They are stored in the
9666** OS's standard temporary file directory, and are deleted prior to exit.
9667** If sqlite is being embedded in another program, you may wish to change the
9668** prefix to reflect your program's name, so that if your program exits
9669** prematurely, old temporary files can be easily identified. This can be done
9670** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
9671**
9672** 2006-10-31:  The default prefix used to be "sqlite_".  But then
9673** Mcafee started using SQLite in their anti-virus product and it
9674** started putting files with the "sqlite" name in the c:/temp folder.
9675** This annoyed many windows users.  Those users would then do a
9676** Google search for "sqlite", find the telephone numbers of the
9677** developers and call to wake them up at night and complain.
9678** For this reason, the default name prefix is changed to be "sqlite"
9679** spelled backwards.  So the temp files are still identified, but
9680** anybody smart enough to figure out the code is also likely smart
9681** enough to know that calling the developer will not help get rid
9682** of the file.
9683*/
9684#ifndef SQLITE_TEMP_FILE_PREFIX
9685# define SQLITE_TEMP_FILE_PREFIX "etilqs_"
9686#endif
9687
9688/*
9689** The following values may be passed as the second argument to
9690** sqlite3OsLock(). The various locks exhibit the following semantics:
9691**
9692** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
9693** RESERVED:  A single process may hold a RESERVED lock on a file at
9694**            any time. Other processes may hold and obtain new SHARED locks.
9695** PENDING:   A single process may hold a PENDING lock on a file at
9696**            any one time. Existing SHARED locks may persist, but no new
9697**            SHARED locks may be obtained by other processes.
9698** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
9699**
9700** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
9701** process that requests an EXCLUSIVE lock may actually obtain a PENDING
9702** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
9703** sqlite3OsLock().
9704*/
9705#define NO_LOCK         0
9706#define SHARED_LOCK     1
9707#define RESERVED_LOCK   2
9708#define PENDING_LOCK    3
9709#define EXCLUSIVE_LOCK  4
9710
9711/*
9712** File Locking Notes:  (Mostly about windows but also some info for Unix)
9713**
9714** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
9715** those functions are not available.  So we use only LockFile() and
9716** UnlockFile().
9717**
9718** LockFile() prevents not just writing but also reading by other processes.
9719** A SHARED_LOCK is obtained by locking a single randomly-chosen
9720** byte out of a specific range of bytes. The lock byte is obtained at
9721** random so two separate readers can probably access the file at the
9722** same time, unless they are unlucky and choose the same lock byte.
9723** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
9724** There can only be one writer.  A RESERVED_LOCK is obtained by locking
9725** a single byte of the file that is designated as the reserved lock byte.
9726** A PENDING_LOCK is obtained by locking a designated byte different from
9727** the RESERVED_LOCK byte.
9728**
9729** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
9730** which means we can use reader/writer locks.  When reader/writer locks
9731** are used, the lock is placed on the same range of bytes that is used
9732** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
9733** will support two or more Win95 readers or two or more WinNT readers.
9734** But a single Win95 reader will lock out all WinNT readers and a single
9735** WinNT reader will lock out all other Win95 readers.
9736**
9737** The following #defines specify the range of bytes used for locking.
9738** SHARED_SIZE is the number of bytes available in the pool from which
9739** a random byte is selected for a shared lock.  The pool of bytes for
9740** shared locks begins at SHARED_FIRST.
9741**
9742** The same locking strategy and
9743** byte ranges are used for Unix.  This leaves open the possiblity of having
9744** clients on win95, winNT, and unix all talking to the same shared file
9745** and all locking correctly.  To do so would require that samba (or whatever
9746** tool is being used for file sharing) implements locks correctly between
9747** windows and unix.  I'm guessing that isn't likely to happen, but by
9748** using the same locking range we are at least open to the possibility.
9749**
9750** Locking in windows is manditory.  For this reason, we cannot store
9751** actual data in the bytes used for locking.  The pager never allocates
9752** the pages involved in locking therefore.  SHARED_SIZE is selected so
9753** that all locks will fit on a single page even at the minimum page size.
9754** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
9755** is set high so that we don't have to allocate an unused page except
9756** for very large databases.  But one should test the page skipping logic
9757** by setting PENDING_BYTE low and running the entire regression suite.
9758**
9759** Changing the value of PENDING_BYTE results in a subtly incompatible
9760** file format.  Depending on how it is changed, you might not notice
9761** the incompatibility right away, even running a full regression test.
9762** The default location of PENDING_BYTE is the first byte past the
9763** 1GB boundary.
9764**
9765*/
9766#ifdef SQLITE_OMIT_WSD
9767# define PENDING_BYTE     (0x40000000)
9768#else
9769# define PENDING_BYTE      sqlite3PendingByte
9770#endif
9771#define RESERVED_BYTE     (PENDING_BYTE+1)
9772#define SHARED_FIRST      (PENDING_BYTE+2)
9773#define SHARED_SIZE       510
9774
9775/*
9776** Wrapper around OS specific sqlite3_os_init() function.
9777*/
9778SQLITE_PRIVATE int sqlite3OsInit(void);
9779
9780/*
9781** Functions for accessing sqlite3_file methods
9782*/
9783SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
9784SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
9785SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
9786SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
9787SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
9788SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
9789SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
9790SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
9791SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
9792SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
9793SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
9794#define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
9795SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
9796SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
9797SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
9798SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
9799SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
9800SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
9801SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);
9802SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);
9803
9804
9805/*
9806** Functions for accessing sqlite3_vfs methods
9807*/
9808SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
9809SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
9810SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
9811SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
9812#ifndef SQLITE_OMIT_LOAD_EXTENSION
9813SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
9814SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
9815SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
9816SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
9817#endif /* SQLITE_OMIT_LOAD_EXTENSION */
9818SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
9819SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
9820SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
9821
9822/*
9823** Convenience functions for opening and closing files using
9824** sqlite3_malloc() to obtain space for the file-handle structure.
9825*/
9826SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
9827SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
9828
9829#endif /* _SQLITE_OS_H_ */
9830
9831/************** End of os.h **************************************************/
9832/************** Continuing where we left off in sqliteInt.h ******************/
9833/************** Include mutex.h in the middle of sqliteInt.h *****************/
9834/************** Begin file mutex.h *******************************************/
9835/*
9836** 2007 August 28
9837**
9838** The author disclaims copyright to this source code.  In place of
9839** a legal notice, here is a blessing:
9840**
9841**    May you do good and not evil.
9842**    May you find forgiveness for yourself and forgive others.
9843**    May you share freely, never taking more than you give.
9844**
9845*************************************************************************
9846**
9847** This file contains the common header for all mutex implementations.
9848** The sqliteInt.h header #includes this file so that it is available
9849** to all source files.  We break it out in an effort to keep the code
9850** better organized.
9851**
9852** NOTE:  source files should *not* #include this header file directly.
9853** Source files should #include the sqliteInt.h file and let that file
9854** include this one indirectly.
9855*/
9856
9857
9858/*
9859** Figure out what version of the code to use.  The choices are
9860**
9861**   SQLITE_MUTEX_OMIT         No mutex logic.  Not even stubs.  The
9862**                             mutexes implemention cannot be overridden
9863**                             at start-time.
9864**
9865**   SQLITE_MUTEX_NOOP         For single-threaded applications.  No
9866**                             mutual exclusion is provided.  But this
9867**                             implementation can be overridden at
9868**                             start-time.
9869**
9870**   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
9871**
9872**   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
9873*/
9874#if !SQLITE_THREADSAFE
9875# define SQLITE_MUTEX_OMIT
9876#endif
9877#if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
9878#  if SQLITE_OS_UNIX
9879#    define SQLITE_MUTEX_PTHREADS
9880#  elif SQLITE_OS_WIN
9881#    define SQLITE_MUTEX_W32
9882#  else
9883#    define SQLITE_MUTEX_NOOP
9884#  endif
9885#endif
9886
9887#ifdef SQLITE_MUTEX_OMIT
9888/*
9889** If this is a no-op implementation, implement everything as macros.
9890*/
9891#define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
9892#define sqlite3_mutex_free(X)
9893#define sqlite3_mutex_enter(X)
9894#define sqlite3_mutex_try(X)      SQLITE_OK
9895#define sqlite3_mutex_leave(X)
9896#define sqlite3_mutex_held(X)     ((void)(X),1)
9897#define sqlite3_mutex_notheld(X)  ((void)(X),1)
9898#define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)
9899#define sqlite3MutexInit()        SQLITE_OK
9900#define sqlite3MutexEnd()
9901#define MUTEX_LOGIC(X)
9902#else
9903#define MUTEX_LOGIC(X)            X
9904#endif /* defined(SQLITE_MUTEX_OMIT) */
9905
9906/************** End of mutex.h ***********************************************/
9907/************** Continuing where we left off in sqliteInt.h ******************/
9908
9909
9910/*
9911** Each database file to be accessed by the system is an instance
9912** of the following structure.  There are normally two of these structures
9913** in the sqlite.aDb[] array.  aDb[0] is the main database file and
9914** aDb[1] is the database file used to hold temporary tables.  Additional
9915** databases may be attached.
9916*/
9917struct Db {
9918  char *zName;         /* Name of this database */
9919  Btree *pBt;          /* The B*Tree structure for this database file */
9920  u8 inTrans;          /* 0: not writable.  1: Transaction.  2: Checkpoint */
9921  u8 safety_level;     /* How aggressive at syncing data to disk */
9922  Schema *pSchema;     /* Pointer to database schema (possibly shared) */
9923};
9924
9925/*
9926** An instance of the following structure stores a database schema.
9927**
9928** Most Schema objects are associated with a Btree.  The exception is
9929** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
9930** In shared cache mode, a single Schema object can be shared by multiple
9931** Btrees that refer to the same underlying BtShared object.
9932**
9933** Schema objects are automatically deallocated when the last Btree that
9934** references them is destroyed.   The TEMP Schema is manually freed by
9935** sqlite3_close().
9936*
9937** A thread must be holding a mutex on the corresponding Btree in order
9938** to access Schema content.  This implies that the thread must also be
9939** holding a mutex on the sqlite3 connection pointer that owns the Btree.
9940** For a TEMP Schema, only the connection mutex is required.
9941*/
9942struct Schema {
9943  int schema_cookie;   /* Database schema version number for this file */
9944  int iGeneration;     /* Generation counter.  Incremented with each change */
9945  Hash tblHash;        /* All tables indexed by name */
9946  Hash idxHash;        /* All (named) indices indexed by name */
9947  Hash trigHash;       /* All triggers indexed by name */
9948  Hash fkeyHash;       /* All foreign keys by referenced table name */
9949  Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
9950  u8 file_format;      /* Schema format version for this file */
9951  u8 enc;              /* Text encoding used by this database */
9952  u16 flags;           /* Flags associated with this schema */
9953  int cache_size;      /* Number of pages to use in the cache */
9954};
9955
9956/*
9957** These macros can be used to test, set, or clear bits in the
9958** Db.pSchema->flags field.
9959*/
9960#define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->flags&(P))==(P))
9961#define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->flags&(P))!=0)
9962#define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->flags|=(P)
9963#define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->flags&=~(P)
9964
9965/*
9966** Allowed values for the DB.pSchema->flags field.
9967**
9968** The DB_SchemaLoaded flag is set after the database schema has been
9969** read into internal hash tables.
9970**
9971** DB_UnresetViews means that one or more views have column names that
9972** have been filled out.  If the schema changes, these column names might
9973** changes and so the view will need to be reset.
9974*/
9975#define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
9976#define DB_UnresetViews    0x0002  /* Some views have defined column names */
9977#define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
9978
9979/*
9980** The number of different kinds of things that can be limited
9981** using the sqlite3_limit() interface.
9982*/
9983#define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1)
9984
9985/*
9986** Lookaside malloc is a set of fixed-size buffers that can be used
9987** to satisfy small transient memory allocation requests for objects
9988** associated with a particular database connection.  The use of
9989** lookaside malloc provides a significant performance enhancement
9990** (approx 10%) by avoiding numerous malloc/free requests while parsing
9991** SQL statements.
9992**
9993** The Lookaside structure holds configuration information about the
9994** lookaside malloc subsystem.  Each available memory allocation in
9995** the lookaside subsystem is stored on a linked list of LookasideSlot
9996** objects.
9997**
9998** Lookaside allocations are only allowed for objects that are associated
9999** with a particular database connection.  Hence, schema information cannot
10000** be stored in lookaside because in shared cache mode the schema information
10001** is shared by multiple database connections.  Therefore, while parsing
10002** schema information, the Lookaside.bEnabled flag is cleared so that
10003** lookaside allocations are not used to construct the schema objects.
10004*/
10005struct Lookaside {
10006  u16 sz;                 /* Size of each buffer in bytes */
10007  u8 bEnabled;            /* False to disable new lookaside allocations */
10008  u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
10009  int nOut;               /* Number of buffers currently checked out */
10010  int mxOut;              /* Highwater mark for nOut */
10011  int anStat[3];          /* 0: hits.  1: size misses.  2: full misses */
10012  LookasideSlot *pFree;   /* List of available buffers */
10013  void *pStart;           /* First byte of available memory space */
10014  void *pEnd;             /* First byte past end of available space */
10015};
10016struct LookasideSlot {
10017  LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
10018};
10019
10020/*
10021** A hash table for function definitions.
10022**
10023** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
10024** Collisions are on the FuncDef.pHash chain.
10025*/
10026struct FuncDefHash {
10027  FuncDef *a[23];       /* Hash table for functions */
10028};
10029
10030/*
10031** Each database connection is an instance of the following structure.
10032*/
10033struct sqlite3 {
10034  sqlite3_vfs *pVfs;            /* OS Interface */
10035  struct Vdbe *pVdbe;           /* List of active virtual machines */
10036  CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
10037  sqlite3_mutex *mutex;         /* Connection mutex */
10038  Db *aDb;                      /* All backends */
10039  int nDb;                      /* Number of backends currently in use */
10040  int flags;                    /* Miscellaneous flags. See below */
10041  i64 lastRowid;                /* ROWID of most recent insert (see above) */
10042  i64 szMmap;                   /* Default mmap_size setting */
10043  unsigned int openFlags;       /* Flags passed to sqlite3_vfs.xOpen() */
10044  int errCode;                  /* Most recent error code (SQLITE_*) */
10045  int errMask;                  /* & result codes with this before returning */
10046  u16 dbOptFlags;               /* Flags to enable/disable optimizations */
10047  u8 autoCommit;                /* The auto-commit flag. */
10048  u8 temp_store;                /* 1: file 2: memory 0: default */
10049  u8 mallocFailed;              /* True if we have seen a malloc failure */
10050  u8 dfltLockMode;              /* Default locking-mode for attached dbs */
10051  signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
10052  u8 suppressErr;               /* Do not issue error messages if true */
10053  u8 vtabOnConflict;            /* Value to return for s3_vtab_on_conflict() */
10054  u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
10055  int nextPagesize;             /* Pagesize after VACUUM if >0 */
10056  u32 magic;                    /* Magic number for detect library misuse */
10057  int nChange;                  /* Value returned by sqlite3_changes() */
10058  int nTotalChange;             /* Value returned by sqlite3_total_changes() */
10059  int aLimit[SQLITE_N_LIMIT];   /* Limits */
10060  struct sqlite3InitInfo {      /* Information used during initialization */
10061    int newTnum;                /* Rootpage of table being initialized */
10062    u8 iDb;                     /* Which db file is being initialized */
10063    u8 busy;                    /* TRUE if currently initializing */
10064    u8 orphanTrigger;           /* Last statement is orphaned TEMP trigger */
10065  } init;
10066  int activeVdbeCnt;            /* Number of VDBEs currently executing */
10067  int writeVdbeCnt;             /* Number of active VDBEs that are writing */
10068  int vdbeExecCnt;              /* Number of nested calls to VdbeExec() */
10069  int nExtension;               /* Number of loaded extensions */
10070  void **aExtension;            /* Array of shared library handles */
10071  void (*xTrace)(void*,const char*);        /* Trace function */
10072  void *pTraceArg;                          /* Argument to the trace function */
10073  void (*xProfile)(void*,const char*,u64);  /* Profiling function */
10074  void *pProfileArg;                        /* Argument to profile function */
10075  void *pCommitArg;                 /* Argument to xCommitCallback() */
10076  int (*xCommitCallback)(void*);    /* Invoked at every commit. */
10077  void *pRollbackArg;               /* Argument to xRollbackCallback() */
10078  void (*xRollbackCallback)(void*); /* Invoked at every commit. */
10079  void *pUpdateArg;
10080  void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
10081#ifndef SQLITE_OMIT_WAL
10082  int (*xWalCallback)(void *, sqlite3 *, const char *, int);
10083  void *pWalArg;
10084#endif
10085  void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
10086  void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
10087  void *pCollNeededArg;
10088  sqlite3_value *pErr;          /* Most recent error message */
10089  char *zErrMsg;                /* Most recent error message (UTF-8 encoded) */
10090  char *zErrMsg16;              /* Most recent error message (UTF-16 encoded) */
10091  union {
10092    volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
10093    double notUsed1;            /* Spacer */
10094  } u1;
10095  Lookaside lookaside;          /* Lookaside malloc configuration */
10096#ifndef SQLITE_OMIT_AUTHORIZATION
10097  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
10098                                /* Access authorization function */
10099  void *pAuthArg;               /* 1st argument to the access auth function */
10100#endif
10101#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
10102  int (*xProgress)(void *);     /* The progress callback */
10103  void *pProgressArg;           /* Argument to the progress callback */
10104  int nProgressOps;             /* Number of opcodes for progress callback */
10105#endif
10106#ifndef SQLITE_OMIT_VIRTUALTABLE
10107  int nVTrans;                  /* Allocated size of aVTrans */
10108  Hash aModule;                 /* populated by sqlite3_create_module() */
10109  VtabCtx *pVtabCtx;            /* Context for active vtab connect/create */
10110  VTable **aVTrans;             /* Virtual tables with open transactions */
10111  VTable *pDisconnect;    /* Disconnect these in next sqlite3_prepare() */
10112#endif
10113  FuncDefHash aFunc;            /* Hash table of connection functions */
10114  Hash aCollSeq;                /* All collating sequences */
10115  BusyHandler busyHandler;      /* Busy callback */
10116  Db aDbStatic[2];              /* Static space for the 2 default backends */
10117  Savepoint *pSavepoint;        /* List of active savepoints */
10118  int busyTimeout;              /* Busy handler timeout, in msec */
10119  int nSavepoint;               /* Number of non-transaction savepoints */
10120  int nStatement;               /* Number of nested statement-transactions  */
10121  i64 nDeferredCons;            /* Net deferred constraints this transaction. */
10122  int *pnBytesFreed;            /* If not NULL, increment this in DbFree() */
10123
10124#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
10125  /* The following variables are all protected by the STATIC_MASTER
10126  ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
10127  **
10128  ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
10129  ** unlock so that it can proceed.
10130  **
10131  ** When X.pBlockingConnection==Y, that means that something that X tried
10132  ** tried to do recently failed with an SQLITE_LOCKED error due to locks
10133  ** held by Y.
10134  */
10135  sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
10136  sqlite3 *pUnlockConnection;           /* Connection to watch for unlock */
10137  void *pUnlockArg;                     /* Argument to xUnlockNotify */
10138  void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */
10139  sqlite3 *pNextBlocked;        /* Next in list of all blocked connections */
10140#endif
10141};
10142
10143/*
10144** A macro to discover the encoding of a database.
10145*/
10146#define ENC(db) ((db)->aDb[0].pSchema->enc)
10147
10148/*
10149** Possible values for the sqlite3.flags.
10150*/
10151#define SQLITE_VdbeTrace      0x00000001  /* True to trace VDBE execution */
10152#define SQLITE_InternChanges  0x00000002  /* Uncommitted Hash table changes */
10153#define SQLITE_FullColNames   0x00000004  /* Show full column names on SELECT */
10154#define SQLITE_ShortColNames  0x00000008  /* Show short columns names */
10155#define SQLITE_CountRows      0x00000010  /* Count rows changed by INSERT, */
10156                                          /*   DELETE, or UPDATE and return */
10157                                          /*   the count using a callback. */
10158#define SQLITE_NullCallback   0x00000020  /* Invoke the callback once if the */
10159                                          /*   result set is empty */
10160#define SQLITE_SqlTrace       0x00000040  /* Debug print SQL as it executes */
10161#define SQLITE_VdbeListing    0x00000080  /* Debug listings of VDBE programs */
10162#define SQLITE_WriteSchema    0x00000100  /* OK to update SQLITE_MASTER */
10163#define SQLITE_VdbeAddopTrace 0x00000200  /* Trace sqlite3VdbeAddOp() calls */
10164#define SQLITE_IgnoreChecks   0x00000400  /* Do not enforce check constraints */
10165#define SQLITE_ReadUncommitted 0x0000800  /* For shared-cache mode */
10166#define SQLITE_LegacyFileFmt  0x00001000  /* Create new databases in format 1 */
10167#define SQLITE_FullFSync      0x00002000  /* Use full fsync on the backend */
10168#define SQLITE_CkptFullFSync  0x00004000  /* Use full fsync for checkpoint */
10169#define SQLITE_RecoveryMode   0x00008000  /* Ignore schema errors */
10170#define SQLITE_ReverseOrder   0x00010000  /* Reverse unordered SELECTs */
10171#define SQLITE_RecTriggers    0x00020000  /* Enable recursive triggers */
10172#define SQLITE_ForeignKeys    0x00040000  /* Enforce foreign key constraints  */
10173#define SQLITE_AutoIndex      0x00080000  /* Enable automatic indexes */
10174#define SQLITE_PreferBuiltin  0x00100000  /* Preference to built-in funcs */
10175#define SQLITE_LoadExtension  0x00200000  /* Enable load_extension */
10176#define SQLITE_EnableTrigger  0x00400000  /* True to enable triggers */
10177
10178/*
10179** Bits of the sqlite3.dbOptFlags field that are used by the
10180** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
10181** selectively disable various optimizations.
10182*/
10183#define SQLITE_QueryFlattener 0x0001   /* Query flattening */
10184#define SQLITE_ColumnCache    0x0002   /* Column cache */
10185#define SQLITE_GroupByOrder   0x0004   /* GROUPBY cover of ORDERBY */
10186#define SQLITE_FactorOutConst 0x0008   /* Constant factoring */
10187#define SQLITE_IdxRealAsInt   0x0010   /* Store REAL as INT in indices */
10188#define SQLITE_DistinctOpt    0x0020   /* DISTINCT using indexes */
10189#define SQLITE_CoverIdxScan   0x0040   /* Covering index scans */
10190#define SQLITE_OrderByIdxJoin 0x0080   /* ORDER BY of joins via index */
10191#define SQLITE_SubqCoroutine  0x0100   /* Evaluate subqueries as coroutines */
10192#define SQLITE_Transitive     0x0200   /* Transitive constraints */
10193#define SQLITE_AllOpts        0xffff   /* All optimizations */
10194
10195/*
10196** Macros for testing whether or not optimizations are enabled or disabled.
10197*/
10198#ifndef SQLITE_OMIT_BUILTIN_TEST
10199#define OptimizationDisabled(db, mask)  (((db)->dbOptFlags&(mask))!=0)
10200#define OptimizationEnabled(db, mask)   (((db)->dbOptFlags&(mask))==0)
10201#else
10202#define OptimizationDisabled(db, mask)  0
10203#define OptimizationEnabled(db, mask)   1
10204#endif
10205
10206/*
10207** Possible values for the sqlite.magic field.
10208** The numbers are obtained at random and have no special meaning, other
10209** than being distinct from one another.
10210*/
10211#define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
10212#define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
10213#define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
10214#define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
10215#define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
10216#define SQLITE_MAGIC_ZOMBIE   0x64cffc7f  /* Close with last statement close */
10217
10218/*
10219** Each SQL function is defined by an instance of the following
10220** structure.  A pointer to this structure is stored in the sqlite.aFunc
10221** hash table.  When multiple functions have the same name, the hash table
10222** points to a linked list of these structures.
10223*/
10224struct FuncDef {
10225  i16 nArg;            /* Number of arguments.  -1 means unlimited */
10226  u8 iPrefEnc;         /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
10227  u8 flags;            /* Some combination of SQLITE_FUNC_* */
10228  void *pUserData;     /* User data parameter */
10229  FuncDef *pNext;      /* Next function with same name */
10230  void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
10231  void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
10232  void (*xFinalize)(sqlite3_context*);                /* Aggregate finalizer */
10233  char *zName;         /* SQL name of the function. */
10234  FuncDef *pHash;      /* Next with a different name but the same hash */
10235  FuncDestructor *pDestructor;   /* Reference counted destructor function */
10236};
10237
10238/*
10239** This structure encapsulates a user-function destructor callback (as
10240** configured using create_function_v2()) and a reference counter. When
10241** create_function_v2() is called to create a function with a destructor,
10242** a single object of this type is allocated. FuncDestructor.nRef is set to
10243** the number of FuncDef objects created (either 1 or 3, depending on whether
10244** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
10245** member of each of the new FuncDef objects is set to point to the allocated
10246** FuncDestructor.
10247**
10248** Thereafter, when one of the FuncDef objects is deleted, the reference
10249** count on this object is decremented. When it reaches 0, the destructor
10250** is invoked and the FuncDestructor structure freed.
10251*/
10252struct FuncDestructor {
10253  int nRef;
10254  void (*xDestroy)(void *);
10255  void *pUserData;
10256};
10257
10258/*
10259** Possible values for FuncDef.flags.  Note that the _LENGTH and _TYPEOF
10260** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG.  There
10261** are assert() statements in the code to verify this.
10262*/
10263#define SQLITE_FUNC_LIKE     0x01 /* Candidate for the LIKE optimization */
10264#define SQLITE_FUNC_CASE     0x02 /* Case-sensitive LIKE-type function */
10265#define SQLITE_FUNC_EPHEM    0x04 /* Ephemeral.  Delete with VDBE */
10266#define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */
10267#define SQLITE_FUNC_COUNT    0x10 /* Built-in count(*) aggregate */
10268#define SQLITE_FUNC_COALESCE 0x20 /* Built-in coalesce() or ifnull() function */
10269#define SQLITE_FUNC_LENGTH   0x40 /* Built-in length() function */
10270#define SQLITE_FUNC_TYPEOF   0x80 /* Built-in typeof() function */
10271
10272/*
10273** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
10274** used to create the initializers for the FuncDef structures.
10275**
10276**   FUNCTION(zName, nArg, iArg, bNC, xFunc)
10277**     Used to create a scalar function definition of a function zName
10278**     implemented by C function xFunc that accepts nArg arguments. The
10279**     value passed as iArg is cast to a (void*) and made available
10280**     as the user-data (sqlite3_user_data()) for the function. If
10281**     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
10282**
10283**   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
10284**     Used to create an aggregate function definition implemented by
10285**     the C functions xStep and xFinal. The first four parameters
10286**     are interpreted in the same way as the first 4 parameters to
10287**     FUNCTION().
10288**
10289**   LIKEFUNC(zName, nArg, pArg, flags)
10290**     Used to create a scalar function definition of a function zName
10291**     that accepts nArg arguments and is implemented by a call to C
10292**     function likeFunc. Argument pArg is cast to a (void *) and made
10293**     available as the function user-data (sqlite3_user_data()). The
10294**     FuncDef.flags variable is set to the value passed as the flags
10295**     parameter.
10296*/
10297#define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
10298  {nArg, SQLITE_UTF8, (bNC*SQLITE_FUNC_NEEDCOLL), \
10299   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
10300#define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
10301  {nArg, SQLITE_UTF8, (bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags, \
10302   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
10303#define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
10304  {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
10305   pArg, 0, xFunc, 0, 0, #zName, 0, 0}
10306#define LIKEFUNC(zName, nArg, arg, flags) \
10307  {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
10308#define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
10309  {nArg, SQLITE_UTF8, nc*SQLITE_FUNC_NEEDCOLL, \
10310   SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
10311
10312/*
10313** All current savepoints are stored in a linked list starting at
10314** sqlite3.pSavepoint. The first element in the list is the most recently
10315** opened savepoint. Savepoints are added to the list by the vdbe
10316** OP_Savepoint instruction.
10317*/
10318struct Savepoint {
10319  char *zName;                        /* Savepoint name (nul-terminated) */
10320  i64 nDeferredCons;                  /* Number of deferred fk violations */
10321  Savepoint *pNext;                   /* Parent savepoint (if any) */
10322};
10323
10324/*
10325** The following are used as the second parameter to sqlite3Savepoint(),
10326** and as the P1 argument to the OP_Savepoint instruction.
10327*/
10328#define SAVEPOINT_BEGIN      0
10329#define SAVEPOINT_RELEASE    1
10330#define SAVEPOINT_ROLLBACK   2
10331
10332
10333/*
10334** Each SQLite module (virtual table definition) is defined by an
10335** instance of the following structure, stored in the sqlite3.aModule
10336** hash table.
10337*/
10338struct Module {
10339  const sqlite3_module *pModule;       /* Callback pointers */
10340  const char *zName;                   /* Name passed to create_module() */
10341  void *pAux;                          /* pAux passed to create_module() */
10342  void (*xDestroy)(void *);            /* Module destructor function */
10343};
10344
10345/*
10346** information about each column of an SQL table is held in an instance
10347** of this structure.
10348*/
10349struct Column {
10350  char *zName;     /* Name of this column */
10351  Expr *pDflt;     /* Default value of this column */
10352  char *zDflt;     /* Original text of the default value */
10353  char *zType;     /* Data type for this column */
10354  char *zColl;     /* Collating sequence.  If NULL, use the default */
10355  u8 notNull;      /* An OE_ code for handling a NOT NULL constraint */
10356  char affinity;   /* One of the SQLITE_AFF_... values */
10357  u16 colFlags;    /* Boolean properties.  See COLFLAG_ defines below */
10358};
10359
10360/* Allowed values for Column.colFlags:
10361*/
10362#define COLFLAG_PRIMKEY  0x0001    /* Column is part of the primary key */
10363#define COLFLAG_HIDDEN   0x0002    /* A hidden column in a virtual table */
10364
10365/*
10366** A "Collating Sequence" is defined by an instance of the following
10367** structure. Conceptually, a collating sequence consists of a name and
10368** a comparison routine that defines the order of that sequence.
10369**
10370** If CollSeq.xCmp is NULL, it means that the
10371** collating sequence is undefined.  Indices built on an undefined
10372** collating sequence may not be read or written.
10373*/
10374struct CollSeq {
10375  char *zName;          /* Name of the collating sequence, UTF-8 encoded */
10376  u8 enc;               /* Text encoding handled by xCmp() */
10377  void *pUser;          /* First argument to xCmp() */
10378  int (*xCmp)(void*,int, const void*, int, const void*);
10379  void (*xDel)(void*);  /* Destructor for pUser */
10380};
10381
10382/*
10383** A sort order can be either ASC or DESC.
10384*/
10385#define SQLITE_SO_ASC       0  /* Sort in ascending order */
10386#define SQLITE_SO_DESC      1  /* Sort in ascending order */
10387
10388/*
10389** Column affinity types.
10390**
10391** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
10392** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
10393** the speed a little by numbering the values consecutively.
10394**
10395** But rather than start with 0 or 1, we begin with 'a'.  That way,
10396** when multiple affinity types are concatenated into a string and
10397** used as the P4 operand, they will be more readable.
10398**
10399** Note also that the numeric types are grouped together so that testing
10400** for a numeric type is a single comparison.
10401*/
10402#define SQLITE_AFF_TEXT     'a'
10403#define SQLITE_AFF_NONE     'b'
10404#define SQLITE_AFF_NUMERIC  'c'
10405#define SQLITE_AFF_INTEGER  'd'
10406#define SQLITE_AFF_REAL     'e'
10407
10408#define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
10409
10410/*
10411** The SQLITE_AFF_MASK values masks off the significant bits of an
10412** affinity value.
10413*/
10414#define SQLITE_AFF_MASK     0x67
10415
10416/*
10417** Additional bit values that can be ORed with an affinity without
10418** changing the affinity.
10419*/
10420#define SQLITE_JUMPIFNULL   0x08  /* jumps if either operand is NULL */
10421#define SQLITE_STOREP2      0x10  /* Store result in reg[P2] rather than jump */
10422#define SQLITE_NULLEQ       0x80  /* NULL=NULL */
10423
10424/*
10425** An object of this type is created for each virtual table present in
10426** the database schema.
10427**
10428** If the database schema is shared, then there is one instance of this
10429** structure for each database connection (sqlite3*) that uses the shared
10430** schema. This is because each database connection requires its own unique
10431** instance of the sqlite3_vtab* handle used to access the virtual table
10432** implementation. sqlite3_vtab* handles can not be shared between
10433** database connections, even when the rest of the in-memory database
10434** schema is shared, as the implementation often stores the database
10435** connection handle passed to it via the xConnect() or xCreate() method
10436** during initialization internally. This database connection handle may
10437** then be used by the virtual table implementation to access real tables
10438** within the database. So that they appear as part of the callers
10439** transaction, these accesses need to be made via the same database
10440** connection as that used to execute SQL operations on the virtual table.
10441**
10442** All VTable objects that correspond to a single table in a shared
10443** database schema are initially stored in a linked-list pointed to by
10444** the Table.pVTable member variable of the corresponding Table object.
10445** When an sqlite3_prepare() operation is required to access the virtual
10446** table, it searches the list for the VTable that corresponds to the
10447** database connection doing the preparing so as to use the correct
10448** sqlite3_vtab* handle in the compiled query.
10449**
10450** When an in-memory Table object is deleted (for example when the
10451** schema is being reloaded for some reason), the VTable objects are not
10452** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
10453** immediately. Instead, they are moved from the Table.pVTable list to
10454** another linked list headed by the sqlite3.pDisconnect member of the
10455** corresponding sqlite3 structure. They are then deleted/xDisconnected
10456** next time a statement is prepared using said sqlite3*. This is done
10457** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
10458** Refer to comments above function sqlite3VtabUnlockList() for an
10459** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
10460** list without holding the corresponding sqlite3.mutex mutex.
10461**
10462** The memory for objects of this type is always allocated by
10463** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
10464** the first argument.
10465*/
10466struct VTable {
10467  sqlite3 *db;              /* Database connection associated with this table */
10468  Module *pMod;             /* Pointer to module implementation */
10469  sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
10470  int nRef;                 /* Number of pointers to this structure */
10471  u8 bConstraint;           /* True if constraints are supported */
10472  int iSavepoint;           /* Depth of the SAVEPOINT stack */
10473  VTable *pNext;            /* Next in linked list (see above) */
10474};
10475
10476/*
10477** Each SQL table is represented in memory by an instance of the
10478** following structure.
10479**
10480** Table.zName is the name of the table.  The case of the original
10481** CREATE TABLE statement is stored, but case is not significant for
10482** comparisons.
10483**
10484** Table.nCol is the number of columns in this table.  Table.aCol is a
10485** pointer to an array of Column structures, one for each column.
10486**
10487** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
10488** the column that is that key.   Otherwise Table.iPKey is negative.  Note
10489** that the datatype of the PRIMARY KEY must be INTEGER for this field to
10490** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
10491** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
10492** is generated for each row of the table.  TF_HasPrimaryKey is set if
10493** the table has any PRIMARY KEY, INTEGER or otherwise.
10494**
10495** Table.tnum is the page number for the root BTree page of the table in the
10496** database file.  If Table.iDb is the index of the database table backend
10497** in sqlite.aDb[].  0 is for the main database and 1 is for the file that
10498** holds temporary tables and indices.  If TF_Ephemeral is set
10499** then the table is stored in a file that is automatically deleted
10500** when the VDBE cursor to the table is closed.  In this case Table.tnum
10501** refers VDBE cursor number that holds the table open, not to the root
10502** page number.  Transient tables are used to hold the results of a
10503** sub-query that appears instead of a real table name in the FROM clause
10504** of a SELECT statement.
10505*/
10506struct Table {
10507  char *zName;         /* Name of the table or view */
10508  Column *aCol;        /* Information about each column */
10509  Index *pIndex;       /* List of SQL indexes on this table. */
10510  Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
10511  FKey *pFKey;         /* Linked list of all foreign keys in this table */
10512  char *zColAff;       /* String defining the affinity of each column */
10513#ifndef SQLITE_OMIT_CHECK
10514  ExprList *pCheck;    /* All CHECK constraints */
10515#endif
10516  tRowcnt nRowEst;     /* Estimated rows in table - from sqlite_stat1 table */
10517  int tnum;            /* Root BTree node for this table (see note above) */
10518  i16 iPKey;           /* If not negative, use aCol[iPKey] as the primary key */
10519  i16 nCol;            /* Number of columns in this table */
10520  u16 nRef;            /* Number of pointers to this Table */
10521  u8 tabFlags;         /* Mask of TF_* values */
10522  u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
10523#ifndef SQLITE_OMIT_ALTERTABLE
10524  int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
10525#endif
10526#ifndef SQLITE_OMIT_VIRTUALTABLE
10527  int nModuleArg;      /* Number of arguments to the module */
10528  char **azModuleArg;  /* Text of all module args. [0] is module name */
10529  VTable *pVTable;     /* List of VTable objects. */
10530#endif
10531  Trigger *pTrigger;   /* List of triggers stored in pSchema */
10532  Schema *pSchema;     /* Schema that contains this table */
10533  Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
10534};
10535
10536/*
10537** Allowed values for Tabe.tabFlags.
10538*/
10539#define TF_Readonly        0x01    /* Read-only system table */
10540#define TF_Ephemeral       0x02    /* An ephemeral table */
10541#define TF_HasPrimaryKey   0x04    /* Table has a primary key */
10542#define TF_Autoincrement   0x08    /* Integer primary key is autoincrement */
10543#define TF_Virtual         0x10    /* Is a virtual table */
10544
10545
10546/*
10547** Test to see whether or not a table is a virtual table.  This is
10548** done as a macro so that it will be optimized out when virtual
10549** table support is omitted from the build.
10550*/
10551#ifndef SQLITE_OMIT_VIRTUALTABLE
10552#  define IsVirtual(X)      (((X)->tabFlags & TF_Virtual)!=0)
10553#  define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
10554#else
10555#  define IsVirtual(X)      0
10556#  define IsHiddenColumn(X) 0
10557#endif
10558
10559/*
10560** Each foreign key constraint is an instance of the following structure.
10561**
10562** A foreign key is associated with two tables.  The "from" table is
10563** the table that contains the REFERENCES clause that creates the foreign
10564** key.  The "to" table is the table that is named in the REFERENCES clause.
10565** Consider this example:
10566**
10567**     CREATE TABLE ex1(
10568**       a INTEGER PRIMARY KEY,
10569**       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
10570**     );
10571**
10572** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
10573**
10574** Each REFERENCES clause generates an instance of the following structure
10575** which is attached to the from-table.  The to-table need not exist when
10576** the from-table is created.  The existence of the to-table is not checked.
10577*/
10578struct FKey {
10579  Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */
10580  FKey *pNextFrom;  /* Next foreign key in pFrom */
10581  char *zTo;        /* Name of table that the key points to (aka: Parent) */
10582  FKey *pNextTo;    /* Next foreign key on table named zTo */
10583  FKey *pPrevTo;    /* Previous foreign key on table named zTo */
10584  int nCol;         /* Number of columns in this key */
10585  /* EV: R-30323-21917 */
10586  u8 isDeferred;    /* True if constraint checking is deferred till COMMIT */
10587  u8 aAction[2];          /* ON DELETE and ON UPDATE actions, respectively */
10588  Trigger *apTrigger[2];  /* Triggers for aAction[] actions */
10589  struct sColMap {  /* Mapping of columns in pFrom to columns in zTo */
10590    int iFrom;         /* Index of column in pFrom */
10591    char *zCol;        /* Name of column in zTo.  If 0 use PRIMARY KEY */
10592  } aCol[1];        /* One entry for each of nCol column s */
10593};
10594
10595/*
10596** SQLite supports many different ways to resolve a constraint
10597** error.  ROLLBACK processing means that a constraint violation
10598** causes the operation in process to fail and for the current transaction
10599** to be rolled back.  ABORT processing means the operation in process
10600** fails and any prior changes from that one operation are backed out,
10601** but the transaction is not rolled back.  FAIL processing means that
10602** the operation in progress stops and returns an error code.  But prior
10603** changes due to the same operation are not backed out and no rollback
10604** occurs.  IGNORE means that the particular row that caused the constraint
10605** error is not inserted or updated.  Processing continues and no error
10606** is returned.  REPLACE means that preexisting database rows that caused
10607** a UNIQUE constraint violation are removed so that the new insert or
10608** update can proceed.  Processing continues and no error is reported.
10609**
10610** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
10611** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
10612** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
10613** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
10614** referenced table row is propagated into the row that holds the
10615** foreign key.
10616**
10617** The following symbolic values are used to record which type
10618** of action to take.
10619*/
10620#define OE_None     0   /* There is no constraint to check */
10621#define OE_Rollback 1   /* Fail the operation and rollback the transaction */
10622#define OE_Abort    2   /* Back out changes but do no rollback transaction */
10623#define OE_Fail     3   /* Stop the operation but leave all prior changes */
10624#define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
10625#define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
10626
10627#define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
10628#define OE_SetNull  7   /* Set the foreign key value to NULL */
10629#define OE_SetDflt  8   /* Set the foreign key value to its default */
10630#define OE_Cascade  9   /* Cascade the changes */
10631
10632#define OE_Default  99  /* Do whatever the default action is */
10633
10634
10635/*
10636** An instance of the following structure is passed as the first
10637** argument to sqlite3VdbeKeyCompare and is used to control the
10638** comparison of the two index keys.
10639*/
10640struct KeyInfo {
10641  sqlite3 *db;        /* The database connection */
10642  u8 enc;             /* Text encoding - one of the SQLITE_UTF* values */
10643  u16 nField;         /* Number of entries in aColl[] */
10644  u8 *aSortOrder;     /* Sort order for each column.  May be NULL */
10645  CollSeq *aColl[1];  /* Collating sequence for each term of the key */
10646};
10647
10648/*
10649** An instance of the following structure holds information about a
10650** single index record that has already been parsed out into individual
10651** values.
10652**
10653** A record is an object that contains one or more fields of data.
10654** Records are used to store the content of a table row and to store
10655** the key of an index.  A blob encoding of a record is created by
10656** the OP_MakeRecord opcode of the VDBE and is disassembled by the
10657** OP_Column opcode.
10658**
10659** This structure holds a record that has already been disassembled
10660** into its constituent fields.
10661*/
10662struct UnpackedRecord {
10663  KeyInfo *pKeyInfo;  /* Collation and sort-order information */
10664  u16 nField;         /* Number of entries in apMem[] */
10665  u8 flags;           /* Boolean settings.  UNPACKED_... below */
10666  i64 rowid;          /* Used by UNPACKED_PREFIX_SEARCH */
10667  Mem *aMem;          /* Values */
10668};
10669
10670/*
10671** Allowed values of UnpackedRecord.flags
10672*/
10673#define UNPACKED_INCRKEY       0x01  /* Make this key an epsilon larger */
10674#define UNPACKED_PREFIX_MATCH  0x02  /* A prefix match is considered OK */
10675#define UNPACKED_PREFIX_SEARCH 0x04  /* Ignore final (rowid) field */
10676
10677/*
10678** Each SQL index is represented in memory by an
10679** instance of the following structure.
10680**
10681** The columns of the table that are to be indexed are described
10682** by the aiColumn[] field of this structure.  For example, suppose
10683** we have the following table and index:
10684**
10685**     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
10686**     CREATE INDEX Ex2 ON Ex1(c3,c1);
10687**
10688** In the Table structure describing Ex1, nCol==3 because there are
10689** three columns in the table.  In the Index structure describing
10690** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
10691** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the
10692** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
10693** The second column to be indexed (c1) has an index of 0 in
10694** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
10695**
10696** The Index.onError field determines whether or not the indexed columns
10697** must be unique and what to do if they are not.  When Index.onError=OE_None,
10698** it means this is not a unique index.  Otherwise it is a unique index
10699** and the value of Index.onError indicate the which conflict resolution
10700** algorithm to employ whenever an attempt is made to insert a non-unique
10701** element.
10702*/
10703struct Index {
10704  char *zName;             /* Name of this index */
10705  int *aiColumn;           /* Which columns are used by this index.  1st is 0 */
10706  tRowcnt *aiRowEst;       /* From ANALYZE: Est. rows selected by each column */
10707  Table *pTable;           /* The SQL table being indexed */
10708  char *zColAff;           /* String defining the affinity of each column */
10709  Index *pNext;            /* The next index associated with the same table */
10710  Schema *pSchema;         /* Schema containing this index */
10711  u8 *aSortOrder;          /* for each column: True==DESC, False==ASC */
10712  char **azColl;           /* Array of collation sequence names for index */
10713  int tnum;                /* DB Page containing root of this index */
10714  u16 nColumn;             /* Number of columns in table used by this index */
10715  u8 onError;              /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
10716  unsigned autoIndex:2;    /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */
10717  unsigned bUnordered:1;   /* Use this index for == or IN queries only */
10718#ifdef SQLITE_ENABLE_STAT3
10719  int nSample;             /* Number of elements in aSample[] */
10720  tRowcnt avgEq;           /* Average nEq value for key values not in aSample */
10721  IndexSample *aSample;    /* Samples of the left-most key */
10722#endif
10723};
10724
10725/*
10726** Each sample stored in the sqlite_stat3 table is represented in memory
10727** using a structure of this type.  See documentation at the top of the
10728** analyze.c source file for additional information.
10729*/
10730struct IndexSample {
10731  union {
10732    char *z;        /* Value if eType is SQLITE_TEXT or SQLITE_BLOB */
10733    double r;       /* Value if eType is SQLITE_FLOAT */
10734    i64 i;          /* Value if eType is SQLITE_INTEGER */
10735  } u;
10736  u8 eType;         /* SQLITE_NULL, SQLITE_INTEGER ... etc. */
10737  int nByte;        /* Size in byte of text or blob. */
10738  tRowcnt nEq;      /* Est. number of rows where the key equals this sample */
10739  tRowcnt nLt;      /* Est. number of rows where key is less than this sample */
10740  tRowcnt nDLt;     /* Est. number of distinct keys less than this sample */
10741};
10742
10743/*
10744** Each token coming out of the lexer is an instance of
10745** this structure.  Tokens are also used as part of an expression.
10746**
10747** Note if Token.z==0 then Token.dyn and Token.n are undefined and
10748** may contain random values.  Do not make any assumptions about Token.dyn
10749** and Token.n when Token.z==0.
10750*/
10751struct Token {
10752  const char *z;     /* Text of the token.  Not NULL-terminated! */
10753  unsigned int n;    /* Number of characters in this token */
10754};
10755
10756/*
10757** An instance of this structure contains information needed to generate
10758** code for a SELECT that contains aggregate functions.
10759**
10760** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
10761** pointer to this structure.  The Expr.iColumn field is the index in
10762** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
10763** code for that node.
10764**
10765** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
10766** original Select structure that describes the SELECT statement.  These
10767** fields do not need to be freed when deallocating the AggInfo structure.
10768*/
10769struct AggInfo {
10770  u8 directMode;          /* Direct rendering mode means take data directly
10771                          ** from source tables rather than from accumulators */
10772  u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
10773                          ** than the source table */
10774  int sortingIdx;         /* Cursor number of the sorting index */
10775  int sortingIdxPTab;     /* Cursor number of pseudo-table */
10776  int nSortingColumn;     /* Number of columns in the sorting index */
10777  ExprList *pGroupBy;     /* The group by clause */
10778  struct AggInfo_col {    /* For each column used in source tables */
10779    Table *pTab;             /* Source table */
10780    int iTable;              /* Cursor number of the source table */
10781    int iColumn;             /* Column number within the source table */
10782    int iSorterColumn;       /* Column number in the sorting index */
10783    int iMem;                /* Memory location that acts as accumulator */
10784    Expr *pExpr;             /* The original expression */
10785  } *aCol;
10786  int nColumn;            /* Number of used entries in aCol[] */
10787  int nAccumulator;       /* Number of columns that show through to the output.
10788                          ** Additional columns are used only as parameters to
10789                          ** aggregate functions */
10790  struct AggInfo_func {   /* For each aggregate function */
10791    Expr *pExpr;             /* Expression encoding the function */
10792    FuncDef *pFunc;          /* The aggregate function implementation */
10793    int iMem;                /* Memory location that acts as accumulator */
10794    int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
10795  } *aFunc;
10796  int nFunc;              /* Number of entries in aFunc[] */
10797};
10798
10799/*
10800** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
10801** Usually it is 16-bits.  But if SQLITE_MAX_VARIABLE_NUMBER is greater
10802** than 32767 we have to make it 32-bit.  16-bit is preferred because
10803** it uses less memory in the Expr object, which is a big memory user
10804** in systems with lots of prepared statements.  And few applications
10805** need more than about 10 or 20 variables.  But some extreme users want
10806** to have prepared statements with over 32767 variables, and for them
10807** the option is available (at compile-time).
10808*/
10809#if SQLITE_MAX_VARIABLE_NUMBER<=32767
10810typedef i16 ynVar;
10811#else
10812typedef int ynVar;
10813#endif
10814
10815/*
10816** Each node of an expression in the parse tree is an instance
10817** of this structure.
10818**
10819** Expr.op is the opcode. The integer parser token codes are reused
10820** as opcodes here. For example, the parser defines TK_GE to be an integer
10821** code representing the ">=" operator. This same integer code is reused
10822** to represent the greater-than-or-equal-to operator in the expression
10823** tree.
10824**
10825** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
10826** or TK_STRING), then Expr.token contains the text of the SQL literal. If
10827** the expression is a variable (TK_VARIABLE), then Expr.token contains the
10828** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
10829** then Expr.token contains the name of the function.
10830**
10831** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
10832** binary operator. Either or both may be NULL.
10833**
10834** Expr.x.pList is a list of arguments if the expression is an SQL function,
10835** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
10836** Expr.x.pSelect is used if the expression is a sub-select or an expression of
10837** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
10838** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
10839** valid.
10840**
10841** An expression of the form ID or ID.ID refers to a column in a table.
10842** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
10843** the integer cursor number of a VDBE cursor pointing to that table and
10844** Expr.iColumn is the column number for the specific column.  If the
10845** expression is used as a result in an aggregate SELECT, then the
10846** value is also stored in the Expr.iAgg column in the aggregate so that
10847** it can be accessed after all aggregates are computed.
10848**
10849** If the expression is an unbound variable marker (a question mark
10850** character '?' in the original SQL) then the Expr.iTable holds the index
10851** number for that variable.
10852**
10853** If the expression is a subquery then Expr.iColumn holds an integer
10854** register number containing the result of the subquery.  If the
10855** subquery gives a constant result, then iTable is -1.  If the subquery
10856** gives a different answer at different times during statement processing
10857** then iTable is the address of a subroutine that computes the subquery.
10858**
10859** If the Expr is of type OP_Column, and the table it is selecting from
10860** is a disk table or the "old.*" pseudo-table, then pTab points to the
10861** corresponding table definition.
10862**
10863** ALLOCATION NOTES:
10864**
10865** Expr objects can use a lot of memory space in database schema.  To
10866** help reduce memory requirements, sometimes an Expr object will be
10867** truncated.  And to reduce the number of memory allocations, sometimes
10868** two or more Expr objects will be stored in a single memory allocation,
10869** together with Expr.zToken strings.
10870**
10871** If the EP_Reduced and EP_TokenOnly flags are set when
10872** an Expr object is truncated.  When EP_Reduced is set, then all
10873** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
10874** are contained within the same memory allocation.  Note, however, that
10875** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
10876** allocated, regardless of whether or not EP_Reduced is set.
10877*/
10878struct Expr {
10879  u8 op;                 /* Operation performed by this node */
10880  char affinity;         /* The affinity of the column or 0 if not a column */
10881  u16 flags;             /* Various flags.  EP_* See below */
10882  union {
10883    char *zToken;          /* Token value. Zero terminated and dequoted */
10884    int iValue;            /* Non-negative integer value if EP_IntValue */
10885  } u;
10886
10887  /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
10888  ** space is allocated for the fields below this point. An attempt to
10889  ** access them will result in a segfault or malfunction.
10890  *********************************************************************/
10891
10892  Expr *pLeft;           /* Left subnode */
10893  Expr *pRight;          /* Right subnode */
10894  union {
10895    ExprList *pList;     /* Function arguments or in "<expr> IN (<expr-list)" */
10896    Select *pSelect;     /* Used for sub-selects and "<expr> IN (<select>)" */
10897  } x;
10898
10899  /* If the EP_Reduced flag is set in the Expr.flags mask, then no
10900  ** space is allocated for the fields below this point. An attempt to
10901  ** access them will result in a segfault or malfunction.
10902  *********************************************************************/
10903
10904#if SQLITE_MAX_EXPR_DEPTH>0
10905  int nHeight;           /* Height of the tree headed by this node */
10906#endif
10907  int iTable;            /* TK_COLUMN: cursor number of table holding column
10908                         ** TK_REGISTER: register number
10909                         ** TK_TRIGGER: 1 -> new, 0 -> old */
10910  ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.
10911                         ** TK_VARIABLE: variable number (always >= 1). */
10912  i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
10913  i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
10914  u8 flags2;             /* Second set of flags.  EP2_... */
10915  u8 op2;                /* TK_REGISTER: original value of Expr.op
10916                         ** TK_COLUMN: the value of p5 for OP_Column
10917                         ** TK_AGG_FUNCTION: nesting depth */
10918  AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
10919  Table *pTab;           /* Table for TK_COLUMN expressions. */
10920};
10921
10922/*
10923** The following are the meanings of bits in the Expr.flags field.
10924*/
10925#define EP_FromJoin   0x0001  /* Originated in ON or USING clause of a join */
10926#define EP_Agg        0x0002  /* Contains one or more aggregate functions */
10927#define EP_Resolved   0x0004  /* IDs have been resolved to COLUMNs */
10928#define EP_Error      0x0008  /* Expression contains one or more errors */
10929#define EP_Distinct   0x0010  /* Aggregate function with DISTINCT keyword */
10930#define EP_VarSelect  0x0020  /* pSelect is correlated, not constant */
10931#define EP_DblQuoted  0x0040  /* token.z was originally in "..." */
10932#define EP_InfixFunc  0x0080  /* True for an infix function: LIKE, GLOB, etc */
10933#define EP_Collate    0x0100  /* Tree contains a TK_COLLATE opeartor */
10934#define EP_FixedDest  0x0200  /* Result needed in a specific register */
10935#define EP_IntValue   0x0400  /* Integer value contained in u.iValue */
10936#define EP_xIsSelect  0x0800  /* x.pSelect is valid (otherwise x.pList is) */
10937#define EP_Hint       0x1000  /* Not used */
10938#define EP_Reduced    0x2000  /* Expr struct is EXPR_REDUCEDSIZE bytes only */
10939#define EP_TokenOnly  0x4000  /* Expr struct is EXPR_TOKENONLYSIZE bytes only */
10940#define EP_Static     0x8000  /* Held in memory not obtained from malloc() */
10941
10942/*
10943** The following are the meanings of bits in the Expr.flags2 field.
10944*/
10945#define EP2_MallocedToken  0x0001  /* Need to sqlite3DbFree() Expr.zToken */
10946#define EP2_Irreducible    0x0002  /* Cannot EXPRDUP_REDUCE this Expr */
10947
10948/*
10949** The pseudo-routine sqlite3ExprSetIrreducible sets the EP2_Irreducible
10950** flag on an expression structure.  This flag is used for VV&A only.  The
10951** routine is implemented as a macro that only works when in debugging mode,
10952** so as not to burden production code.
10953*/
10954#ifdef SQLITE_DEBUG
10955# define ExprSetIrreducible(X)  (X)->flags2 |= EP2_Irreducible
10956#else
10957# define ExprSetIrreducible(X)
10958#endif
10959
10960/*
10961** These macros can be used to test, set, or clear bits in the
10962** Expr.flags field.
10963*/
10964#define ExprHasProperty(E,P)     (((E)->flags&(P))==(P))
10965#define ExprHasAnyProperty(E,P)  (((E)->flags&(P))!=0)
10966#define ExprSetProperty(E,P)     (E)->flags|=(P)
10967#define ExprClearProperty(E,P)   (E)->flags&=~(P)
10968
10969/*
10970** Macros to determine the number of bytes required by a normal Expr
10971** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
10972** and an Expr struct with the EP_TokenOnly flag set.
10973*/
10974#define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
10975#define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */
10976#define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */
10977
10978/*
10979** Flags passed to the sqlite3ExprDup() function. See the header comment
10980** above sqlite3ExprDup() for details.
10981*/
10982#define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */
10983
10984/*
10985** A list of expressions.  Each expression may optionally have a
10986** name.  An expr/name combination can be used in several ways, such
10987** as the list of "expr AS ID" fields following a "SELECT" or in the
10988** list of "ID = expr" items in an UPDATE.  A list of expressions can
10989** also be used as the argument to a function, in which case the a.zName
10990** field is not used.
10991**
10992** By default the Expr.zSpan field holds a human-readable description of
10993** the expression that is used in the generation of error messages and
10994** column labels.  In this case, Expr.zSpan is typically the text of a
10995** column expression as it exists in a SELECT statement.  However, if
10996** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name
10997** of the result column in the form: DATABASE.TABLE.COLUMN.  This later
10998** form is used for name resolution with nested FROM clauses.
10999*/
11000struct ExprList {
11001  int nExpr;             /* Number of expressions on the list */
11002  int iECursor;          /* VDBE Cursor associated with this ExprList */
11003  struct ExprList_item { /* For each expression in the list */
11004    Expr *pExpr;            /* The list of expressions */
11005    char *zName;            /* Token associated with this expression */
11006    char *zSpan;            /* Original text of the expression */
11007    u8 sortOrder;           /* 1 for DESC or 0 for ASC */
11008    unsigned done :1;       /* A flag to indicate when processing is finished */
11009    unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
11010    u16 iOrderByCol;        /* For ORDER BY, column number in result set */
11011    u16 iAlias;             /* Index into Parse.aAlias[] for zName */
11012  } *a;                  /* Alloc a power of two greater or equal to nExpr */
11013};
11014
11015/*
11016** An instance of this structure is used by the parser to record both
11017** the parse tree for an expression and the span of input text for an
11018** expression.
11019*/
11020struct ExprSpan {
11021  Expr *pExpr;          /* The expression parse tree */
11022  const char *zStart;   /* First character of input text */
11023  const char *zEnd;     /* One character past the end of input text */
11024};
11025
11026/*
11027** An instance of this structure can hold a simple list of identifiers,
11028** such as the list "a,b,c" in the following statements:
11029**
11030**      INSERT INTO t(a,b,c) VALUES ...;
11031**      CREATE INDEX idx ON t(a,b,c);
11032**      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
11033**
11034** The IdList.a.idx field is used when the IdList represents the list of
11035** column names after a table name in an INSERT statement.  In the statement
11036**
11037**     INSERT INTO t(a,b,c) ...
11038**
11039** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
11040*/
11041struct IdList {
11042  struct IdList_item {
11043    char *zName;      /* Name of the identifier */
11044    int idx;          /* Index in some Table.aCol[] of a column named zName */
11045  } *a;
11046  int nId;         /* Number of identifiers on the list */
11047};
11048
11049/*
11050** The bitmask datatype defined below is used for various optimizations.
11051**
11052** Changing this from a 64-bit to a 32-bit type limits the number of
11053** tables in a join to 32 instead of 64.  But it also reduces the size
11054** of the library by 738 bytes on ix86.
11055*/
11056typedef u64 Bitmask;
11057
11058/*
11059** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
11060*/
11061#define BMS  ((int)(sizeof(Bitmask)*8))
11062
11063/*
11064** The following structure describes the FROM clause of a SELECT statement.
11065** Each table or subquery in the FROM clause is a separate element of
11066** the SrcList.a[] array.
11067**
11068** With the addition of multiple database support, the following structure
11069** can also be used to describe a particular table such as the table that
11070** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
11071** such a table must be a simple name: ID.  But in SQLite, the table can
11072** now be identified by a database name, a dot, then the table name: ID.ID.
11073**
11074** The jointype starts out showing the join type between the current table
11075** and the next table on the list.  The parser builds the list this way.
11076** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
11077** jointype expresses the join between the table and the previous table.
11078**
11079** In the colUsed field, the high-order bit (bit 63) is set if the table
11080** contains more than 63 columns and the 64-th or later column is used.
11081*/
11082struct SrcList {
11083  i16 nSrc;        /* Number of tables or subqueries in the FROM clause */
11084  i16 nAlloc;      /* Number of entries allocated in a[] below */
11085  struct SrcList_item {
11086    Schema *pSchema;  /* Schema to which this item is fixed */
11087    char *zDatabase;  /* Name of database holding this table */
11088    char *zName;      /* Name of the table */
11089    char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
11090    Table *pTab;      /* An SQL table corresponding to zName */
11091    Select *pSelect;  /* A SELECT statement used in place of a table name */
11092    int addrFillSub;  /* Address of subroutine to manifest a subquery */
11093    int regReturn;    /* Register holding return address of addrFillSub */
11094    u8 jointype;      /* Type of join between this able and the previous */
11095    unsigned notIndexed :1;    /* True if there is a NOT INDEXED clause */
11096    unsigned isCorrelated :1;  /* True if sub-query is correlated */
11097    unsigned viaCoroutine :1;  /* Implemented as a co-routine */
11098#ifndef SQLITE_OMIT_EXPLAIN
11099    u8 iSelectId;     /* If pSelect!=0, the id of the sub-select in EQP */
11100#endif
11101    int iCursor;      /* The VDBE cursor number used to access this table */
11102    Expr *pOn;        /* The ON clause of a join */
11103    IdList *pUsing;   /* The USING clause of a join */
11104    Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
11105    char *zIndex;     /* Identifier from "INDEXED BY <zIndex>" clause */
11106    Index *pIndex;    /* Index structure corresponding to zIndex, if any */
11107  } a[1];             /* One entry for each identifier on the list */
11108};
11109
11110/*
11111** Permitted values of the SrcList.a.jointype field
11112*/
11113#define JT_INNER     0x0001    /* Any kind of inner or cross join */
11114#define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
11115#define JT_NATURAL   0x0004    /* True for a "natural" join */
11116#define JT_LEFT      0x0008    /* Left outer join */
11117#define JT_RIGHT     0x0010    /* Right outer join */
11118#define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
11119#define JT_ERROR     0x0040    /* unknown or unsupported join type */
11120
11121
11122/*
11123** A WherePlan object holds information that describes a lookup
11124** strategy.
11125**
11126** This object is intended to be opaque outside of the where.c module.
11127** It is included here only so that that compiler will know how big it
11128** is.  None of the fields in this object should be used outside of
11129** the where.c module.
11130**
11131** Within the union, pIdx is only used when wsFlags&WHERE_INDEXED is true.
11132** pTerm is only used when wsFlags&WHERE_MULTI_OR is true.  And pVtabIdx
11133** is only used when wsFlags&WHERE_VIRTUALTABLE is true.  It is never the
11134** case that more than one of these conditions is true.
11135*/
11136struct WherePlan {
11137  u32 wsFlags;                   /* WHERE_* flags that describe the strategy */
11138  u16 nEq;                       /* Number of == constraints */
11139  u16 nOBSat;                    /* Number of ORDER BY terms satisfied */
11140  double nRow;                   /* Estimated number of rows (for EQP) */
11141  union {
11142    Index *pIdx;                   /* Index when WHERE_INDEXED is true */
11143    struct WhereTerm *pTerm;       /* WHERE clause term for OR-search */
11144    sqlite3_index_info *pVtabIdx;  /* Virtual table index to use */
11145  } u;
11146};
11147
11148/*
11149** For each nested loop in a WHERE clause implementation, the WhereInfo
11150** structure contains a single instance of this structure.  This structure
11151** is intended to be private to the where.c module and should not be
11152** access or modified by other modules.
11153**
11154** The pIdxInfo field is used to help pick the best index on a
11155** virtual table.  The pIdxInfo pointer contains indexing
11156** information for the i-th table in the FROM clause before reordering.
11157** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
11158** All other information in the i-th WhereLevel object for the i-th table
11159** after FROM clause ordering.
11160*/
11161struct WhereLevel {
11162  WherePlan plan;       /* query plan for this element of the FROM clause */
11163  int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
11164  int iTabCur;          /* The VDBE cursor used to access the table */
11165  int iIdxCur;          /* The VDBE cursor used to access pIdx */
11166  int addrBrk;          /* Jump here to break out of the loop */
11167  int addrNxt;          /* Jump here to start the next IN combination */
11168  int addrCont;         /* Jump here to continue with the next loop cycle */
11169  int addrFirst;        /* First instruction of interior of the loop */
11170  u8 iFrom;             /* Which entry in the FROM clause */
11171  u8 op, p5;            /* Opcode and P5 of the opcode that ends the loop */
11172  int p1, p2;           /* Operands of the opcode used to ends the loop */
11173  union {               /* Information that depends on plan.wsFlags */
11174    struct {
11175      int nIn;              /* Number of entries in aInLoop[] */
11176      struct InLoop {
11177        int iCur;              /* The VDBE cursor used by this IN operator */
11178        int addrInTop;         /* Top of the IN loop */
11179        u8 eEndLoopOp;         /* IN Loop terminator. OP_Next or OP_Prev */
11180      } *aInLoop;           /* Information about each nested IN operator */
11181    } in;                 /* Used when plan.wsFlags&WHERE_IN_ABLE */
11182    Index *pCovidx;       /* Possible covering index for WHERE_MULTI_OR */
11183  } u;
11184  double rOptCost;      /* "Optimal" cost for this level */
11185
11186  /* The following field is really not part of the current level.  But
11187  ** we need a place to cache virtual table index information for each
11188  ** virtual table in the FROM clause and the WhereLevel structure is
11189  ** a convenient place since there is one WhereLevel for each FROM clause
11190  ** element.
11191  */
11192  sqlite3_index_info *pIdxInfo;  /* Index info for n-th source table */
11193};
11194
11195/*
11196** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
11197** and the WhereInfo.wctrlFlags member.
11198*/
11199#define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
11200#define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
11201#define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
11202#define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
11203#define WHERE_DUPLICATES_OK    0x0008 /* Ok to return a row more than once */
11204#define WHERE_OMIT_OPEN_CLOSE  0x0010 /* Table cursors are already open */
11205#define WHERE_FORCE_TABLE      0x0020 /* Do not use an index-only search */
11206#define WHERE_ONETABLE_ONLY    0x0040 /* Only code the 1st table in pTabList */
11207#define WHERE_AND_ONLY         0x0080 /* Don't use indices for OR terms */
11208
11209/*
11210** The WHERE clause processing routine has two halves.  The
11211** first part does the start of the WHERE loop and the second
11212** half does the tail of the WHERE loop.  An instance of
11213** this structure is returned by the first half and passed
11214** into the second half to give some continuity.
11215*/
11216struct WhereInfo {
11217  Parse *pParse;            /* Parsing and code generating context */
11218  SrcList *pTabList;        /* List of tables in the join */
11219  u16 nOBSat;               /* Number of ORDER BY terms satisfied by indices */
11220  u16 wctrlFlags;           /* Flags originally passed to sqlite3WhereBegin() */
11221  u8 okOnePass;             /* Ok to use one-pass algorithm for UPDATE/DELETE */
11222  u8 untestedTerms;         /* Not all WHERE terms resolved by outer loop */
11223  u8 eDistinct;             /* One of the WHERE_DISTINCT_* values below */
11224  int iTop;                 /* The very beginning of the WHERE loop */
11225  int iContinue;            /* Jump here to continue with next record */
11226  int iBreak;               /* Jump here to break out of the loop */
11227  int nLevel;               /* Number of nested loop */
11228  struct WhereClause *pWC;  /* Decomposition of the WHERE clause */
11229  double savedNQueryLoop;   /* pParse->nQueryLoop outside the WHERE loop */
11230  double nRowOut;           /* Estimated number of output rows */
11231  WhereLevel a[1];          /* Information about each nest loop in WHERE */
11232};
11233
11234/* Allowed values for WhereInfo.eDistinct and DistinctCtx.eTnctType */
11235#define WHERE_DISTINCT_NOOP      0  /* DISTINCT keyword not used */
11236#define WHERE_DISTINCT_UNIQUE    1  /* No duplicates */
11237#define WHERE_DISTINCT_ORDERED   2  /* All duplicates are adjacent */
11238#define WHERE_DISTINCT_UNORDERED 3  /* Duplicates are scattered */
11239
11240/*
11241** A NameContext defines a context in which to resolve table and column
11242** names.  The context consists of a list of tables (the pSrcList) field and
11243** a list of named expression (pEList).  The named expression list may
11244** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
11245** to the table being operated on by INSERT, UPDATE, or DELETE.  The
11246** pEList corresponds to the result set of a SELECT and is NULL for
11247** other statements.
11248**
11249** NameContexts can be nested.  When resolving names, the inner-most
11250** context is searched first.  If no match is found, the next outer
11251** context is checked.  If there is still no match, the next context
11252** is checked.  This process continues until either a match is found
11253** or all contexts are check.  When a match is found, the nRef member of
11254** the context containing the match is incremented.
11255**
11256** Each subquery gets a new NameContext.  The pNext field points to the
11257** NameContext in the parent query.  Thus the process of scanning the
11258** NameContext list corresponds to searching through successively outer
11259** subqueries looking for a match.
11260*/
11261struct NameContext {
11262  Parse *pParse;       /* The parser */
11263  SrcList *pSrcList;   /* One or more tables used to resolve names */
11264  ExprList *pEList;    /* Optional list of named expressions */
11265  AggInfo *pAggInfo;   /* Information about aggregates at this level */
11266  NameContext *pNext;  /* Next outer name context.  NULL for outermost */
11267  int nRef;            /* Number of names resolved by this context */
11268  int nErr;            /* Number of errors encountered while resolving names */
11269  u8 ncFlags;          /* Zero or more NC_* flags defined below */
11270};
11271
11272/*
11273** Allowed values for the NameContext, ncFlags field.
11274*/
11275#define NC_AllowAgg  0x01    /* Aggregate functions are allowed here */
11276#define NC_HasAgg    0x02    /* One or more aggregate functions seen */
11277#define NC_IsCheck   0x04    /* True if resolving names in a CHECK constraint */
11278#define NC_InAggFunc 0x08    /* True if analyzing arguments to an agg func */
11279#define NC_AsMaybe   0x10    /* Resolve to AS terms of the result set only
11280                             ** if no other resolution is available */
11281
11282/*
11283** An instance of the following structure contains all information
11284** needed to generate code for a single SELECT statement.
11285**
11286** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
11287** If there is a LIMIT clause, the parser sets nLimit to the value of the
11288** limit and nOffset to the value of the offset (or 0 if there is not
11289** offset).  But later on, nLimit and nOffset become the memory locations
11290** in the VDBE that record the limit and offset counters.
11291**
11292** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
11293** These addresses must be stored so that we can go back and fill in
11294** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
11295** the number of columns in P2 can be computed at the same time
11296** as the OP_OpenEphm instruction is coded because not
11297** enough information about the compound query is known at that point.
11298** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
11299** for the result set.  The KeyInfo for addrOpenEphm[2] contains collating
11300** sequences for the ORDER BY clause.
11301*/
11302struct Select {
11303  ExprList *pEList;      /* The fields of the result */
11304  u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
11305  u16 selFlags;          /* Various SF_* values */
11306  int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
11307  int addrOpenEphm[3];   /* OP_OpenEphem opcodes related to this select */
11308  double nSelectRow;     /* Estimated number of result rows */
11309  SrcList *pSrc;         /* The FROM clause */
11310  Expr *pWhere;          /* The WHERE clause */
11311  ExprList *pGroupBy;    /* The GROUP BY clause */
11312  Expr *pHaving;         /* The HAVING clause */
11313  ExprList *pOrderBy;    /* The ORDER BY clause */
11314  Select *pPrior;        /* Prior select in a compound select statement */
11315  Select *pNext;         /* Next select to the left in a compound */
11316  Select *pRightmost;    /* Right-most select in a compound select statement */
11317  Expr *pLimit;          /* LIMIT expression. NULL means not used. */
11318  Expr *pOffset;         /* OFFSET expression. NULL means not used. */
11319};
11320
11321/*
11322** Allowed values for Select.selFlags.  The "SF" prefix stands for
11323** "Select Flag".
11324*/
11325#define SF_Distinct        0x0001  /* Output should be DISTINCT */
11326#define SF_Resolved        0x0002  /* Identifiers have been resolved */
11327#define SF_Aggregate       0x0004  /* Contains aggregate functions */
11328#define SF_UsesEphemeral   0x0008  /* Uses the OpenEphemeral opcode */
11329#define SF_Expanded        0x0010  /* sqlite3SelectExpand() called on this */
11330#define SF_HasTypeInfo     0x0020  /* FROM subqueries have Table metadata */
11331#define SF_UseSorter       0x0040  /* Sort using a sorter */
11332#define SF_Values          0x0080  /* Synthesized from VALUES clause */
11333#define SF_Materialize     0x0100  /* Force materialization of views */
11334#define SF_NestedFrom      0x0200  /* Part of a parenthesized FROM clause */
11335
11336
11337/*
11338** The results of a select can be distributed in several ways.  The
11339** "SRT" prefix means "SELECT Result Type".
11340*/
11341#define SRT_Union        1  /* Store result as keys in an index */
11342#define SRT_Except       2  /* Remove result from a UNION index */
11343#define SRT_Exists       3  /* Store 1 if the result is not empty */
11344#define SRT_Discard      4  /* Do not save the results anywhere */
11345
11346/* The ORDER BY clause is ignored for all of the above */
11347#define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
11348
11349#define SRT_Output       5  /* Output each row of result */
11350#define SRT_Mem          6  /* Store result in a memory cell */
11351#define SRT_Set          7  /* Store results as keys in an index */
11352#define SRT_Table        8  /* Store result as data with an automatic rowid */
11353#define SRT_EphemTab     9  /* Create transient tab and store like SRT_Table */
11354#define SRT_Coroutine   10  /* Generate a single row of result */
11355
11356/*
11357** An instance of this object describes where to put of the results of
11358** a SELECT statement.
11359*/
11360struct SelectDest {
11361  u8 eDest;         /* How to dispose of the results.  On of SRT_* above. */
11362  char affSdst;     /* Affinity used when eDest==SRT_Set */
11363  int iSDParm;      /* A parameter used by the eDest disposal method */
11364  int iSdst;        /* Base register where results are written */
11365  int nSdst;        /* Number of registers allocated */
11366};
11367
11368/*
11369** During code generation of statements that do inserts into AUTOINCREMENT
11370** tables, the following information is attached to the Table.u.autoInc.p
11371** pointer of each autoincrement table to record some side information that
11372** the code generator needs.  We have to keep per-table autoincrement
11373** information in case inserts are down within triggers.  Triggers do not
11374** normally coordinate their activities, but we do need to coordinate the
11375** loading and saving of autoincrement information.
11376*/
11377struct AutoincInfo {
11378  AutoincInfo *pNext;   /* Next info block in a list of them all */
11379  Table *pTab;          /* Table this info block refers to */
11380  int iDb;              /* Index in sqlite3.aDb[] of database holding pTab */
11381  int regCtr;           /* Memory register holding the rowid counter */
11382};
11383
11384/*
11385** Size of the column cache
11386*/
11387#ifndef SQLITE_N_COLCACHE
11388# define SQLITE_N_COLCACHE 10
11389#endif
11390
11391/*
11392** At least one instance of the following structure is created for each
11393** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
11394** statement. All such objects are stored in the linked list headed at
11395** Parse.pTriggerPrg and deleted once statement compilation has been
11396** completed.
11397**
11398** A Vdbe sub-program that implements the body and WHEN clause of trigger
11399** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
11400** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
11401** The Parse.pTriggerPrg list never contains two entries with the same
11402** values for both pTrigger and orconf.
11403**
11404** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
11405** accessed (or set to 0 for triggers fired as a result of INSERT
11406** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
11407** a mask of new.* columns used by the program.
11408*/
11409struct TriggerPrg {
11410  Trigger *pTrigger;      /* Trigger this program was coded from */
11411  TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
11412  SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
11413  int orconf;             /* Default ON CONFLICT policy */
11414  u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */
11415};
11416
11417/*
11418** The yDbMask datatype for the bitmask of all attached databases.
11419*/
11420#if SQLITE_MAX_ATTACHED>30
11421  typedef sqlite3_uint64 yDbMask;
11422#else
11423  typedef unsigned int yDbMask;
11424#endif
11425
11426/*
11427** An SQL parser context.  A copy of this structure is passed through
11428** the parser and down into all the parser action routine in order to
11429** carry around information that is global to the entire parse.
11430**
11431** The structure is divided into two parts.  When the parser and code
11432** generate call themselves recursively, the first part of the structure
11433** is constant but the second part is reset at the beginning and end of
11434** each recursion.
11435**
11436** The nTableLock and aTableLock variables are only used if the shared-cache
11437** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
11438** used to store the set of table-locks required by the statement being
11439** compiled. Function sqlite3TableLock() is used to add entries to the
11440** list.
11441*/
11442struct Parse {
11443  sqlite3 *db;         /* The main database structure */
11444  char *zErrMsg;       /* An error message */
11445  Vdbe *pVdbe;         /* An engine for executing database bytecode */
11446  int rc;              /* Return code from execution */
11447  u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
11448  u8 checkSchema;      /* Causes schema cookie check after an error */
11449  u8 nested;           /* Number of nested calls to the parser/code generator */
11450  u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
11451  u8 nTempInUse;       /* Number of aTempReg[] currently checked out */
11452  u8 nColCache;        /* Number of entries in aColCache[] */
11453  u8 iColCache;        /* Next entry in aColCache[] to replace */
11454  u8 isMultiWrite;     /* True if statement may modify/insert multiple rows */
11455  u8 mayAbort;         /* True if statement may throw an ABORT exception */
11456  int aTempReg[8];     /* Holding area for temporary registers */
11457  int nRangeReg;       /* Size of the temporary register block */
11458  int iRangeReg;       /* First register in temporary register block */
11459  int nErr;            /* Number of errors seen */
11460  int nTab;            /* Number of previously allocated VDBE cursors */
11461  int nMem;            /* Number of memory cells used so far */
11462  int nSet;            /* Number of sets used so far */
11463  int nOnce;           /* Number of OP_Once instructions so far */
11464  int ckBase;          /* Base register of data during check constraints */
11465  int iCacheLevel;     /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
11466  int iCacheCnt;       /* Counter used to generate aColCache[].lru values */
11467  struct yColCache {
11468    int iTable;           /* Table cursor number */
11469    int iColumn;          /* Table column number */
11470    u8 tempReg;           /* iReg is a temp register that needs to be freed */
11471    int iLevel;           /* Nesting level */
11472    int iReg;             /* Reg with value of this column. 0 means none. */
11473    int lru;              /* Least recently used entry has the smallest value */
11474  } aColCache[SQLITE_N_COLCACHE];  /* One for each column cache entry */
11475  yDbMask writeMask;   /* Start a write transaction on these databases */
11476  yDbMask cookieMask;  /* Bitmask of schema verified databases */
11477  int cookieGoto;      /* Address of OP_Goto to cookie verifier subroutine */
11478  int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
11479  int regRowid;        /* Register holding rowid of CREATE TABLE entry */
11480  int regRoot;         /* Register holding root page number for new objects */
11481  int nMaxArg;         /* Max args passed to user function by sub-program */
11482  Token constraintName;/* Name of the constraint currently being parsed */
11483#ifndef SQLITE_OMIT_SHARED_CACHE
11484  int nTableLock;        /* Number of locks in aTableLock */
11485  TableLock *aTableLock; /* Required table locks for shared-cache mode */
11486#endif
11487  AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
11488
11489  /* Information used while coding trigger programs. */
11490  Parse *pToplevel;    /* Parse structure for main program (or NULL) */
11491  Table *pTriggerTab;  /* Table triggers are being coded for */
11492  double nQueryLoop;   /* Estimated number of iterations of a query */
11493  u32 oldmask;         /* Mask of old.* columns referenced */
11494  u32 newmask;         /* Mask of new.* columns referenced */
11495  u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
11496  u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
11497  u8 disableTriggers;  /* True to disable triggers */
11498
11499  /* Above is constant between recursions.  Below is reset before and after
11500  ** each recursion */
11501
11502  int nVar;                 /* Number of '?' variables seen in the SQL so far */
11503  int nzVar;                /* Number of available slots in azVar[] */
11504  u8 explain;               /* True if the EXPLAIN flag is found on the query */
11505#ifndef SQLITE_OMIT_VIRTUALTABLE
11506  u8 declareVtab;           /* True if inside sqlite3_declare_vtab() */
11507  int nVtabLock;            /* Number of virtual tables to lock */
11508#endif
11509  int nAlias;               /* Number of aliased result set columns */
11510  int nHeight;              /* Expression tree height of current sub-select */
11511#ifndef SQLITE_OMIT_EXPLAIN
11512  int iSelectId;            /* ID of current select for EXPLAIN output */
11513  int iNextSelectId;        /* Next available select ID for EXPLAIN output */
11514#endif
11515  char **azVar;             /* Pointers to names of parameters */
11516  Vdbe *pReprepare;         /* VM being reprepared (sqlite3Reprepare()) */
11517  int *aAlias;              /* Register used to hold aliased result */
11518  const char *zTail;        /* All SQL text past the last semicolon parsed */
11519  Table *pNewTable;         /* A table being constructed by CREATE TABLE */
11520  Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
11521  const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
11522  Token sNameToken;         /* Token with unqualified schema object name */
11523  Token sLastToken;         /* The last token parsed */
11524#ifndef SQLITE_OMIT_VIRTUALTABLE
11525  Token sArg;               /* Complete text of a module argument */
11526  Table **apVtabLock;       /* Pointer to virtual tables needing locking */
11527#endif
11528  Table *pZombieTab;        /* List of Table objects to delete after code gen */
11529  TriggerPrg *pTriggerPrg;  /* Linked list of coded triggers */
11530};
11531
11532/*
11533** Return true if currently inside an sqlite3_declare_vtab() call.
11534*/
11535#ifdef SQLITE_OMIT_VIRTUALTABLE
11536  #define IN_DECLARE_VTAB 0
11537#else
11538  #define IN_DECLARE_VTAB (pParse->declareVtab)
11539#endif
11540
11541/*
11542** An instance of the following structure can be declared on a stack and used
11543** to save the Parse.zAuthContext value so that it can be restored later.
11544*/
11545struct AuthContext {
11546  const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
11547  Parse *pParse;              /* The Parse structure */
11548};
11549
11550/*
11551** Bitfield flags for P5 value in various opcodes.
11552*/
11553#define OPFLAG_NCHANGE       0x01    /* Set to update db->nChange */
11554#define OPFLAG_LASTROWID     0x02    /* Set to update db->lastRowid */
11555#define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
11556#define OPFLAG_APPEND        0x08    /* This is likely to be an append */
11557#define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
11558#define OPFLAG_CLEARCACHE    0x20    /* Clear pseudo-table cache in OP_Column */
11559#define OPFLAG_LENGTHARG     0x40    /* OP_Column only used for length() */
11560#define OPFLAG_TYPEOFARG     0x80    /* OP_Column only used for typeof() */
11561#define OPFLAG_BULKCSR       0x01    /* OP_Open** used to open bulk cursor */
11562#define OPFLAG_P2ISREG       0x02    /* P2 to OP_Open** is a register number */
11563#define OPFLAG_PERMUTE       0x01    /* OP_Compare: use the permutation */
11564
11565/*
11566 * Each trigger present in the database schema is stored as an instance of
11567 * struct Trigger.
11568 *
11569 * Pointers to instances of struct Trigger are stored in two ways.
11570 * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
11571 *    database). This allows Trigger structures to be retrieved by name.
11572 * 2. All triggers associated with a single table form a linked list, using the
11573 *    pNext member of struct Trigger. A pointer to the first element of the
11574 *    linked list is stored as the "pTrigger" member of the associated
11575 *    struct Table.
11576 *
11577 * The "step_list" member points to the first element of a linked list
11578 * containing the SQL statements specified as the trigger program.
11579 */
11580struct Trigger {
11581  char *zName;            /* The name of the trigger                        */
11582  char *table;            /* The table or view to which the trigger applies */
11583  u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
11584  u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
11585  Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
11586  IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
11587                             the <column-list> is stored here */
11588  Schema *pSchema;        /* Schema containing the trigger */
11589  Schema *pTabSchema;     /* Schema containing the table */
11590  TriggerStep *step_list; /* Link list of trigger program steps             */
11591  Trigger *pNext;         /* Next trigger associated with the table */
11592};
11593
11594/*
11595** A trigger is either a BEFORE or an AFTER trigger.  The following constants
11596** determine which.
11597**
11598** If there are multiple triggers, you might of some BEFORE and some AFTER.
11599** In that cases, the constants below can be ORed together.
11600*/
11601#define TRIGGER_BEFORE  1
11602#define TRIGGER_AFTER   2
11603
11604/*
11605 * An instance of struct TriggerStep is used to store a single SQL statement
11606 * that is a part of a trigger-program.
11607 *
11608 * Instances of struct TriggerStep are stored in a singly linked list (linked
11609 * using the "pNext" member) referenced by the "step_list" member of the
11610 * associated struct Trigger instance. The first element of the linked list is
11611 * the first step of the trigger-program.
11612 *
11613 * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
11614 * "SELECT" statement. The meanings of the other members is determined by the
11615 * value of "op" as follows:
11616 *
11617 * (op == TK_INSERT)
11618 * orconf    -> stores the ON CONFLICT algorithm
11619 * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
11620 *              this stores a pointer to the SELECT statement. Otherwise NULL.
11621 * target    -> A token holding the quoted name of the table to insert into.
11622 * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
11623 *              this stores values to be inserted. Otherwise NULL.
11624 * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ...
11625 *              statement, then this stores the column-names to be
11626 *              inserted into.
11627 *
11628 * (op == TK_DELETE)
11629 * target    -> A token holding the quoted name of the table to delete from.
11630 * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
11631 *              Otherwise NULL.
11632 *
11633 * (op == TK_UPDATE)
11634 * target    -> A token holding the quoted name of the table to update rows of.
11635 * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
11636 *              Otherwise NULL.
11637 * pExprList -> A list of the columns to update and the expressions to update
11638 *              them to. See sqlite3Update() documentation of "pChanges"
11639 *              argument.
11640 *
11641 */
11642struct TriggerStep {
11643  u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
11644  u8 orconf;           /* OE_Rollback etc. */
11645  Trigger *pTrig;      /* The trigger that this step is a part of */
11646  Select *pSelect;     /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
11647  Token target;        /* Target table for DELETE, UPDATE, INSERT */
11648  Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
11649  ExprList *pExprList; /* SET clause for UPDATE.  VALUES clause for INSERT */
11650  IdList *pIdList;     /* Column names for INSERT */
11651  TriggerStep *pNext;  /* Next in the link-list */
11652  TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
11653};
11654
11655/*
11656** The following structure contains information used by the sqliteFix...
11657** routines as they walk the parse tree to make database references
11658** explicit.
11659*/
11660typedef struct DbFixer DbFixer;
11661struct DbFixer {
11662  Parse *pParse;      /* The parsing context.  Error messages written here */
11663  Schema *pSchema;    /* Fix items to this schema */
11664  const char *zDb;    /* Make sure all objects are contained in this database */
11665  const char *zType;  /* Type of the container - used for error messages */
11666  const Token *pName; /* Name of the container - used for error messages */
11667};
11668
11669/*
11670** An objected used to accumulate the text of a string where we
11671** do not necessarily know how big the string will be in the end.
11672*/
11673struct StrAccum {
11674  sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
11675  char *zBase;         /* A base allocation.  Not from malloc. */
11676  char *zText;         /* The string collected so far */
11677  int  nChar;          /* Length of the string so far */
11678  int  nAlloc;         /* Amount of space allocated in zText */
11679  int  mxAlloc;        /* Maximum allowed string length */
11680  u8   mallocFailed;   /* Becomes true if any memory allocation fails */
11681  u8   useMalloc;      /* 0: none,  1: sqlite3DbMalloc,  2: sqlite3_malloc */
11682  u8   tooBig;         /* Becomes true if string size exceeds limits */
11683};
11684
11685/*
11686** A pointer to this structure is used to communicate information
11687** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
11688*/
11689typedef struct {
11690  sqlite3 *db;        /* The database being initialized */
11691  char **pzErrMsg;    /* Error message stored here */
11692  int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
11693  int rc;             /* Result code stored here */
11694} InitData;
11695
11696/*
11697** Structure containing global configuration data for the SQLite library.
11698**
11699** This structure also contains some state information.
11700*/
11701struct Sqlite3Config {
11702  int bMemstat;                     /* True to enable memory status */
11703  int bCoreMutex;                   /* True to enable core mutexing */
11704  int bFullMutex;                   /* True to enable full mutexing */
11705  int bOpenUri;                     /* True to interpret filenames as URIs */
11706  int bUseCis;                      /* Use covering indices for full-scans */
11707  int mxStrlen;                     /* Maximum string length */
11708  int szLookaside;                  /* Default lookaside buffer size */
11709  int nLookaside;                   /* Default lookaside buffer count */
11710  sqlite3_mem_methods m;            /* Low-level memory allocation interface */
11711  sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
11712  sqlite3_pcache_methods2 pcache2;  /* Low-level page-cache interface */
11713  void *pHeap;                      /* Heap storage space */
11714  int nHeap;                        /* Size of pHeap[] */
11715  int mnReq, mxReq;                 /* Min and max heap requests sizes */
11716  sqlite3_int64 szMmap;             /* mmap() space per open file */
11717  sqlite3_int64 mxMmap;             /* Maximum value for szMmap */
11718  void *pScratch;                   /* Scratch memory */
11719  int szScratch;                    /* Size of each scratch buffer */
11720  int nScratch;                     /* Number of scratch buffers */
11721  void *pPage;                      /* Page cache memory */
11722  int szPage;                       /* Size of each page in pPage[] */
11723  int nPage;                        /* Number of pages in pPage[] */
11724  int mxParserStack;                /* maximum depth of the parser stack */
11725  int sharedCacheEnabled;           /* true if shared-cache mode enabled */
11726  /* The above might be initialized to non-zero.  The following need to always
11727  ** initially be zero, however. */
11728  int isInit;                       /* True after initialization has finished */
11729  int inProgress;                   /* True while initialization in progress */
11730  int isMutexInit;                  /* True after mutexes are initialized */
11731  int isMallocInit;                 /* True after malloc is initialized */
11732  int isPCacheInit;                 /* True after malloc is initialized */
11733  sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
11734  int nRefInitMutex;                /* Number of users of pInitMutex */
11735  void (*xLog)(void*,int,const char*); /* Function for logging */
11736  void *pLogArg;                       /* First argument to xLog() */
11737  int bLocaltimeFault;              /* True to fail localtime() calls */
11738#ifdef SQLITE_ENABLE_SQLLOG
11739  void(*xSqllog)(void*,sqlite3*,const char*, int);
11740  void *pSqllogArg;
11741#endif
11742};
11743
11744/*
11745** Context pointer passed down through the tree-walk.
11746*/
11747struct Walker {
11748  int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
11749  int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
11750  Parse *pParse;                            /* Parser context.  */
11751  int walkerDepth;                          /* Number of subqueries */
11752  u8 bSelectDepthFirst;                     /* Do subqueries first */
11753  union {                                   /* Extra data for callback */
11754    NameContext *pNC;                          /* Naming context */
11755    int i;                                     /* Integer value */
11756    SrcList *pSrcList;                         /* FROM clause */
11757    struct SrcCount *pSrcCount;                /* Counting column references */
11758  } u;
11759};
11760
11761/* Forward declarations */
11762SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
11763SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
11764SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
11765SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
11766SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
11767
11768/*
11769** Return code from the parse-tree walking primitives and their
11770** callbacks.
11771*/
11772#define WRC_Continue    0   /* Continue down into children */
11773#define WRC_Prune       1   /* Omit children but continue walking siblings */
11774#define WRC_Abort       2   /* Abandon the tree walk */
11775
11776/*
11777** Assuming zIn points to the first byte of a UTF-8 character,
11778** advance zIn to point to the first byte of the next UTF-8 character.
11779*/
11780#define SQLITE_SKIP_UTF8(zIn) {                        \
11781  if( (*(zIn++))>=0xc0 ){                              \
11782    while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
11783  }                                                    \
11784}
11785
11786/*
11787** The SQLITE_*_BKPT macros are substitutes for the error codes with
11788** the same name but without the _BKPT suffix.  These macros invoke
11789** routines that report the line-number on which the error originated
11790** using sqlite3_log().  The routines also provide a convenient place
11791** to set a debugger breakpoint.
11792*/
11793SQLITE_PRIVATE int sqlite3CorruptError(int);
11794SQLITE_PRIVATE int sqlite3MisuseError(int);
11795SQLITE_PRIVATE int sqlite3CantopenError(int);
11796#define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
11797#define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
11798#define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
11799
11800
11801/*
11802** FTS4 is really an extension for FTS3.  It is enabled using the
11803** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
11804** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
11805*/
11806#if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
11807# define SQLITE_ENABLE_FTS3
11808#endif
11809
11810/*
11811** The ctype.h header is needed for non-ASCII systems.  It is also
11812** needed by FTS3 when FTS3 is included in the amalgamation.
11813*/
11814#if !defined(SQLITE_ASCII) || \
11815    (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
11816# include <ctype.h>
11817#endif
11818
11819/*
11820** The following macros mimic the standard library functions toupper(),
11821** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
11822** sqlite versions only work for ASCII characters, regardless of locale.
11823*/
11824#ifdef SQLITE_ASCII
11825# define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
11826# define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
11827# define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
11828# define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
11829# define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
11830# define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
11831# define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
11832#else
11833# define sqlite3Toupper(x)   toupper((unsigned char)(x))
11834# define sqlite3Isspace(x)   isspace((unsigned char)(x))
11835# define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
11836# define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
11837# define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
11838# define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
11839# define sqlite3Tolower(x)   tolower((unsigned char)(x))
11840#endif
11841
11842/*
11843** Internal function prototypes
11844*/
11845#define sqlite3StrICmp sqlite3_stricmp
11846SQLITE_PRIVATE int sqlite3Strlen30(const char*);
11847#define sqlite3StrNICmp sqlite3_strnicmp
11848
11849SQLITE_PRIVATE int sqlite3MallocInit(void);
11850SQLITE_PRIVATE void sqlite3MallocEnd(void);
11851SQLITE_PRIVATE void *sqlite3Malloc(int);
11852SQLITE_PRIVATE void *sqlite3MallocZero(int);
11853SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
11854SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
11855SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
11856SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
11857SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
11858SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
11859SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
11860SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
11861SQLITE_PRIVATE int sqlite3MallocSize(void*);
11862SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
11863SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
11864SQLITE_PRIVATE void sqlite3ScratchFree(void*);
11865SQLITE_PRIVATE void *sqlite3PageMalloc(int);
11866SQLITE_PRIVATE void sqlite3PageFree(void*);
11867SQLITE_PRIVATE void sqlite3MemSetDefault(void);
11868SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
11869SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
11870
11871/*
11872** On systems with ample stack space and that support alloca(), make
11873** use of alloca() to obtain space for large automatic objects.  By default,
11874** obtain space from malloc().
11875**
11876** The alloca() routine never returns NULL.  This will cause code paths
11877** that deal with sqlite3StackAlloc() failures to be unreachable.
11878*/
11879#ifdef SQLITE_USE_ALLOCA
11880# define sqlite3StackAllocRaw(D,N)   alloca(N)
11881# define sqlite3StackAllocZero(D,N)  memset(alloca(N), 0, N)
11882# define sqlite3StackFree(D,P)
11883#else
11884# define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)
11885# define sqlite3StackAllocZero(D,N)  sqlite3DbMallocZero(D,N)
11886# define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)
11887#endif
11888
11889#ifdef SQLITE_ENABLE_MEMSYS3
11890SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
11891#endif
11892#ifdef SQLITE_ENABLE_MEMSYS5
11893SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
11894#endif
11895
11896
11897#ifndef SQLITE_MUTEX_OMIT
11898SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
11899SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3NoopMutex(void);
11900SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);
11901SQLITE_PRIVATE   int sqlite3MutexInit(void);
11902SQLITE_PRIVATE   int sqlite3MutexEnd(void);
11903#endif
11904
11905SQLITE_PRIVATE int sqlite3StatusValue(int);
11906SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
11907SQLITE_PRIVATE void sqlite3StatusSet(int, int);
11908
11909#ifndef SQLITE_OMIT_FLOATING_POINT
11910SQLITE_PRIVATE   int sqlite3IsNaN(double);
11911#else
11912# define sqlite3IsNaN(X)  0
11913#endif
11914
11915SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
11916#ifndef SQLITE_OMIT_TRACE
11917SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
11918#endif
11919SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
11920SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
11921SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
11922#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
11923SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
11924#endif
11925#if defined(SQLITE_TEST)
11926SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);
11927#endif
11928
11929/* Output formatting for SQLITE_TESTCTRL_EXPLAIN */
11930#if defined(SQLITE_ENABLE_TREE_EXPLAIN)
11931SQLITE_PRIVATE   void sqlite3ExplainBegin(Vdbe*);
11932SQLITE_PRIVATE   void sqlite3ExplainPrintf(Vdbe*, const char*, ...);
11933SQLITE_PRIVATE   void sqlite3ExplainNL(Vdbe*);
11934SQLITE_PRIVATE   void sqlite3ExplainPush(Vdbe*);
11935SQLITE_PRIVATE   void sqlite3ExplainPop(Vdbe*);
11936SQLITE_PRIVATE   void sqlite3ExplainFinish(Vdbe*);
11937SQLITE_PRIVATE   void sqlite3ExplainSelect(Vdbe*, Select*);
11938SQLITE_PRIVATE   void sqlite3ExplainExpr(Vdbe*, Expr*);
11939SQLITE_PRIVATE   void sqlite3ExplainExprList(Vdbe*, ExprList*);
11940SQLITE_PRIVATE   const char *sqlite3VdbeExplanation(Vdbe*);
11941#else
11942# define sqlite3ExplainBegin(X)
11943# define sqlite3ExplainSelect(A,B)
11944# define sqlite3ExplainExpr(A,B)
11945# define sqlite3ExplainExprList(A,B)
11946# define sqlite3ExplainFinish(X)
11947# define sqlite3VdbeExplanation(X) 0
11948#endif
11949
11950
11951SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
11952SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
11953SQLITE_PRIVATE int sqlite3Dequote(char*);
11954SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
11955SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
11956SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
11957SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
11958SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
11959SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
11960SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
11961SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
11962SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
11963SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
11964SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
11965SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
11966SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
11967SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
11968SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
11969SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
11970SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
11971SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
11972SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
11973SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
11974SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
11975SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
11976SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
11977SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
11978SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
11979SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
11980SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
11981SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
11982SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
11983SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
11984SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
11985SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
11986SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
11987SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
11988SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
11989SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
11990SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
11991SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
11992SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);
11993SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
11994                    sqlite3_vfs**,char**,char **);
11995SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
11996SQLITE_PRIVATE int sqlite3CodeOnce(Parse *);
11997
11998SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
11999SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
12000SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
12001SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
12002SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
12003SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
12004SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
12005
12006SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
12007SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
12008SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
12009SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, u8 iBatch, i64);
12010SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
12011
12012SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
12013
12014#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
12015SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
12016#else
12017# define sqlite3ViewGetColumnNames(A,B) 0
12018#endif
12019
12020SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
12021SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
12022SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
12023#ifndef SQLITE_OMIT_AUTOINCREMENT
12024SQLITE_PRIVATE   void sqlite3AutoincrementBegin(Parse *pParse);
12025SQLITE_PRIVATE   void sqlite3AutoincrementEnd(Parse *pParse);
12026#else
12027# define sqlite3AutoincrementBegin(X)
12028# define sqlite3AutoincrementEnd(X)
12029#endif
12030SQLITE_PRIVATE int sqlite3CodeCoroutine(Parse*, Select*, SelectDest*);
12031SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
12032SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
12033SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
12034SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
12035SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
12036SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
12037SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
12038                                      Token*, Select*, Expr*, IdList*);
12039SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
12040SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
12041SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
12042SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
12043SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
12044SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
12045SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
12046                        Token*, int, int);
12047SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
12048SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
12049SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
12050                         Expr*,ExprList*,u16,Expr*,Expr*);
12051SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
12052SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
12053SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
12054SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
12055#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
12056SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,Expr*,char*);
12057#endif
12058SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
12059SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
12060SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
12061SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
12062SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
12063SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
12064SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
12065SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
12066SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
12067SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*, int);
12068SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
12069SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
12070SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
12071SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
12072SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
12073SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
12074SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
12075SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);
12076SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
12077SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
12078SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
12079SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
12080SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
12081SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,int isView,struct SrcList_item *);
12082SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
12083SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
12084SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
12085SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
12086SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
12087SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
12088SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*);
12089SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*);
12090SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
12091SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
12092SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
12093SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
12094SQLITE_PRIVATE void sqlite3PrngSaveState(void);
12095SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
12096SQLITE_PRIVATE void sqlite3PrngResetState(void);
12097SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
12098SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
12099SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
12100SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
12101SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
12102SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
12103SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
12104SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
12105SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
12106SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
12107SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
12108SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
12109SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
12110SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
12111SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int);
12112SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
12113SQLITE_PRIVATE int sqlite3IsRowid(const char*);
12114SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int, Trigger *, int);
12115SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
12116SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
12117SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
12118                                     int*,int,int,int,int,int*);
12119SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
12120SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
12121SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
12122SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
12123SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
12124SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, int);
12125SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
12126SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
12127SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
12128SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
12129SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
12130SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
12131SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,u8);
12132SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
12133SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
12134SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
12135SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
12136SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
12137SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
12138
12139#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
12140SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
12141#endif
12142
12143#ifndef SQLITE_OMIT_TRIGGER
12144SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
12145                           Expr*,int, int);
12146SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
12147SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
12148SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
12149SQLITE_PRIVATE   Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
12150SQLITE_PRIVATE   Trigger *sqlite3TriggerList(Parse *, Table *);
12151SQLITE_PRIVATE   void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
12152                            int, int, int);
12153SQLITE_PRIVATE   void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
12154  void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
12155SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
12156SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
12157SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
12158                                        ExprList*,Select*,u8);
12159SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
12160SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
12161SQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
12162SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
12163SQLITE_PRIVATE   u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
12164# define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
12165#else
12166# define sqlite3TriggersExist(B,C,D,E,F) 0
12167# define sqlite3DeleteTrigger(A,B)
12168# define sqlite3DropTriggerPtr(A,B)
12169# define sqlite3UnlinkAndDeleteTrigger(A,B,C)
12170# define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
12171# define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
12172# define sqlite3TriggerList(X, Y) 0
12173# define sqlite3ParseToplevel(p) p
12174# define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
12175#endif
12176
12177SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
12178SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
12179SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
12180#ifndef SQLITE_OMIT_AUTHORIZATION
12181SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
12182SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
12183SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
12184SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
12185SQLITE_PRIVATE   int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
12186#else
12187# define sqlite3AuthRead(a,b,c,d)
12188# define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
12189# define sqlite3AuthContextPush(a,b,c)
12190# define sqlite3AuthContextPop(a)  ((void)(a))
12191#endif
12192SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
12193SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
12194SQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
12195SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
12196SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
12197SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
12198SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
12199SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
12200SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
12201SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
12202SQLITE_PRIVATE int sqlite3Atoi(const char*);
12203SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
12204SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
12205SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
12206
12207/*
12208** Routines to read and write variable-length integers.  These used to
12209** be defined locally, but now we use the varint routines in the util.c
12210** file.  Code should use the MACRO forms below, as the Varint32 versions
12211** are coded to assume the single byte case is already handled (which
12212** the MACRO form does).
12213*/
12214SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
12215SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
12216SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
12217SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
12218SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
12219
12220/*
12221** The header of a record consists of a sequence variable-length integers.
12222** These integers are almost always small and are encoded as a single byte.
12223** The following macros take advantage this fact to provide a fast encode
12224** and decode of the integers in a record header.  It is faster for the common
12225** case where the integer is a single byte.  It is a little slower when the
12226** integer is two or more bytes.  But overall it is faster.
12227**
12228** The following expressions are equivalent:
12229**
12230**     x = sqlite3GetVarint32( A, &B );
12231**     x = sqlite3PutVarint32( A, B );
12232**
12233**     x = getVarint32( A, B );
12234**     x = putVarint32( A, B );
12235**
12236*/
12237#define getVarint32(A,B)  \
12238  (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
12239#define putVarint32(A,B)  \
12240  (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
12241  sqlite3PutVarint32((A),(B)))
12242#define getVarint    sqlite3GetVarint
12243#define putVarint    sqlite3PutVarint
12244
12245
12246SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
12247SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
12248SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
12249SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
12250SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
12251SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
12252SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
12253SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
12254SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
12255SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
12256
12257#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) || \
12258    defined(SQLITE_DEBUG_OS_TRACE)
12259SQLITE_PRIVATE const char *sqlite3ErrName(int);
12260#endif
12261
12262SQLITE_PRIVATE const char *sqlite3ErrStr(int);
12263SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
12264SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
12265SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
12266SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
12267SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, Token*);
12268SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
12269SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
12270SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
12271SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
12272SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
12273SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
12274SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
12275SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
12276SQLITE_PRIVATE int sqlite3AbsInt32(int);
12277#ifdef SQLITE_ENABLE_8_3_NAMES
12278SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
12279#else
12280# define sqlite3FileSuffix3(X,Y)
12281#endif
12282SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,int);
12283
12284SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
12285SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
12286SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
12287                        void(*)(void*));
12288SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
12289SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
12290SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
12291#ifdef SQLITE_ENABLE_STAT3
12292SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *, u8, char *, int, int *);
12293#endif
12294SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
12295SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
12296#ifndef SQLITE_AMALGAMATION
12297SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
12298SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
12299SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
12300SQLITE_PRIVATE const Token sqlite3IntTokens[];
12301SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
12302SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
12303#ifndef SQLITE_OMIT_WSD
12304SQLITE_PRIVATE int sqlite3PendingByte;
12305#endif
12306#endif
12307SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
12308SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
12309SQLITE_PRIVATE void sqlite3AlterFunctions(void);
12310SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
12311SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
12312SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
12313SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
12314SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
12315SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
12316SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
12317SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
12318SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
12319SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
12320SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
12321SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
12322SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
12323SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
12324SQLITE_PRIVATE char sqlite3AffinityType(const char*);
12325SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
12326SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
12327SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
12328SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
12329SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
12330SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
12331SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
12332SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
12333SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
12334SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
12335SQLITE_PRIVATE void sqlite3SchemaClear(void *);
12336SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
12337SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
12338SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
12339SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
12340  void (*)(sqlite3_context*,int,sqlite3_value **),
12341  void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
12342  FuncDestructor *pDestructor
12343);
12344SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
12345SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
12346
12347SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
12348SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
12349SQLITE_PRIVATE void sqlite3AppendSpace(StrAccum*,int);
12350SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
12351SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
12352SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
12353SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
12354
12355SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
12356SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
12357
12358/*
12359** The interface to the LEMON-generated parser
12360*/
12361SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
12362SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
12363SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
12364#ifdef YYTRACKMAXSTACKDEPTH
12365SQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);
12366#endif
12367
12368SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
12369#ifndef SQLITE_OMIT_LOAD_EXTENSION
12370SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
12371#else
12372# define sqlite3CloseExtensions(X)
12373#endif
12374
12375#ifndef SQLITE_OMIT_SHARED_CACHE
12376SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
12377#else
12378  #define sqlite3TableLock(v,w,x,y,z)
12379#endif
12380
12381#ifdef SQLITE_TEST
12382SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
12383#endif
12384
12385#ifdef SQLITE_OMIT_VIRTUALTABLE
12386#  define sqlite3VtabClear(Y)
12387#  define sqlite3VtabSync(X,Y) SQLITE_OK
12388#  define sqlite3VtabRollback(X)
12389#  define sqlite3VtabCommit(X)
12390#  define sqlite3VtabInSync(db) 0
12391#  define sqlite3VtabLock(X)
12392#  define sqlite3VtabUnlock(X)
12393#  define sqlite3VtabUnlockList(X)
12394#  define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
12395#  define sqlite3GetVTable(X,Y)  ((VTable*)0)
12396#else
12397SQLITE_PRIVATE    void sqlite3VtabClear(sqlite3 *db, Table*);
12398SQLITE_PRIVATE    void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
12399SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, char **);
12400SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
12401SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
12402SQLITE_PRIVATE    void sqlite3VtabLock(VTable *);
12403SQLITE_PRIVATE    void sqlite3VtabUnlock(VTable *);
12404SQLITE_PRIVATE    void sqlite3VtabUnlockList(sqlite3*);
12405SQLITE_PRIVATE    int sqlite3VtabSavepoint(sqlite3 *, int, int);
12406SQLITE_PRIVATE    VTable *sqlite3GetVTable(sqlite3*, Table*);
12407#  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
12408#endif
12409SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
12410SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
12411SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
12412SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
12413SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
12414SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
12415SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
12416SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
12417SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
12418SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
12419SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
12420SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
12421SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
12422SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
12423SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
12424SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
12425SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
12426SQLITE_PRIVATE const char *sqlite3JournalModename(int);
12427#ifndef SQLITE_OMIT_WAL
12428SQLITE_PRIVATE   int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
12429SQLITE_PRIVATE   int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
12430#endif
12431
12432/* Declarations for functions in fkey.c. All of these are replaced by
12433** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
12434** key functionality is available. If OMIT_TRIGGER is defined but
12435** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
12436** this case foreign keys are parsed, but no other functionality is
12437** provided (enforcement of FK constraints requires the triggers sub-system).
12438*/
12439#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
12440SQLITE_PRIVATE   void sqlite3FkCheck(Parse*, Table*, int, int);
12441SQLITE_PRIVATE   void sqlite3FkDropTable(Parse*, SrcList *, Table*);
12442SQLITE_PRIVATE   void sqlite3FkActions(Parse*, Table*, ExprList*, int);
12443SQLITE_PRIVATE   int sqlite3FkRequired(Parse*, Table*, int*, int);
12444SQLITE_PRIVATE   u32 sqlite3FkOldmask(Parse*, Table*);
12445SQLITE_PRIVATE   FKey *sqlite3FkReferences(Table *);
12446#else
12447  #define sqlite3FkActions(a,b,c,d)
12448  #define sqlite3FkCheck(a,b,c,d)
12449  #define sqlite3FkDropTable(a,b,c)
12450  #define sqlite3FkOldmask(a,b)      0
12451  #define sqlite3FkRequired(a,b,c,d) 0
12452#endif
12453#ifndef SQLITE_OMIT_FOREIGN_KEY
12454SQLITE_PRIVATE   void sqlite3FkDelete(sqlite3 *, Table*);
12455SQLITE_PRIVATE   int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
12456#else
12457  #define sqlite3FkDelete(a,b)
12458  #define sqlite3FkLocateIndex(a,b,c,d,e)
12459#endif
12460
12461
12462/*
12463** Available fault injectors.  Should be numbered beginning with 0.
12464*/
12465#define SQLITE_FAULTINJECTOR_MALLOC     0
12466#define SQLITE_FAULTINJECTOR_COUNT      1
12467
12468/*
12469** The interface to the code in fault.c used for identifying "benign"
12470** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
12471** is not defined.
12472*/
12473#ifndef SQLITE_OMIT_BUILTIN_TEST
12474SQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);
12475SQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);
12476#else
12477  #define sqlite3BeginBenignMalloc()
12478  #define sqlite3EndBenignMalloc()
12479#endif
12480
12481#define IN_INDEX_ROWID           1
12482#define IN_INDEX_EPH             2
12483#define IN_INDEX_INDEX_ASC       3
12484#define IN_INDEX_INDEX_DESC      4
12485SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);
12486
12487#ifdef SQLITE_ENABLE_ATOMIC_WRITE
12488SQLITE_PRIVATE   int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
12489SQLITE_PRIVATE   int sqlite3JournalSize(sqlite3_vfs *);
12490SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
12491SQLITE_PRIVATE   int sqlite3JournalExists(sqlite3_file *p);
12492#else
12493  #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
12494  #define sqlite3JournalExists(p) 1
12495#endif
12496
12497SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
12498SQLITE_PRIVATE int sqlite3MemJournalSize(void);
12499SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
12500
12501#if SQLITE_MAX_EXPR_DEPTH>0
12502SQLITE_PRIVATE   void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
12503SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
12504SQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);
12505#else
12506  #define sqlite3ExprSetHeight(x,y)
12507  #define sqlite3SelectExprHeight(x) 0
12508  #define sqlite3ExprCheckHeight(x,y)
12509#endif
12510
12511SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
12512SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
12513
12514#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
12515SQLITE_PRIVATE   void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
12516SQLITE_PRIVATE   void sqlite3ConnectionUnlocked(sqlite3 *db);
12517SQLITE_PRIVATE   void sqlite3ConnectionClosed(sqlite3 *db);
12518#else
12519  #define sqlite3ConnectionBlocked(x,y)
12520  #define sqlite3ConnectionUnlocked(x)
12521  #define sqlite3ConnectionClosed(x)
12522#endif
12523
12524#ifdef SQLITE_DEBUG
12525SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
12526#endif
12527
12528/*
12529** If the SQLITE_ENABLE IOTRACE exists then the global variable
12530** sqlite3IoTrace is a pointer to a printf-like routine used to
12531** print I/O tracing messages.
12532*/
12533#ifdef SQLITE_ENABLE_IOTRACE
12534# define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
12535SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
12536SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
12537#else
12538# define IOTRACE(A)
12539# define sqlite3VdbeIOTraceSql(X)
12540#endif
12541
12542/*
12543** These routines are available for the mem2.c debugging memory allocator
12544** only.  They are used to verify that different "types" of memory
12545** allocations are properly tracked by the system.
12546**
12547** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
12548** the MEMTYPE_* macros defined below.  The type must be a bitmask with
12549** a single bit set.
12550**
12551** sqlite3MemdebugHasType() returns true if any of the bits in its second
12552** argument match the type set by the previous sqlite3MemdebugSetType().
12553** sqlite3MemdebugHasType() is intended for use inside assert() statements.
12554**
12555** sqlite3MemdebugNoType() returns true if none of the bits in its second
12556** argument match the type set by the previous sqlite3MemdebugSetType().
12557**
12558** Perhaps the most important point is the difference between MEMTYPE_HEAP
12559** and MEMTYPE_LOOKASIDE.  If an allocation is MEMTYPE_LOOKASIDE, that means
12560** it might have been allocated by lookaside, except the allocation was
12561** too large or lookaside was already full.  It is important to verify
12562** that allocations that might have been satisfied by lookaside are not
12563** passed back to non-lookaside free() routines.  Asserts such as the
12564** example above are placed on the non-lookaside free() routines to verify
12565** this constraint.
12566**
12567** All of this is no-op for a production build.  It only comes into
12568** play when the SQLITE_MEMDEBUG compile-time option is used.
12569*/
12570#ifdef SQLITE_MEMDEBUG
12571SQLITE_PRIVATE   void sqlite3MemdebugSetType(void*,u8);
12572SQLITE_PRIVATE   int sqlite3MemdebugHasType(void*,u8);
12573SQLITE_PRIVATE   int sqlite3MemdebugNoType(void*,u8);
12574#else
12575# define sqlite3MemdebugSetType(X,Y)  /* no-op */
12576# define sqlite3MemdebugHasType(X,Y)  1
12577# define sqlite3MemdebugNoType(X,Y)   1
12578#endif
12579#define MEMTYPE_HEAP       0x01  /* General heap allocations */
12580#define MEMTYPE_LOOKASIDE  0x02  /* Might have been lookaside memory */
12581#define MEMTYPE_SCRATCH    0x04  /* Scratch allocations */
12582#define MEMTYPE_PCACHE     0x08  /* Page cache allocations */
12583#define MEMTYPE_DB         0x10  /* Uses sqlite3DbMalloc, not sqlite_malloc */
12584
12585#endif /* _SQLITEINT_H_ */
12586
12587/************** End of sqliteInt.h *******************************************/
12588/************** Begin file global.c ******************************************/
12589/*
12590** 2008 June 13
12591**
12592** The author disclaims copyright to this source code.  In place of
12593** a legal notice, here is a blessing:
12594**
12595**    May you do good and not evil.
12596**    May you find forgiveness for yourself and forgive others.
12597**    May you share freely, never taking more than you give.
12598**
12599*************************************************************************
12600**
12601** This file contains definitions of global variables and contants.
12602*/
12603
12604/* An array to map all upper-case characters into their corresponding
12605** lower-case character.
12606**
12607** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
12608** handle case conversions for the UTF character set since the tables
12609** involved are nearly as big or bigger than SQLite itself.
12610*/
12611SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
12612#ifdef SQLITE_ASCII
12613      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
12614     18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
12615     36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
12616     54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
12617    104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
12618    122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
12619    108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
12620    126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
12621    144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
12622    162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
12623    180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
12624    198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
12625    216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
12626    234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
12627    252,253,254,255
12628#endif
12629#ifdef SQLITE_EBCDIC
12630      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
12631     16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
12632     32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
12633     48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
12634     64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
12635     80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
12636     96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
12637    112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
12638    128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
12639    144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
12640    160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
12641    176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
12642    192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
12643    208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
12644    224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
12645    239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
12646#endif
12647};
12648
12649/*
12650** The following 256 byte lookup table is used to support SQLites built-in
12651** equivalents to the following standard library functions:
12652**
12653**   isspace()                        0x01
12654**   isalpha()                        0x02
12655**   isdigit()                        0x04
12656**   isalnum()                        0x06
12657**   isxdigit()                       0x08
12658**   toupper()                        0x20
12659**   SQLite identifier character      0x40
12660**
12661** Bit 0x20 is set if the mapped character requires translation to upper
12662** case. i.e. if the character is a lower-case ASCII character.
12663** If x is a lower-case ASCII character, then its upper-case equivalent
12664** is (x - 0x20). Therefore toupper() can be implemented as:
12665**
12666**   (x & ~(map[x]&0x20))
12667**
12668** Standard function tolower() is implemented using the sqlite3UpperToLower[]
12669** array. tolower() is used more often than toupper() by SQLite.
12670**
12671** Bit 0x40 is set if the character non-alphanumeric and can be used in an
12672** SQLite identifier.  Identifiers are alphanumerics, "_", "$", and any
12673** non-ASCII UTF character. Hence the test for whether or not a character is
12674** part of an identifier is 0x46.
12675**
12676** SQLite's versions are identical to the standard versions assuming a
12677** locale of "C". They are implemented as macros in sqliteInt.h.
12678*/
12679#ifdef SQLITE_ASCII
12680SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
12681  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */
12682  0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */
12683  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */
12684  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */
12685  0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,  /* 20..27     !"#$%&' */
12686  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */
12687  0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */
12688  0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */
12689
12690  0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */
12691  0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */
12692  0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */
12693  0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40,  /* 58..5f    XYZ[\]^_ */
12694  0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */
12695  0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */
12696  0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */
12697  0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */
12698
12699  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 80..87    ........ */
12700  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 88..8f    ........ */
12701  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 90..97    ........ */
12702  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 98..9f    ........ */
12703  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a0..a7    ........ */
12704  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a8..af    ........ */
12705  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b0..b7    ........ */
12706  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b8..bf    ........ */
12707
12708  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c0..c7    ........ */
12709  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c8..cf    ........ */
12710  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d0..d7    ........ */
12711  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d8..df    ........ */
12712  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e0..e7    ........ */
12713  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e8..ef    ........ */
12714  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */
12715  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */
12716};
12717#endif
12718
12719#ifndef SQLITE_USE_URI
12720# define  SQLITE_USE_URI 0
12721#endif
12722
12723#ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN
12724# define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
12725#endif
12726
12727/*
12728** The following singleton contains the global configuration for
12729** the SQLite library.
12730*/
12731SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
12732   SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
12733   1,                         /* bCoreMutex */
12734   SQLITE_THREADSAFE==1,      /* bFullMutex */
12735   SQLITE_USE_URI,            /* bOpenUri */
12736   SQLITE_ALLOW_COVERING_INDEX_SCAN,   /* bUseCis */
12737   0x7ffffffe,                /* mxStrlen */
12738   128,                       /* szLookaside */
12739   500,                       /* nLookaside */
12740   {0,0,0,0,0,0,0,0},         /* m */
12741   {0,0,0,0,0,0,0,0,0},       /* mutex */
12742   {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
12743   (void*)0,                  /* pHeap */
12744   0,                         /* nHeap */
12745   0, 0,                      /* mnHeap, mxHeap */
12746   SQLITE_DEFAULT_MMAP_SIZE,  /* szMmap */
12747   SQLITE_MAX_MMAP_SIZE,      /* mxMmap */
12748   (void*)0,                  /* pScratch */
12749   0,                         /* szScratch */
12750   0,                         /* nScratch */
12751   (void*)0,                  /* pPage */
12752   0,                         /* szPage */
12753   0,                         /* nPage */
12754   0,                         /* mxParserStack */
12755   0,                         /* sharedCacheEnabled */
12756   /* All the rest should always be initialized to zero */
12757   0,                         /* isInit */
12758   0,                         /* inProgress */
12759   0,                         /* isMutexInit */
12760   0,                         /* isMallocInit */
12761   0,                         /* isPCacheInit */
12762   0,                         /* pInitMutex */
12763   0,                         /* nRefInitMutex */
12764   0,                         /* xLog */
12765   0,                         /* pLogArg */
12766   0,                         /* bLocaltimeFault */
12767#ifdef SQLITE_ENABLE_SQLLOG
12768   0,                         /* xSqllog */
12769   0                          /* pSqllogArg */
12770#endif
12771};
12772
12773
12774/*
12775** Hash table for global functions - functions common to all
12776** database connections.  After initialization, this table is
12777** read-only.
12778*/
12779SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
12780
12781/*
12782** Constant tokens for values 0 and 1.
12783*/
12784SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
12785   { "0", 1 },
12786   { "1", 1 }
12787};
12788
12789
12790/*
12791** The value of the "pending" byte must be 0x40000000 (1 byte past the
12792** 1-gibabyte boundary) in a compatible database.  SQLite never uses
12793** the database page that contains the pending byte.  It never attempts
12794** to read or write that page.  The pending byte page is set assign
12795** for use by the VFS layers as space for managing file locks.
12796**
12797** During testing, it is often desirable to move the pending byte to
12798** a different position in the file.  This allows code that has to
12799** deal with the pending byte to run on files that are much smaller
12800** than 1 GiB.  The sqlite3_test_control() interface can be used to
12801** move the pending byte.
12802**
12803** IMPORTANT:  Changing the pending byte to any value other than
12804** 0x40000000 results in an incompatible database file format!
12805** Changing the pending byte during operating results in undefined
12806** and dileterious behavior.
12807*/
12808#ifndef SQLITE_OMIT_WSD
12809SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
12810#endif
12811
12812/*
12813** Properties of opcodes.  The OPFLG_INITIALIZER macro is
12814** created by mkopcodeh.awk during compilation.  Data is obtained
12815** from the comments following the "case OP_xxxx:" statements in
12816** the vdbe.c file.
12817*/
12818SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
12819
12820/************** End of global.c **********************************************/
12821/************** Begin file ctime.c *******************************************/
12822/*
12823** 2010 February 23
12824**
12825** The author disclaims copyright to this source code.  In place of
12826** a legal notice, here is a blessing:
12827**
12828**    May you do good and not evil.
12829**    May you find forgiveness for yourself and forgive others.
12830**    May you share freely, never taking more than you give.
12831**
12832*************************************************************************
12833**
12834** This file implements routines used to report what compile-time options
12835** SQLite was built with.
12836*/
12837
12838#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
12839
12840
12841/*
12842** An array of names of all compile-time options.  This array should
12843** be sorted A-Z.
12844**
12845** This array looks large, but in a typical installation actually uses
12846** only a handful of compile-time options, so most times this array is usually
12847** rather short and uses little memory space.
12848*/
12849static const char * const azCompileOpt[] = {
12850
12851/* These macros are provided to "stringify" the value of the define
12852** for those options in which the value is meaningful. */
12853#define CTIMEOPT_VAL_(opt) #opt
12854#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
12855
12856#ifdef SQLITE_32BIT_ROWID
12857  "32BIT_ROWID",
12858#endif
12859#ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
12860  "4_BYTE_ALIGNED_MALLOC",
12861#endif
12862#ifdef SQLITE_CASE_SENSITIVE_LIKE
12863  "CASE_SENSITIVE_LIKE",
12864#endif
12865#ifdef SQLITE_CHECK_PAGES
12866  "CHECK_PAGES",
12867#endif
12868#ifdef SQLITE_COVERAGE_TEST
12869  "COVERAGE_TEST",
12870#endif
12871#ifdef SQLITE_DEBUG
12872  "DEBUG",
12873#endif
12874#ifdef SQLITE_DEFAULT_LOCKING_MODE
12875  "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
12876#endif
12877#if defined(SQLITE_DEFAULT_MMAP_SIZE) && !defined(SQLITE_DEFAULT_MMAP_SIZE_xc)
12878  "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE),
12879#endif
12880#ifdef SQLITE_DISABLE_DIRSYNC
12881  "DISABLE_DIRSYNC",
12882#endif
12883#ifdef SQLITE_DISABLE_LFS
12884  "DISABLE_LFS",
12885#endif
12886#ifdef SQLITE_ENABLE_ATOMIC_WRITE
12887  "ENABLE_ATOMIC_WRITE",
12888#endif
12889#ifdef SQLITE_ENABLE_CEROD
12890  "ENABLE_CEROD",
12891#endif
12892#ifdef SQLITE_ENABLE_COLUMN_METADATA
12893  "ENABLE_COLUMN_METADATA",
12894#endif
12895#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
12896  "ENABLE_EXPENSIVE_ASSERT",
12897#endif
12898#ifdef SQLITE_ENABLE_FTS1
12899  "ENABLE_FTS1",
12900#endif
12901#ifdef SQLITE_ENABLE_FTS2
12902  "ENABLE_FTS2",
12903#endif
12904#ifdef SQLITE_ENABLE_FTS3
12905  "ENABLE_FTS3",
12906#endif
12907#ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
12908  "ENABLE_FTS3_PARENTHESIS",
12909#endif
12910#ifdef SQLITE_ENABLE_FTS4
12911  "ENABLE_FTS4",
12912#endif
12913#ifdef SQLITE_ENABLE_ICU
12914  "ENABLE_ICU",
12915#endif
12916#ifdef SQLITE_ENABLE_IOTRACE
12917  "ENABLE_IOTRACE",
12918#endif
12919#ifdef SQLITE_ENABLE_LOAD_EXTENSION
12920  "ENABLE_LOAD_EXTENSION",
12921#endif
12922#ifdef SQLITE_ENABLE_LOCKING_STYLE
12923  "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
12924#endif
12925#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
12926  "ENABLE_MEMORY_MANAGEMENT",
12927#endif
12928#ifdef SQLITE_ENABLE_MEMSYS3
12929  "ENABLE_MEMSYS3",
12930#endif
12931#ifdef SQLITE_ENABLE_MEMSYS5
12932  "ENABLE_MEMSYS5",
12933#endif
12934#ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK
12935  "ENABLE_OVERSIZE_CELL_CHECK",
12936#endif
12937#ifdef SQLITE_ENABLE_RTREE
12938  "ENABLE_RTREE",
12939#endif
12940#ifdef SQLITE_ENABLE_STAT3
12941  "ENABLE_STAT3",
12942#endif
12943#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
12944  "ENABLE_UNLOCK_NOTIFY",
12945#endif
12946#ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
12947  "ENABLE_UPDATE_DELETE_LIMIT",
12948#endif
12949#ifdef SQLITE_HAS_CODEC
12950  "HAS_CODEC",
12951#endif
12952#ifdef SQLITE_HAVE_ISNAN
12953  "HAVE_ISNAN",
12954#endif
12955#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
12956  "HOMEGROWN_RECURSIVE_MUTEX",
12957#endif
12958#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
12959  "IGNORE_AFP_LOCK_ERRORS",
12960#endif
12961#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
12962  "IGNORE_FLOCK_LOCK_ERRORS",
12963#endif
12964#ifdef SQLITE_INT64_TYPE
12965  "INT64_TYPE",
12966#endif
12967#ifdef SQLITE_LOCK_TRACE
12968  "LOCK_TRACE",
12969#endif
12970#if defined(SQLITE_MAX_MMAP_SIZE) && !defined(SQLITE_MAX_MMAP_SIZE_xc)
12971  "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),
12972#endif
12973#ifdef SQLITE_MAX_SCHEMA_RETRY
12974  "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
12975#endif
12976#ifdef SQLITE_MEMDEBUG
12977  "MEMDEBUG",
12978#endif
12979#ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
12980  "MIXED_ENDIAN_64BIT_FLOAT",
12981#endif
12982#ifdef SQLITE_NO_SYNC
12983  "NO_SYNC",
12984#endif
12985#ifdef SQLITE_OMIT_ALTERTABLE
12986  "OMIT_ALTERTABLE",
12987#endif
12988#ifdef SQLITE_OMIT_ANALYZE
12989  "OMIT_ANALYZE",
12990#endif
12991#ifdef SQLITE_OMIT_ATTACH
12992  "OMIT_ATTACH",
12993#endif
12994#ifdef SQLITE_OMIT_AUTHORIZATION
12995  "OMIT_AUTHORIZATION",
12996#endif
12997#ifdef SQLITE_OMIT_AUTOINCREMENT
12998  "OMIT_AUTOINCREMENT",
12999#endif
13000#ifdef SQLITE_OMIT_AUTOINIT
13001  "OMIT_AUTOINIT",
13002#endif
13003#ifdef SQLITE_OMIT_AUTOMATIC_INDEX
13004  "OMIT_AUTOMATIC_INDEX",
13005#endif
13006#ifdef SQLITE_OMIT_AUTORESET
13007  "OMIT_AUTORESET",
13008#endif
13009#ifdef SQLITE_OMIT_AUTOVACUUM
13010  "OMIT_AUTOVACUUM",
13011#endif
13012#ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION
13013  "OMIT_BETWEEN_OPTIMIZATION",
13014#endif
13015#ifdef SQLITE_OMIT_BLOB_LITERAL
13016  "OMIT_BLOB_LITERAL",
13017#endif
13018#ifdef SQLITE_OMIT_BTREECOUNT
13019  "OMIT_BTREECOUNT",
13020#endif
13021#ifdef SQLITE_OMIT_BUILTIN_TEST
13022  "OMIT_BUILTIN_TEST",
13023#endif
13024#ifdef SQLITE_OMIT_CAST
13025  "OMIT_CAST",
13026#endif
13027#ifdef SQLITE_OMIT_CHECK
13028  "OMIT_CHECK",
13029#endif
13030#ifdef SQLITE_OMIT_COMPLETE
13031  "OMIT_COMPLETE",
13032#endif
13033#ifdef SQLITE_OMIT_COMPOUND_SELECT
13034  "OMIT_COMPOUND_SELECT",
13035#endif
13036#ifdef SQLITE_OMIT_DATETIME_FUNCS
13037  "OMIT_DATETIME_FUNCS",
13038#endif
13039#ifdef SQLITE_OMIT_DECLTYPE
13040  "OMIT_DECLTYPE",
13041#endif
13042#ifdef SQLITE_OMIT_DEPRECATED
13043  "OMIT_DEPRECATED",
13044#endif
13045#ifdef SQLITE_OMIT_DISKIO
13046  "OMIT_DISKIO",
13047#endif
13048#ifdef SQLITE_OMIT_EXPLAIN
13049  "OMIT_EXPLAIN",
13050#endif
13051#ifdef SQLITE_OMIT_FLAG_PRAGMAS
13052  "OMIT_FLAG_PRAGMAS",
13053#endif
13054#ifdef SQLITE_OMIT_FLOATING_POINT
13055  "OMIT_FLOATING_POINT",
13056#endif
13057#ifdef SQLITE_OMIT_FOREIGN_KEY
13058  "OMIT_FOREIGN_KEY",
13059#endif
13060#ifdef SQLITE_OMIT_GET_TABLE
13061  "OMIT_GET_TABLE",
13062#endif
13063#ifdef SQLITE_OMIT_INCRBLOB
13064  "OMIT_INCRBLOB",
13065#endif
13066#ifdef SQLITE_OMIT_INTEGRITY_CHECK
13067  "OMIT_INTEGRITY_CHECK",
13068#endif
13069#ifdef SQLITE_OMIT_LIKE_OPTIMIZATION
13070  "OMIT_LIKE_OPTIMIZATION",
13071#endif
13072#ifdef SQLITE_OMIT_LOAD_EXTENSION
13073  "OMIT_LOAD_EXTENSION",
13074#endif
13075#ifdef SQLITE_OMIT_LOCALTIME
13076  "OMIT_LOCALTIME",
13077#endif
13078#ifdef SQLITE_OMIT_LOOKASIDE
13079  "OMIT_LOOKASIDE",
13080#endif
13081#ifdef SQLITE_OMIT_MEMORYDB
13082  "OMIT_MEMORYDB",
13083#endif
13084#ifdef SQLITE_OMIT_OR_OPTIMIZATION
13085  "OMIT_OR_OPTIMIZATION",
13086#endif
13087#ifdef SQLITE_OMIT_PAGER_PRAGMAS
13088  "OMIT_PAGER_PRAGMAS",
13089#endif
13090#ifdef SQLITE_OMIT_PRAGMA
13091  "OMIT_PRAGMA",
13092#endif
13093#ifdef SQLITE_OMIT_PROGRESS_CALLBACK
13094  "OMIT_PROGRESS_CALLBACK",
13095#endif
13096#ifdef SQLITE_OMIT_QUICKBALANCE
13097  "OMIT_QUICKBALANCE",
13098#endif
13099#ifdef SQLITE_OMIT_REINDEX
13100  "OMIT_REINDEX",
13101#endif
13102#ifdef SQLITE_OMIT_SCHEMA_PRAGMAS
13103  "OMIT_SCHEMA_PRAGMAS",
13104#endif
13105#ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
13106  "OMIT_SCHEMA_VERSION_PRAGMAS",
13107#endif
13108#ifdef SQLITE_OMIT_SHARED_CACHE
13109  "OMIT_SHARED_CACHE",
13110#endif
13111#ifdef SQLITE_OMIT_SUBQUERY
13112  "OMIT_SUBQUERY",
13113#endif
13114#ifdef SQLITE_OMIT_TCL_VARIABLE
13115  "OMIT_TCL_VARIABLE",
13116#endif
13117#ifdef SQLITE_OMIT_TEMPDB
13118  "OMIT_TEMPDB",
13119#endif
13120#ifdef SQLITE_OMIT_TRACE
13121  "OMIT_TRACE",
13122#endif
13123#ifdef SQLITE_OMIT_TRIGGER
13124  "OMIT_TRIGGER",
13125#endif
13126#ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
13127  "OMIT_TRUNCATE_OPTIMIZATION",
13128#endif
13129#ifdef SQLITE_OMIT_UTF16
13130  "OMIT_UTF16",
13131#endif
13132#ifdef SQLITE_OMIT_VACUUM
13133  "OMIT_VACUUM",
13134#endif
13135#ifdef SQLITE_OMIT_VIEW
13136  "OMIT_VIEW",
13137#endif
13138#ifdef SQLITE_OMIT_VIRTUALTABLE
13139  "OMIT_VIRTUALTABLE",
13140#endif
13141#ifdef SQLITE_OMIT_WAL
13142  "OMIT_WAL",
13143#endif
13144#ifdef SQLITE_OMIT_WSD
13145  "OMIT_WSD",
13146#endif
13147#ifdef SQLITE_OMIT_XFER_OPT
13148  "OMIT_XFER_OPT",
13149#endif
13150#ifdef SQLITE_PERFORMANCE_TRACE
13151  "PERFORMANCE_TRACE",
13152#endif
13153#ifdef SQLITE_PROXY_DEBUG
13154  "PROXY_DEBUG",
13155#endif
13156#ifdef SQLITE_RTREE_INT_ONLY
13157  "RTREE_INT_ONLY",
13158#endif
13159#ifdef SQLITE_SECURE_DELETE
13160  "SECURE_DELETE",
13161#endif
13162#ifdef SQLITE_SMALL_STACK
13163  "SMALL_STACK",
13164#endif
13165#ifdef SQLITE_SOUNDEX
13166  "SOUNDEX",
13167#endif
13168#ifdef SQLITE_TCL
13169  "TCL",
13170#endif
13171#if defined(SQLITE_TEMP_STORE) && !defined(SQLITE_TEMP_STORE_xc)
13172  "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
13173#endif
13174#ifdef SQLITE_TEST
13175  "TEST",
13176#endif
13177#if defined(SQLITE_THREADSAFE)
13178  "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
13179#endif
13180#ifdef SQLITE_USE_ALLOCA
13181  "USE_ALLOCA",
13182#endif
13183#ifdef SQLITE_ZERO_MALLOC
13184  "ZERO_MALLOC"
13185#endif
13186};
13187
13188/*
13189** Given the name of a compile-time option, return true if that option
13190** was used and false if not.
13191**
13192** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
13193** is not required for a match.
13194*/
13195SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
13196  int i, n;
13197  if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
13198  n = sqlite3Strlen30(zOptName);
13199
13200  /* Since ArraySize(azCompileOpt) is normally in single digits, a
13201  ** linear search is adequate.  No need for a binary search. */
13202  for(i=0; i<ArraySize(azCompileOpt); i++){
13203    if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
13204     && sqlite3CtypeMap[(unsigned char)azCompileOpt[i][n]]==0
13205    ){
13206      return 1;
13207    }
13208  }
13209  return 0;
13210}
13211
13212/*
13213** Return the N-th compile-time option string.  If N is out of range,
13214** return a NULL pointer.
13215*/
13216SQLITE_API const char *sqlite3_compileoption_get(int N){
13217  if( N>=0 && N<ArraySize(azCompileOpt) ){
13218    return azCompileOpt[N];
13219  }
13220  return 0;
13221}
13222
13223#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
13224
13225/************** End of ctime.c ***********************************************/
13226/************** Begin file status.c ******************************************/
13227/*
13228** 2008 June 18
13229**
13230** The author disclaims copyright to this source code.  In place of
13231** a legal notice, here is a blessing:
13232**
13233**    May you do good and not evil.
13234**    May you find forgiveness for yourself and forgive others.
13235**    May you share freely, never taking more than you give.
13236**
13237*************************************************************************
13238**
13239** This module implements the sqlite3_status() interface and related
13240** functionality.
13241*/
13242/************** Include vdbeInt.h in the middle of status.c ******************/
13243/************** Begin file vdbeInt.h *****************************************/
13244/*
13245** 2003 September 6
13246**
13247** The author disclaims copyright to this source code.  In place of
13248** a legal notice, here is a blessing:
13249**
13250**    May you do good and not evil.
13251**    May you find forgiveness for yourself and forgive others.
13252**    May you share freely, never taking more than you give.
13253**
13254*************************************************************************
13255** This is the header file for information that is private to the
13256** VDBE.  This information used to all be at the top of the single
13257** source code file "vdbe.c".  When that file became too big (over
13258** 6000 lines long) it was split up into several smaller files and
13259** this header information was factored out.
13260*/
13261#ifndef _VDBEINT_H_
13262#define _VDBEINT_H_
13263
13264/*
13265** The maximum number of times that a statement will try to reparse
13266** itself before giving up and returning SQLITE_SCHEMA.
13267*/
13268#ifndef SQLITE_MAX_SCHEMA_RETRY
13269# define SQLITE_MAX_SCHEMA_RETRY 50
13270#endif
13271
13272/*
13273** SQL is translated into a sequence of instructions to be
13274** executed by a virtual machine.  Each instruction is an instance
13275** of the following structure.
13276*/
13277typedef struct VdbeOp Op;
13278
13279/*
13280** Boolean values
13281*/
13282typedef unsigned char Bool;
13283
13284/* Opaque type used by code in vdbesort.c */
13285typedef struct VdbeSorter VdbeSorter;
13286
13287/* Opaque type used by the explainer */
13288typedef struct Explain Explain;
13289
13290/*
13291** A cursor is a pointer into a single BTree within a database file.
13292** The cursor can seek to a BTree entry with a particular key, or
13293** loop over all entries of the Btree.  You can also insert new BTree
13294** entries or retrieve the key or data from the entry that the cursor
13295** is currently pointing to.
13296**
13297** Every cursor that the virtual machine has open is represented by an
13298** instance of the following structure.
13299*/
13300struct VdbeCursor {
13301  BtCursor *pCursor;    /* The cursor structure of the backend */
13302  Btree *pBt;           /* Separate file holding temporary table */
13303  KeyInfo *pKeyInfo;    /* Info about index keys needed by index cursors */
13304  int iDb;              /* Index of cursor database in db->aDb[] (or -1) */
13305  int pseudoTableReg;   /* Register holding pseudotable content. */
13306  int nField;           /* Number of fields in the header */
13307  Bool zeroed;          /* True if zeroed out and ready for reuse */
13308  Bool rowidIsValid;    /* True if lastRowid is valid */
13309  Bool atFirst;         /* True if pointing to first entry */
13310  Bool useRandomRowid;  /* Generate new record numbers semi-randomly */
13311  Bool nullRow;         /* True if pointing to a row with no data */
13312  Bool deferredMoveto;  /* A call to sqlite3BtreeMoveto() is needed */
13313  Bool isTable;         /* True if a table requiring integer keys */
13314  Bool isIndex;         /* True if an index containing keys only - no data */
13315  Bool isOrdered;       /* True if the underlying table is BTREE_UNORDERED */
13316  Bool isSorter;        /* True if a new-style sorter */
13317  Bool multiPseudo;     /* Multi-register pseudo-cursor */
13318  sqlite3_vtab_cursor *pVtabCursor;  /* The cursor for a virtual table */
13319  const sqlite3_module *pModule;     /* Module for cursor pVtabCursor */
13320  i64 seqCount;         /* Sequence counter */
13321  i64 movetoTarget;     /* Argument to the deferred sqlite3BtreeMoveto() */
13322  i64 lastRowid;        /* Last rowid from a Next or NextIdx operation */
13323  VdbeSorter *pSorter;  /* Sorter object for OP_SorterOpen cursors */
13324
13325  /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or
13326  ** OP_IsUnique opcode on this cursor. */
13327  int seekResult;
13328
13329  /* Cached information about the header for the data record that the
13330  ** cursor is currently pointing to.  Only valid if cacheStatus matches
13331  ** Vdbe.cacheCtr.  Vdbe.cacheCtr will never take on the value of
13332  ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
13333  ** the cache is out of date.
13334  **
13335  ** aRow might point to (ephemeral) data for the current row, or it might
13336  ** be NULL.
13337  */
13338  u32 cacheStatus;      /* Cache is valid if this matches Vdbe.cacheCtr */
13339  int payloadSize;      /* Total number of bytes in the record */
13340  u32 *aType;           /* Type values for all entries in the record */
13341  u32 *aOffset;         /* Cached offsets to the start of each columns data */
13342  u8 *aRow;             /* Data for the current row, if all on one page */
13343};
13344typedef struct VdbeCursor VdbeCursor;
13345
13346/*
13347** When a sub-program is executed (OP_Program), a structure of this type
13348** is allocated to store the current value of the program counter, as
13349** well as the current memory cell array and various other frame specific
13350** values stored in the Vdbe struct. When the sub-program is finished,
13351** these values are copied back to the Vdbe from the VdbeFrame structure,
13352** restoring the state of the VM to as it was before the sub-program
13353** began executing.
13354**
13355** The memory for a VdbeFrame object is allocated and managed by a memory
13356** cell in the parent (calling) frame. When the memory cell is deleted or
13357** overwritten, the VdbeFrame object is not freed immediately. Instead, it
13358** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
13359** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
13360** this instead of deleting the VdbeFrame immediately is to avoid recursive
13361** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
13362** child frame are released.
13363**
13364** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
13365** set to NULL if the currently executing frame is the main program.
13366*/
13367typedef struct VdbeFrame VdbeFrame;
13368struct VdbeFrame {
13369  Vdbe *v;                /* VM this frame belongs to */
13370  VdbeFrame *pParent;     /* Parent of this frame, or NULL if parent is main */
13371  Op *aOp;                /* Program instructions for parent frame */
13372  Mem *aMem;              /* Array of memory cells for parent frame */
13373  u8 *aOnceFlag;          /* Array of OP_Once flags for parent frame */
13374  VdbeCursor **apCsr;     /* Array of Vdbe cursors for parent frame */
13375  void *token;            /* Copy of SubProgram.token */
13376  i64 lastRowid;          /* Last insert rowid (sqlite3.lastRowid) */
13377  int nCursor;            /* Number of entries in apCsr */
13378  int pc;                 /* Program Counter in parent (calling) frame */
13379  int nOp;                /* Size of aOp array */
13380  int nMem;               /* Number of entries in aMem */
13381  int nOnceFlag;          /* Number of entries in aOnceFlag */
13382  int nChildMem;          /* Number of memory cells for child frame */
13383  int nChildCsr;          /* Number of cursors for child frame */
13384  int nChange;            /* Statement changes (Vdbe.nChanges)     */
13385};
13386
13387#define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
13388
13389/*
13390** A value for VdbeCursor.cacheValid that means the cache is always invalid.
13391*/
13392#define CACHE_STALE 0
13393
13394/*
13395** Internally, the vdbe manipulates nearly all SQL values as Mem
13396** structures. Each Mem struct may cache multiple representations (string,
13397** integer etc.) of the same value.
13398*/
13399struct Mem {
13400  sqlite3 *db;        /* The associated database connection */
13401  char *z;            /* String or BLOB value */
13402  double r;           /* Real value */
13403  union {
13404    i64 i;              /* Integer value used when MEM_Int is set in flags */
13405    int nZero;          /* Used when bit MEM_Zero is set in flags */
13406    FuncDef *pDef;      /* Used only when flags==MEM_Agg */
13407    RowSet *pRowSet;    /* Used only when flags==MEM_RowSet */
13408    VdbeFrame *pFrame;  /* Used when flags==MEM_Frame */
13409  } u;
13410  int n;              /* Number of characters in string value, excluding '\0' */
13411  u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
13412  u8  type;           /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
13413  u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
13414#ifdef SQLITE_DEBUG
13415  Mem *pScopyFrom;    /* This Mem is a shallow copy of pScopyFrom */
13416  void *pFiller;      /* So that sizeof(Mem) is a multiple of 8 */
13417#endif
13418  void (*xDel)(void *);  /* If not null, call this function to delete Mem.z */
13419  char *zMalloc;      /* Dynamic buffer allocated by sqlite3_malloc() */
13420};
13421
13422/* One or more of the following flags are set to indicate the validOK
13423** representations of the value stored in the Mem struct.
13424**
13425** If the MEM_Null flag is set, then the value is an SQL NULL value.
13426** No other flags may be set in this case.
13427**
13428** If the MEM_Str flag is set then Mem.z points at a string representation.
13429** Usually this is encoded in the same unicode encoding as the main
13430** database (see below for exceptions). If the MEM_Term flag is also
13431** set, then the string is nul terminated. The MEM_Int and MEM_Real
13432** flags may coexist with the MEM_Str flag.
13433*/
13434#define MEM_Null      0x0001   /* Value is NULL */
13435#define MEM_Str       0x0002   /* Value is a string */
13436#define MEM_Int       0x0004   /* Value is an integer */
13437#define MEM_Real      0x0008   /* Value is a real number */
13438#define MEM_Blob      0x0010   /* Value is a BLOB */
13439#define MEM_RowSet    0x0020   /* Value is a RowSet object */
13440#define MEM_Frame     0x0040   /* Value is a VdbeFrame object */
13441#define MEM_Invalid   0x0080   /* Value is undefined */
13442#define MEM_Cleared   0x0100   /* NULL set by OP_Null, not from data */
13443#define MEM_TypeMask  0x01ff   /* Mask of type bits */
13444
13445
13446/* Whenever Mem contains a valid string or blob representation, one of
13447** the following flags must be set to determine the memory management
13448** policy for Mem.z.  The MEM_Term flag tells us whether or not the
13449** string is \000 or \u0000 terminated
13450*/
13451#define MEM_Term      0x0200   /* String rep is nul terminated */
13452#define MEM_Dyn       0x0400   /* Need to call sqliteFree() on Mem.z */
13453#define MEM_Static    0x0800   /* Mem.z points to a static string */
13454#define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */
13455#define MEM_Agg       0x2000   /* Mem.z points to an agg function context */
13456#define MEM_Zero      0x4000   /* Mem.i contains count of 0s appended to blob */
13457#ifdef SQLITE_OMIT_INCRBLOB
13458  #undef MEM_Zero
13459  #define MEM_Zero 0x0000
13460#endif
13461
13462/*
13463** Clear any existing type flags from a Mem and replace them with f
13464*/
13465#define MemSetTypeFlag(p, f) \
13466   ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
13467
13468/*
13469** Return true if a memory cell is not marked as invalid.  This macro
13470** is for use inside assert() statements only.
13471*/
13472#ifdef SQLITE_DEBUG
13473#define memIsValid(M)  ((M)->flags & MEM_Invalid)==0
13474#endif
13475
13476
13477/* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
13478** additional information about auxiliary information bound to arguments
13479** of the function.  This is used to implement the sqlite3_get_auxdata()
13480** and sqlite3_set_auxdata() APIs.  The "auxdata" is some auxiliary data
13481** that can be associated with a constant argument to a function.  This
13482** allows functions such as "regexp" to compile their constant regular
13483** expression argument once and reused the compiled code for multiple
13484** invocations.
13485*/
13486struct VdbeFunc {
13487  FuncDef *pFunc;               /* The definition of the function */
13488  int nAux;                     /* Number of entries allocated for apAux[] */
13489  struct AuxData {
13490    void *pAux;                   /* Aux data for the i-th argument */
13491    void (*xDelete)(void *);      /* Destructor for the aux data */
13492  } apAux[1];                   /* One slot for each function argument */
13493};
13494
13495/*
13496** The "context" argument for a installable function.  A pointer to an
13497** instance of this structure is the first argument to the routines used
13498** implement the SQL functions.
13499**
13500** There is a typedef for this structure in sqlite.h.  So all routines,
13501** even the public interface to SQLite, can use a pointer to this structure.
13502** But this file is the only place where the internal details of this
13503** structure are known.
13504**
13505** This structure is defined inside of vdbeInt.h because it uses substructures
13506** (Mem) which are only defined there.
13507*/
13508struct sqlite3_context {
13509  FuncDef *pFunc;       /* Pointer to function information.  MUST BE FIRST */
13510  VdbeFunc *pVdbeFunc;  /* Auxilary data, if created. */
13511  Mem s;                /* The return value is stored here */
13512  Mem *pMem;            /* Memory cell used to store aggregate context */
13513  CollSeq *pColl;       /* Collating sequence */
13514  int isError;          /* Error code returned by the function. */
13515  int skipFlag;         /* Skip skip accumulator loading if true */
13516};
13517
13518/*
13519** An Explain object accumulates indented output which is helpful
13520** in describing recursive data structures.
13521*/
13522struct Explain {
13523  Vdbe *pVdbe;       /* Attach the explanation to this Vdbe */
13524  StrAccum str;      /* The string being accumulated */
13525  int nIndent;       /* Number of elements in aIndent */
13526  u16 aIndent[100];  /* Levels of indentation */
13527  char zBase[100];   /* Initial space */
13528};
13529
13530/* A bitfield type for use inside of structures.  Always follow with :N where
13531** N is the number of bits.
13532*/
13533typedef unsigned bft;  /* Bit Field Type */
13534
13535/*
13536** An instance of the virtual machine.  This structure contains the complete
13537** state of the virtual machine.
13538**
13539** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
13540** is really a pointer to an instance of this structure.
13541**
13542** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
13543** any virtual table method invocations made by the vdbe program. It is
13544** set to 2 for xDestroy method calls and 1 for all other methods. This
13545** variable is used for two purposes: to allow xDestroy methods to execute
13546** "DROP TABLE" statements and to prevent some nasty side effects of
13547** malloc failure when SQLite is invoked recursively by a virtual table
13548** method function.
13549*/
13550struct Vdbe {
13551  sqlite3 *db;            /* The database connection that owns this statement */
13552  Op *aOp;                /* Space to hold the virtual machine's program */
13553  Mem *aMem;              /* The memory locations */
13554  Mem **apArg;            /* Arguments to currently executing user function */
13555  Mem *aColName;          /* Column names to return */
13556  Mem *pResultSet;        /* Pointer to an array of results */
13557  int nMem;               /* Number of memory locations currently allocated */
13558  int nOp;                /* Number of instructions in the program */
13559  int nOpAlloc;           /* Number of slots allocated for aOp[] */
13560  int nLabel;             /* Number of labels used */
13561  int *aLabel;            /* Space to hold the labels */
13562  u16 nResColumn;         /* Number of columns in one row of the result set */
13563  int nCursor;            /* Number of slots in apCsr[] */
13564  u32 magic;              /* Magic number for sanity checking */
13565  char *zErrMsg;          /* Error message written here */
13566  Vdbe *pPrev,*pNext;     /* Linked list of VDBEs with the same Vdbe.db */
13567  VdbeCursor **apCsr;     /* One element of this array for each open cursor */
13568  Mem *aVar;              /* Values for the OP_Variable opcode. */
13569  char **azVar;           /* Name of variables */
13570  ynVar nVar;             /* Number of entries in aVar[] */
13571  ynVar nzVar;            /* Number of entries in azVar[] */
13572  u32 cacheCtr;           /* VdbeCursor row cache generation counter */
13573  int pc;                 /* The program counter */
13574  int rc;                 /* Value to return */
13575  u8 errorAction;         /* Recovery action to do in case of an error */
13576  u8 minWriteFileFormat;  /* Minimum file format for writable database files */
13577  bft explain:2;          /* True if EXPLAIN present on SQL command */
13578  bft inVtabMethod:2;     /* See comments above */
13579  bft changeCntOn:1;      /* True to update the change-counter */
13580  bft expired:1;          /* True if the VM needs to be recompiled */
13581  bft runOnlyOnce:1;      /* Automatically expire on reset */
13582  bft usesStmtJournal:1;  /* True if uses a statement journal */
13583  bft readOnly:1;         /* True for read-only statements */
13584  bft isPrepareV2:1;      /* True if prepared with prepare_v2() */
13585  bft doingRerun:1;       /* True if rerunning after an auto-reprepare */
13586  int nChange;            /* Number of db changes made since last reset */
13587  yDbMask btreeMask;      /* Bitmask of db->aDb[] entries referenced */
13588  yDbMask lockMask;       /* Subset of btreeMask that requires a lock */
13589  int iStatement;         /* Statement number (or 0 if has not opened stmt) */
13590  int aCounter[3];        /* Counters used by sqlite3_stmt_status() */
13591#ifndef SQLITE_OMIT_TRACE
13592  i64 startTime;          /* Time when query started - used for profiling */
13593#endif
13594  i64 nFkConstraint;      /* Number of imm. FK constraints this VM */
13595  i64 nStmtDefCons;       /* Number of def. constraints when stmt started */
13596  char *zSql;             /* Text of the SQL statement that generated this */
13597  void *pFree;            /* Free this when deleting the vdbe */
13598#ifdef SQLITE_DEBUG
13599  FILE *trace;            /* Write an execution trace here, if not NULL */
13600#endif
13601#ifdef SQLITE_ENABLE_TREE_EXPLAIN
13602  Explain *pExplain;      /* The explainer */
13603  char *zExplain;         /* Explanation of data structures */
13604#endif
13605  VdbeFrame *pFrame;      /* Parent frame */
13606  VdbeFrame *pDelFrame;   /* List of frame objects to free on VM reset */
13607  int nFrame;             /* Number of frames in pFrame list */
13608  u32 expmask;            /* Binding to these vars invalidates VM */
13609  SubProgram *pProgram;   /* Linked list of all sub-programs used by VM */
13610  int nOnceFlag;          /* Size of array aOnceFlag[] */
13611  u8 *aOnceFlag;          /* Flags for OP_Once */
13612};
13613
13614/*
13615** The following are allowed values for Vdbe.magic
13616*/
13617#define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
13618#define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
13619#define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
13620#define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */
13621
13622/*
13623** Function prototypes
13624*/
13625SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
13626void sqliteVdbePopStack(Vdbe*,int);
13627SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
13628#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
13629SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
13630#endif
13631SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
13632SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
13633SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
13634SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
13635SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);
13636
13637int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
13638SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
13639SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor *, i64 *);
13640SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
13641SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
13642SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
13643SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
13644SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
13645SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
13646SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
13647SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
13648SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
13649SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
13650SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
13651SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
13652#ifdef SQLITE_OMIT_FLOATING_POINT
13653# define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
13654#else
13655SQLITE_PRIVATE   void sqlite3VdbeMemSetDouble(Mem*, double);
13656#endif
13657SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
13658SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
13659SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
13660SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
13661SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
13662SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
13663SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
13664SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
13665SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
13666SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
13667SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
13668SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
13669SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
13670SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
13671#define VdbeMemRelease(X)  \
13672  if((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame)) \
13673    sqlite3VdbeMemReleaseExternal(X);
13674SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
13675SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
13676SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
13677SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
13678SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
13679SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
13680SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem);
13681SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
13682
13683SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, VdbeCursor *);
13684SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
13685SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
13686SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *, int *);
13687SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *, const VdbeCursor *, int *);
13688SQLITE_PRIVATE int sqlite3VdbeSorterWrite(sqlite3 *, const VdbeCursor *, Mem *);
13689SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int *);
13690
13691#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
13692SQLITE_PRIVATE   void sqlite3VdbeEnter(Vdbe*);
13693SQLITE_PRIVATE   void sqlite3VdbeLeave(Vdbe*);
13694#else
13695# define sqlite3VdbeEnter(X)
13696# define sqlite3VdbeLeave(X)
13697#endif
13698
13699#ifdef SQLITE_DEBUG
13700SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
13701#endif
13702
13703#ifndef SQLITE_OMIT_FOREIGN_KEY
13704SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
13705#else
13706# define sqlite3VdbeCheckFk(p,i) 0
13707#endif
13708
13709SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
13710#ifdef SQLITE_DEBUG
13711SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
13712SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
13713#endif
13714SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
13715
13716#ifndef SQLITE_OMIT_INCRBLOB
13717SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
13718  #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
13719#else
13720  #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
13721  #define ExpandBlob(P) SQLITE_OK
13722#endif
13723
13724#endif /* !defined(_VDBEINT_H_) */
13725
13726/************** End of vdbeInt.h *********************************************/
13727/************** Continuing where we left off in status.c *********************/
13728
13729/*
13730** Variables in which to record status information.
13731*/
13732typedef struct sqlite3StatType sqlite3StatType;
13733static SQLITE_WSD struct sqlite3StatType {
13734  int nowValue[10];         /* Current value */
13735  int mxValue[10];          /* Maximum value */
13736} sqlite3Stat = { {0,}, {0,} };
13737
13738
13739/* The "wsdStat" macro will resolve to the status information
13740** state vector.  If writable static data is unsupported on the target,
13741** we have to locate the state vector at run-time.  In the more common
13742** case where writable static data is supported, wsdStat can refer directly
13743** to the "sqlite3Stat" state vector declared above.
13744*/
13745#ifdef SQLITE_OMIT_WSD
13746# define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
13747# define wsdStat x[0]
13748#else
13749# define wsdStatInit
13750# define wsdStat sqlite3Stat
13751#endif
13752
13753/*
13754** Return the current value of a status parameter.
13755*/
13756SQLITE_PRIVATE int sqlite3StatusValue(int op){
13757  wsdStatInit;
13758  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
13759  return wsdStat.nowValue[op];
13760}
13761
13762/*
13763** Add N to the value of a status record.  It is assumed that the
13764** caller holds appropriate locks.
13765*/
13766SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
13767  wsdStatInit;
13768  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
13769  wsdStat.nowValue[op] += N;
13770  if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
13771    wsdStat.mxValue[op] = wsdStat.nowValue[op];
13772  }
13773}
13774
13775/*
13776** Set the value of a status to X.
13777*/
13778SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
13779  wsdStatInit;
13780  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
13781  wsdStat.nowValue[op] = X;
13782  if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
13783    wsdStat.mxValue[op] = wsdStat.nowValue[op];
13784  }
13785}
13786
13787/*
13788** Query status information.
13789**
13790** This implementation assumes that reading or writing an aligned
13791** 32-bit integer is an atomic operation.  If that assumption is not true,
13792** then this routine is not threadsafe.
13793*/
13794SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
13795  wsdStatInit;
13796  if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
13797    return SQLITE_MISUSE_BKPT;
13798  }
13799  *pCurrent = wsdStat.nowValue[op];
13800  *pHighwater = wsdStat.mxValue[op];
13801  if( resetFlag ){
13802    wsdStat.mxValue[op] = wsdStat.nowValue[op];
13803  }
13804  return SQLITE_OK;
13805}
13806
13807/*
13808** Query status information for a single database connection
13809*/
13810SQLITE_API int sqlite3_db_status(
13811  sqlite3 *db,          /* The database connection whose status is desired */
13812  int op,               /* Status verb */
13813  int *pCurrent,        /* Write current value here */
13814  int *pHighwater,      /* Write high-water mark here */
13815  int resetFlag         /* Reset high-water mark if true */
13816){
13817  int rc = SQLITE_OK;   /* Return code */
13818  sqlite3_mutex_enter(db->mutex);
13819  switch( op ){
13820    case SQLITE_DBSTATUS_LOOKASIDE_USED: {
13821      *pCurrent = db->lookaside.nOut;
13822      *pHighwater = db->lookaside.mxOut;
13823      if( resetFlag ){
13824        db->lookaside.mxOut = db->lookaside.nOut;
13825      }
13826      break;
13827    }
13828
13829    case SQLITE_DBSTATUS_LOOKASIDE_HIT:
13830    case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
13831    case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
13832      testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
13833      testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
13834      testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
13835      assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
13836      assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
13837      *pCurrent = 0;
13838      *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
13839      if( resetFlag ){
13840        db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
13841      }
13842      break;
13843    }
13844
13845    /*
13846    ** Return an approximation for the amount of memory currently used
13847    ** by all pagers associated with the given database connection.  The
13848    ** highwater mark is meaningless and is returned as zero.
13849    */
13850    case SQLITE_DBSTATUS_CACHE_USED: {
13851      int totalUsed = 0;
13852      int i;
13853      sqlite3BtreeEnterAll(db);
13854      for(i=0; i<db->nDb; i++){
13855        Btree *pBt = db->aDb[i].pBt;
13856        if( pBt ){
13857          Pager *pPager = sqlite3BtreePager(pBt);
13858          totalUsed += sqlite3PagerMemUsed(pPager);
13859        }
13860      }
13861      sqlite3BtreeLeaveAll(db);
13862      *pCurrent = totalUsed;
13863      *pHighwater = 0;
13864      break;
13865    }
13866
13867    /*
13868    ** *pCurrent gets an accurate estimate of the amount of memory used
13869    ** to store the schema for all databases (main, temp, and any ATTACHed
13870    ** databases.  *pHighwater is set to zero.
13871    */
13872    case SQLITE_DBSTATUS_SCHEMA_USED: {
13873      int i;                      /* Used to iterate through schemas */
13874      int nByte = 0;              /* Used to accumulate return value */
13875
13876      sqlite3BtreeEnterAll(db);
13877      db->pnBytesFreed = &nByte;
13878      for(i=0; i<db->nDb; i++){
13879        Schema *pSchema = db->aDb[i].pSchema;
13880        if( ALWAYS(pSchema!=0) ){
13881          HashElem *p;
13882
13883          nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
13884              pSchema->tblHash.count
13885            + pSchema->trigHash.count
13886            + pSchema->idxHash.count
13887            + pSchema->fkeyHash.count
13888          );
13889          nByte += sqlite3MallocSize(pSchema->tblHash.ht);
13890          nByte += sqlite3MallocSize(pSchema->trigHash.ht);
13891          nByte += sqlite3MallocSize(pSchema->idxHash.ht);
13892          nByte += sqlite3MallocSize(pSchema->fkeyHash.ht);
13893
13894          for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
13895            sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
13896          }
13897          for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
13898            sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
13899          }
13900        }
13901      }
13902      db->pnBytesFreed = 0;
13903      sqlite3BtreeLeaveAll(db);
13904
13905      *pHighwater = 0;
13906      *pCurrent = nByte;
13907      break;
13908    }
13909
13910    /*
13911    ** *pCurrent gets an accurate estimate of the amount of memory used
13912    ** to store all prepared statements.
13913    ** *pHighwater is set to zero.
13914    */
13915    case SQLITE_DBSTATUS_STMT_USED: {
13916      struct Vdbe *pVdbe;         /* Used to iterate through VMs */
13917      int nByte = 0;              /* Used to accumulate return value */
13918
13919      db->pnBytesFreed = &nByte;
13920      for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
13921        sqlite3VdbeClearObject(db, pVdbe);
13922        sqlite3DbFree(db, pVdbe);
13923      }
13924      db->pnBytesFreed = 0;
13925
13926      *pHighwater = 0;
13927      *pCurrent = nByte;
13928
13929      break;
13930    }
13931
13932    /*
13933    ** Set *pCurrent to the total cache hits or misses encountered by all
13934    ** pagers the database handle is connected to. *pHighwater is always set
13935    ** to zero.
13936    */
13937    case SQLITE_DBSTATUS_CACHE_HIT:
13938    case SQLITE_DBSTATUS_CACHE_MISS:
13939    case SQLITE_DBSTATUS_CACHE_WRITE:{
13940      int i;
13941      int nRet = 0;
13942      assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
13943      assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
13944
13945      for(i=0; i<db->nDb; i++){
13946        if( db->aDb[i].pBt ){
13947          Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
13948          sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
13949        }
13950      }
13951      *pHighwater = 0;
13952      *pCurrent = nRet;
13953      break;
13954    }
13955
13956    default: {
13957      rc = SQLITE_ERROR;
13958    }
13959  }
13960  sqlite3_mutex_leave(db->mutex);
13961  return rc;
13962}
13963
13964/************** End of status.c **********************************************/
13965/************** Begin file date.c ********************************************/
13966/*
13967** 2003 October 31
13968**
13969** The author disclaims copyright to this source code.  In place of
13970** a legal notice, here is a blessing:
13971**
13972**    May you do good and not evil.
13973**    May you find forgiveness for yourself and forgive others.
13974**    May you share freely, never taking more than you give.
13975**
13976*************************************************************************
13977** This file contains the C functions that implement date and time
13978** functions for SQLite.
13979**
13980** There is only one exported symbol in this file - the function
13981** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
13982** All other code has file scope.
13983**
13984** SQLite processes all times and dates as Julian Day numbers.  The
13985** dates and times are stored as the number of days since noon
13986** in Greenwich on November 24, 4714 B.C. according to the Gregorian
13987** calendar system.
13988**
13989** 1970-01-01 00:00:00 is JD 2440587.5
13990** 2000-01-01 00:00:00 is JD 2451544.5
13991**
13992** This implemention requires years to be expressed as a 4-digit number
13993** which means that only dates between 0000-01-01 and 9999-12-31 can
13994** be represented, even though julian day numbers allow a much wider
13995** range of dates.
13996**
13997** The Gregorian calendar system is used for all dates and times,
13998** even those that predate the Gregorian calendar.  Historians usually
13999** use the Julian calendar for dates prior to 1582-10-15 and for some
14000** dates afterwards, depending on locale.  Beware of this difference.
14001**
14002** The conversion algorithms are implemented based on descriptions
14003** in the following text:
14004**
14005**      Jean Meeus
14006**      Astronomical Algorithms, 2nd Edition, 1998
14007**      ISBM 0-943396-61-1
14008**      Willmann-Bell, Inc
14009**      Richmond, Virginia (USA)
14010*/
14011/* #include <stdlib.h> */
14012/* #include <assert.h> */
14013#include <time.h>
14014
14015#ifndef SQLITE_OMIT_DATETIME_FUNCS
14016
14017
14018/*
14019** A structure for holding a single date and time.
14020*/
14021typedef struct DateTime DateTime;
14022struct DateTime {
14023  sqlite3_int64 iJD; /* The julian day number times 86400000 */
14024  int Y, M, D;       /* Year, month, and day */
14025  int h, m;          /* Hour and minutes */
14026  int tz;            /* Timezone offset in minutes */
14027  double s;          /* Seconds */
14028  char validYMD;     /* True (1) if Y,M,D are valid */
14029  char validHMS;     /* True (1) if h,m,s are valid */
14030  char validJD;      /* True (1) if iJD is valid */
14031  char validTZ;      /* True (1) if tz is valid */
14032};
14033
14034
14035/*
14036** Convert zDate into one or more integers.  Additional arguments
14037** come in groups of 5 as follows:
14038**
14039**       N       number of digits in the integer
14040**       min     minimum allowed value of the integer
14041**       max     maximum allowed value of the integer
14042**       nextC   first character after the integer
14043**       pVal    where to write the integers value.
14044**
14045** Conversions continue until one with nextC==0 is encountered.
14046** The function returns the number of successful conversions.
14047*/
14048static int getDigits(const char *zDate, ...){
14049  va_list ap;
14050  int val;
14051  int N;
14052  int min;
14053  int max;
14054  int nextC;
14055  int *pVal;
14056  int cnt = 0;
14057  va_start(ap, zDate);
14058  do{
14059    N = va_arg(ap, int);
14060    min = va_arg(ap, int);
14061    max = va_arg(ap, int);
14062    nextC = va_arg(ap, int);
14063    pVal = va_arg(ap, int*);
14064    val = 0;
14065    while( N-- ){
14066      if( !sqlite3Isdigit(*zDate) ){
14067        goto end_getDigits;
14068      }
14069      val = val*10 + *zDate - '0';
14070      zDate++;
14071    }
14072    if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
14073      goto end_getDigits;
14074    }
14075    *pVal = val;
14076    zDate++;
14077    cnt++;
14078  }while( nextC );
14079end_getDigits:
14080  va_end(ap);
14081  return cnt;
14082}
14083
14084/*
14085** Parse a timezone extension on the end of a date-time.
14086** The extension is of the form:
14087**
14088**        (+/-)HH:MM
14089**
14090** Or the "zulu" notation:
14091**
14092**        Z
14093**
14094** If the parse is successful, write the number of minutes
14095** of change in p->tz and return 0.  If a parser error occurs,
14096** return non-zero.
14097**
14098** A missing specifier is not considered an error.
14099*/
14100static int parseTimezone(const char *zDate, DateTime *p){
14101  int sgn = 0;
14102  int nHr, nMn;
14103  int c;
14104  while( sqlite3Isspace(*zDate) ){ zDate++; }
14105  p->tz = 0;
14106  c = *zDate;
14107  if( c=='-' ){
14108    sgn = -1;
14109  }else if( c=='+' ){
14110    sgn = +1;
14111  }else if( c=='Z' || c=='z' ){
14112    zDate++;
14113    goto zulu_time;
14114  }else{
14115    return c!=0;
14116  }
14117  zDate++;
14118  if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
14119    return 1;
14120  }
14121  zDate += 5;
14122  p->tz = sgn*(nMn + nHr*60);
14123zulu_time:
14124  while( sqlite3Isspace(*zDate) ){ zDate++; }
14125  return *zDate!=0;
14126}
14127
14128/*
14129** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
14130** The HH, MM, and SS must each be exactly 2 digits.  The
14131** fractional seconds FFFF can be one or more digits.
14132**
14133** Return 1 if there is a parsing error and 0 on success.
14134*/
14135static int parseHhMmSs(const char *zDate, DateTime *p){
14136  int h, m, s;
14137  double ms = 0.0;
14138  if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
14139    return 1;
14140  }
14141  zDate += 5;
14142  if( *zDate==':' ){
14143    zDate++;
14144    if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
14145      return 1;
14146    }
14147    zDate += 2;
14148    if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
14149      double rScale = 1.0;
14150      zDate++;
14151      while( sqlite3Isdigit(*zDate) ){
14152        ms = ms*10.0 + *zDate - '0';
14153        rScale *= 10.0;
14154        zDate++;
14155      }
14156      ms /= rScale;
14157    }
14158  }else{
14159    s = 0;
14160  }
14161  p->validJD = 0;
14162  p->validHMS = 1;
14163  p->h = h;
14164  p->m = m;
14165  p->s = s + ms;
14166  if( parseTimezone(zDate, p) ) return 1;
14167  p->validTZ = (p->tz!=0)?1:0;
14168  return 0;
14169}
14170
14171/*
14172** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
14173** that the YYYY-MM-DD is according to the Gregorian calendar.
14174**
14175** Reference:  Meeus page 61
14176*/
14177static void computeJD(DateTime *p){
14178  int Y, M, D, A, B, X1, X2;
14179
14180  if( p->validJD ) return;
14181  if( p->validYMD ){
14182    Y = p->Y;
14183    M = p->M;
14184    D = p->D;
14185  }else{
14186    Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
14187    M = 1;
14188    D = 1;
14189  }
14190  if( M<=2 ){
14191    Y--;
14192    M += 12;
14193  }
14194  A = Y/100;
14195  B = 2 - A + (A/4);
14196  X1 = 36525*(Y+4716)/100;
14197  X2 = 306001*(M+1)/10000;
14198  p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
14199  p->validJD = 1;
14200  if( p->validHMS ){
14201    p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
14202    if( p->validTZ ){
14203      p->iJD -= p->tz*60000;
14204      p->validYMD = 0;
14205      p->validHMS = 0;
14206      p->validTZ = 0;
14207    }
14208  }
14209}
14210
14211/*
14212** Parse dates of the form
14213**
14214**     YYYY-MM-DD HH:MM:SS.FFF
14215**     YYYY-MM-DD HH:MM:SS
14216**     YYYY-MM-DD HH:MM
14217**     YYYY-MM-DD
14218**
14219** Write the result into the DateTime structure and return 0
14220** on success and 1 if the input string is not a well-formed
14221** date.
14222*/
14223static int parseYyyyMmDd(const char *zDate, DateTime *p){
14224  int Y, M, D, neg;
14225
14226  if( zDate[0]=='-' ){
14227    zDate++;
14228    neg = 1;
14229  }else{
14230    neg = 0;
14231  }
14232  if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
14233    return 1;
14234  }
14235  zDate += 10;
14236  while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
14237  if( parseHhMmSs(zDate, p)==0 ){
14238    /* We got the time */
14239  }else if( *zDate==0 ){
14240    p->validHMS = 0;
14241  }else{
14242    return 1;
14243  }
14244  p->validJD = 0;
14245  p->validYMD = 1;
14246  p->Y = neg ? -Y : Y;
14247  p->M = M;
14248  p->D = D;
14249  if( p->validTZ ){
14250    computeJD(p);
14251  }
14252  return 0;
14253}
14254
14255/*
14256** Set the time to the current time reported by the VFS.
14257**
14258** Return the number of errors.
14259*/
14260static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
14261  sqlite3 *db = sqlite3_context_db_handle(context);
14262  if( sqlite3OsCurrentTimeInt64(db->pVfs, &p->iJD)==SQLITE_OK ){
14263    p->validJD = 1;
14264    return 0;
14265  }else{
14266    return 1;
14267  }
14268}
14269
14270/*
14271** Attempt to parse the given string into a Julian Day Number.  Return
14272** the number of errors.
14273**
14274** The following are acceptable forms for the input string:
14275**
14276**      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
14277**      DDDD.DD
14278**      now
14279**
14280** In the first form, the +/-HH:MM is always optional.  The fractional
14281** seconds extension (the ".FFF") is optional.  The seconds portion
14282** (":SS.FFF") is option.  The year and date can be omitted as long
14283** as there is a time string.  The time string can be omitted as long
14284** as there is a year and date.
14285*/
14286static int parseDateOrTime(
14287  sqlite3_context *context,
14288  const char *zDate,
14289  DateTime *p
14290){
14291  double r;
14292  if( parseYyyyMmDd(zDate,p)==0 ){
14293    return 0;
14294  }else if( parseHhMmSs(zDate, p)==0 ){
14295    return 0;
14296  }else if( sqlite3StrICmp(zDate,"now")==0){
14297    return setDateTimeToCurrent(context, p);
14298  }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
14299    p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
14300    p->validJD = 1;
14301    return 0;
14302  }
14303  return 1;
14304}
14305
14306/*
14307** Compute the Year, Month, and Day from the julian day number.
14308*/
14309static void computeYMD(DateTime *p){
14310  int Z, A, B, C, D, E, X1;
14311  if( p->validYMD ) return;
14312  if( !p->validJD ){
14313    p->Y = 2000;
14314    p->M = 1;
14315    p->D = 1;
14316  }else{
14317    Z = (int)((p->iJD + 43200000)/86400000);
14318    A = (int)((Z - 1867216.25)/36524.25);
14319    A = Z + 1 + A - (A/4);
14320    B = A + 1524;
14321    C = (int)((B - 122.1)/365.25);
14322    D = (36525*C)/100;
14323    E = (int)((B-D)/30.6001);
14324    X1 = (int)(30.6001*E);
14325    p->D = B - D - X1;
14326    p->M = E<14 ? E-1 : E-13;
14327    p->Y = p->M>2 ? C - 4716 : C - 4715;
14328  }
14329  p->validYMD = 1;
14330}
14331
14332/*
14333** Compute the Hour, Minute, and Seconds from the julian day number.
14334*/
14335static void computeHMS(DateTime *p){
14336  int s;
14337  if( p->validHMS ) return;
14338  computeJD(p);
14339  s = (int)((p->iJD + 43200000) % 86400000);
14340  p->s = s/1000.0;
14341  s = (int)p->s;
14342  p->s -= s;
14343  p->h = s/3600;
14344  s -= p->h*3600;
14345  p->m = s/60;
14346  p->s += s - p->m*60;
14347  p->validHMS = 1;
14348}
14349
14350/*
14351** Compute both YMD and HMS
14352*/
14353static void computeYMD_HMS(DateTime *p){
14354  computeYMD(p);
14355  computeHMS(p);
14356}
14357
14358/*
14359** Clear the YMD and HMS and the TZ
14360*/
14361static void clearYMD_HMS_TZ(DateTime *p){
14362  p->validYMD = 0;
14363  p->validHMS = 0;
14364  p->validTZ = 0;
14365}
14366
14367/*
14368** On recent Windows platforms, the localtime_s() function is available
14369** as part of the "Secure CRT". It is essentially equivalent to
14370** localtime_r() available under most POSIX platforms, except that the
14371** order of the parameters is reversed.
14372**
14373** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
14374**
14375** If the user has not indicated to use localtime_r() or localtime_s()
14376** already, check for an MSVC build environment that provides
14377** localtime_s().
14378*/
14379#if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
14380     defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
14381#define HAVE_LOCALTIME_S 1
14382#endif
14383
14384#ifndef SQLITE_OMIT_LOCALTIME
14385/*
14386** The following routine implements the rough equivalent of localtime_r()
14387** using whatever operating-system specific localtime facility that
14388** is available.  This routine returns 0 on success and
14389** non-zero on any kind of error.
14390**
14391** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
14392** routine will always fail.
14393*/
14394static int osLocaltime(time_t *t, struct tm *pTm){
14395  int rc;
14396#if (!defined(HAVE_LOCALTIME_R) || !HAVE_LOCALTIME_R) \
14397      && (!defined(HAVE_LOCALTIME_S) || !HAVE_LOCALTIME_S)
14398  struct tm *pX;
14399#if SQLITE_THREADSAFE>0
14400  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
14401#endif
14402  sqlite3_mutex_enter(mutex);
14403  pX = localtime(t);
14404#ifndef SQLITE_OMIT_BUILTIN_TEST
14405  if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
14406#endif
14407  if( pX ) *pTm = *pX;
14408  sqlite3_mutex_leave(mutex);
14409  rc = pX==0;
14410#else
14411#ifndef SQLITE_OMIT_BUILTIN_TEST
14412  if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
14413#endif
14414#if defined(HAVE_LOCALTIME_R) && HAVE_LOCALTIME_R
14415  rc = localtime_r(t, pTm)==0;
14416#else
14417  rc = localtime_s(pTm, t);
14418#endif /* HAVE_LOCALTIME_R */
14419#endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
14420  return rc;
14421}
14422#endif /* SQLITE_OMIT_LOCALTIME */
14423
14424
14425#ifndef SQLITE_OMIT_LOCALTIME
14426/*
14427** Compute the difference (in milliseconds) between localtime and UTC
14428** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
14429** return this value and set *pRc to SQLITE_OK.
14430**
14431** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
14432** is undefined in this case.
14433*/
14434static sqlite3_int64 localtimeOffset(
14435  DateTime *p,                    /* Date at which to calculate offset */
14436  sqlite3_context *pCtx,          /* Write error here if one occurs */
14437  int *pRc                        /* OUT: Error code. SQLITE_OK or ERROR */
14438){
14439  DateTime x, y;
14440  time_t t;
14441  struct tm sLocal;
14442
14443  /* Initialize the contents of sLocal to avoid a compiler warning. */
14444  memset(&sLocal, 0, sizeof(sLocal));
14445
14446  x = *p;
14447  computeYMD_HMS(&x);
14448  if( x.Y<1971 || x.Y>=2038 ){
14449    x.Y = 2000;
14450    x.M = 1;
14451    x.D = 1;
14452    x.h = 0;
14453    x.m = 0;
14454    x.s = 0.0;
14455  } else {
14456    int s = (int)(x.s + 0.5);
14457    x.s = s;
14458  }
14459  x.tz = 0;
14460  x.validJD = 0;
14461  computeJD(&x);
14462  t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
14463  if( osLocaltime(&t, &sLocal) ){
14464    sqlite3_result_error(pCtx, "local time unavailable", -1);
14465    *pRc = SQLITE_ERROR;
14466    return 0;
14467  }
14468  y.Y = sLocal.tm_year + 1900;
14469  y.M = sLocal.tm_mon + 1;
14470  y.D = sLocal.tm_mday;
14471  y.h = sLocal.tm_hour;
14472  y.m = sLocal.tm_min;
14473  y.s = sLocal.tm_sec;
14474  y.validYMD = 1;
14475  y.validHMS = 1;
14476  y.validJD = 0;
14477  y.validTZ = 0;
14478  computeJD(&y);
14479  *pRc = SQLITE_OK;
14480  return y.iJD - x.iJD;
14481}
14482#endif /* SQLITE_OMIT_LOCALTIME */
14483
14484/*
14485** Process a modifier to a date-time stamp.  The modifiers are
14486** as follows:
14487**
14488**     NNN days
14489**     NNN hours
14490**     NNN minutes
14491**     NNN.NNNN seconds
14492**     NNN months
14493**     NNN years
14494**     start of month
14495**     start of year
14496**     start of week
14497**     start of day
14498**     weekday N
14499**     unixepoch
14500**     localtime
14501**     utc
14502**
14503** Return 0 on success and 1 if there is any kind of error. If the error
14504** is in a system call (i.e. localtime()), then an error message is written
14505** to context pCtx. If the error is an unrecognized modifier, no error is
14506** written to pCtx.
14507*/
14508static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){
14509  int rc = 1;
14510  int n;
14511  double r;
14512  char *z, zBuf[30];
14513  z = zBuf;
14514  for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
14515    z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
14516  }
14517  z[n] = 0;
14518  switch( z[0] ){
14519#ifndef SQLITE_OMIT_LOCALTIME
14520    case 'l': {
14521      /*    localtime
14522      **
14523      ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
14524      ** show local time.
14525      */
14526      if( strcmp(z, "localtime")==0 ){
14527        computeJD(p);
14528        p->iJD += localtimeOffset(p, pCtx, &rc);
14529        clearYMD_HMS_TZ(p);
14530      }
14531      break;
14532    }
14533#endif
14534    case 'u': {
14535      /*
14536      **    unixepoch
14537      **
14538      ** Treat the current value of p->iJD as the number of
14539      ** seconds since 1970.  Convert to a real julian day number.
14540      */
14541      if( strcmp(z, "unixepoch")==0 && p->validJD ){
14542        p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
14543        clearYMD_HMS_TZ(p);
14544        rc = 0;
14545      }
14546#ifndef SQLITE_OMIT_LOCALTIME
14547      else if( strcmp(z, "utc")==0 ){
14548        sqlite3_int64 c1;
14549        computeJD(p);
14550        c1 = localtimeOffset(p, pCtx, &rc);
14551        if( rc==SQLITE_OK ){
14552          p->iJD -= c1;
14553          clearYMD_HMS_TZ(p);
14554          p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
14555        }
14556      }
14557#endif
14558      break;
14559    }
14560    case 'w': {
14561      /*
14562      **    weekday N
14563      **
14564      ** Move the date to the same time on the next occurrence of
14565      ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
14566      ** date is already on the appropriate weekday, this is a no-op.
14567      */
14568      if( strncmp(z, "weekday ", 8)==0
14569               && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
14570               && (n=(int)r)==r && n>=0 && r<7 ){
14571        sqlite3_int64 Z;
14572        computeYMD_HMS(p);
14573        p->validTZ = 0;
14574        p->validJD = 0;
14575        computeJD(p);
14576        Z = ((p->iJD + 129600000)/86400000) % 7;
14577        if( Z>n ) Z -= 7;
14578        p->iJD += (n - Z)*86400000;
14579        clearYMD_HMS_TZ(p);
14580        rc = 0;
14581      }
14582      break;
14583    }
14584    case 's': {
14585      /*
14586      **    start of TTTTT
14587      **
14588      ** Move the date backwards to the beginning of the current day,
14589      ** or month or year.
14590      */
14591      if( strncmp(z, "start of ", 9)!=0 ) break;
14592      z += 9;
14593      computeYMD(p);
14594      p->validHMS = 1;
14595      p->h = p->m = 0;
14596      p->s = 0.0;
14597      p->validTZ = 0;
14598      p->validJD = 0;
14599      if( strcmp(z,"month")==0 ){
14600        p->D = 1;
14601        rc = 0;
14602      }else if( strcmp(z,"year")==0 ){
14603        computeYMD(p);
14604        p->M = 1;
14605        p->D = 1;
14606        rc = 0;
14607      }else if( strcmp(z,"day")==0 ){
14608        rc = 0;
14609      }
14610      break;
14611    }
14612    case '+':
14613    case '-':
14614    case '0':
14615    case '1':
14616    case '2':
14617    case '3':
14618    case '4':
14619    case '5':
14620    case '6':
14621    case '7':
14622    case '8':
14623    case '9': {
14624      double rRounder;
14625      for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
14626      if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
14627        rc = 1;
14628        break;
14629      }
14630      if( z[n]==':' ){
14631        /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
14632        ** specified number of hours, minutes, seconds, and fractional seconds
14633        ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
14634        ** omitted.
14635        */
14636        const char *z2 = z;
14637        DateTime tx;
14638        sqlite3_int64 day;
14639        if( !sqlite3Isdigit(*z2) ) z2++;
14640        memset(&tx, 0, sizeof(tx));
14641        if( parseHhMmSs(z2, &tx) ) break;
14642        computeJD(&tx);
14643        tx.iJD -= 43200000;
14644        day = tx.iJD/86400000;
14645        tx.iJD -= day*86400000;
14646        if( z[0]=='-' ) tx.iJD = -tx.iJD;
14647        computeJD(p);
14648        clearYMD_HMS_TZ(p);
14649        p->iJD += tx.iJD;
14650        rc = 0;
14651        break;
14652      }
14653      z += n;
14654      while( sqlite3Isspace(*z) ) z++;
14655      n = sqlite3Strlen30(z);
14656      if( n>10 || n<3 ) break;
14657      if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
14658      computeJD(p);
14659      rc = 0;
14660      rRounder = r<0 ? -0.5 : +0.5;
14661      if( n==3 && strcmp(z,"day")==0 ){
14662        p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
14663      }else if( n==4 && strcmp(z,"hour")==0 ){
14664        p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
14665      }else if( n==6 && strcmp(z,"minute")==0 ){
14666        p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
14667      }else if( n==6 && strcmp(z,"second")==0 ){
14668        p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
14669      }else if( n==5 && strcmp(z,"month")==0 ){
14670        int x, y;
14671        computeYMD_HMS(p);
14672        p->M += (int)r;
14673        x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
14674        p->Y += x;
14675        p->M -= x*12;
14676        p->validJD = 0;
14677        computeJD(p);
14678        y = (int)r;
14679        if( y!=r ){
14680          p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
14681        }
14682      }else if( n==4 && strcmp(z,"year")==0 ){
14683        int y = (int)r;
14684        computeYMD_HMS(p);
14685        p->Y += y;
14686        p->validJD = 0;
14687        computeJD(p);
14688        if( y!=r ){
14689          p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
14690        }
14691      }else{
14692        rc = 1;
14693      }
14694      clearYMD_HMS_TZ(p);
14695      break;
14696    }
14697    default: {
14698      break;
14699    }
14700  }
14701  return rc;
14702}
14703
14704/*
14705** Process time function arguments.  argv[0] is a date-time stamp.
14706** argv[1] and following are modifiers.  Parse them all and write
14707** the resulting time into the DateTime structure p.  Return 0
14708** on success and 1 if there are any errors.
14709**
14710** If there are zero parameters (if even argv[0] is undefined)
14711** then assume a default value of "now" for argv[0].
14712*/
14713static int isDate(
14714  sqlite3_context *context,
14715  int argc,
14716  sqlite3_value **argv,
14717  DateTime *p
14718){
14719  int i;
14720  const unsigned char *z;
14721  int eType;
14722  memset(p, 0, sizeof(*p));
14723  if( argc==0 ){
14724    return setDateTimeToCurrent(context, p);
14725  }
14726  if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
14727                   || eType==SQLITE_INTEGER ){
14728    p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
14729    p->validJD = 1;
14730  }else{
14731    z = sqlite3_value_text(argv[0]);
14732    if( !z || parseDateOrTime(context, (char*)z, p) ){
14733      return 1;
14734    }
14735  }
14736  for(i=1; i<argc; i++){
14737    z = sqlite3_value_text(argv[i]);
14738    if( z==0 || parseModifier(context, (char*)z, p) ) return 1;
14739  }
14740  return 0;
14741}
14742
14743
14744/*
14745** The following routines implement the various date and time functions
14746** of SQLite.
14747*/
14748
14749/*
14750**    julianday( TIMESTRING, MOD, MOD, ...)
14751**
14752** Return the julian day number of the date specified in the arguments
14753*/
14754static void juliandayFunc(
14755  sqlite3_context *context,
14756  int argc,
14757  sqlite3_value **argv
14758){
14759  DateTime x;
14760  if( isDate(context, argc, argv, &x)==0 ){
14761    computeJD(&x);
14762    sqlite3_result_double(context, x.iJD/86400000.0);
14763  }
14764}
14765
14766/*
14767**    datetime( TIMESTRING, MOD, MOD, ...)
14768**
14769** Return YYYY-MM-DD HH:MM:SS
14770*/
14771static void datetimeFunc(
14772  sqlite3_context *context,
14773  int argc,
14774  sqlite3_value **argv
14775){
14776  DateTime x;
14777  if( isDate(context, argc, argv, &x)==0 ){
14778    char zBuf[100];
14779    computeYMD_HMS(&x);
14780    sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
14781                     x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
14782    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
14783  }
14784}
14785
14786/*
14787**    time( TIMESTRING, MOD, MOD, ...)
14788**
14789** Return HH:MM:SS
14790*/
14791static void timeFunc(
14792  sqlite3_context *context,
14793  int argc,
14794  sqlite3_value **argv
14795){
14796  DateTime x;
14797  if( isDate(context, argc, argv, &x)==0 ){
14798    char zBuf[100];
14799    computeHMS(&x);
14800    sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
14801    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
14802  }
14803}
14804
14805/*
14806**    date( TIMESTRING, MOD, MOD, ...)
14807**
14808** Return YYYY-MM-DD
14809*/
14810static void dateFunc(
14811  sqlite3_context *context,
14812  int argc,
14813  sqlite3_value **argv
14814){
14815  DateTime x;
14816  if( isDate(context, argc, argv, &x)==0 ){
14817    char zBuf[100];
14818    computeYMD(&x);
14819    sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
14820    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
14821  }
14822}
14823
14824/*
14825**    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
14826**
14827** Return a string described by FORMAT.  Conversions as follows:
14828**
14829**   %d  day of month
14830**   %f  ** fractional seconds  SS.SSS
14831**   %H  hour 00-24
14832**   %j  day of year 000-366
14833**   %J  ** Julian day number
14834**   %m  month 01-12
14835**   %M  minute 00-59
14836**   %s  seconds since 1970-01-01
14837**   %S  seconds 00-59
14838**   %w  day of week 0-6  sunday==0
14839**   %W  week of year 00-53
14840**   %Y  year 0000-9999
14841**   %%  %
14842*/
14843static void strftimeFunc(
14844  sqlite3_context *context,
14845  int argc,
14846  sqlite3_value **argv
14847){
14848  DateTime x;
14849  u64 n;
14850  size_t i,j;
14851  char *z;
14852  sqlite3 *db;
14853  const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
14854  char zBuf[100];
14855  if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
14856  db = sqlite3_context_db_handle(context);
14857  for(i=0, n=1; zFmt[i]; i++, n++){
14858    if( zFmt[i]=='%' ){
14859      switch( zFmt[i+1] ){
14860        case 'd':
14861        case 'H':
14862        case 'm':
14863        case 'M':
14864        case 'S':
14865        case 'W':
14866          n++;
14867          /* fall thru */
14868        case 'w':
14869        case '%':
14870          break;
14871        case 'f':
14872          n += 8;
14873          break;
14874        case 'j':
14875          n += 3;
14876          break;
14877        case 'Y':
14878          n += 8;
14879          break;
14880        case 's':
14881        case 'J':
14882          n += 50;
14883          break;
14884        default:
14885          return;  /* ERROR.  return a NULL */
14886      }
14887      i++;
14888    }
14889  }
14890  testcase( n==sizeof(zBuf)-1 );
14891  testcase( n==sizeof(zBuf) );
14892  testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
14893  testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
14894  if( n<sizeof(zBuf) ){
14895    z = zBuf;
14896  }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
14897    sqlite3_result_error_toobig(context);
14898    return;
14899  }else{
14900    z = sqlite3DbMallocRaw(db, (int)n);
14901    if( z==0 ){
14902      sqlite3_result_error_nomem(context);
14903      return;
14904    }
14905  }
14906  computeJD(&x);
14907  computeYMD_HMS(&x);
14908  for(i=j=0; zFmt[i]; i++){
14909    if( zFmt[i]!='%' ){
14910      z[j++] = zFmt[i];
14911    }else{
14912      i++;
14913      switch( zFmt[i] ){
14914        case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
14915        case 'f': {
14916          double s = x.s;
14917          if( s>59.999 ) s = 59.999;
14918          sqlite3_snprintf(7, &z[j],"%06.3f", s);
14919          j += sqlite3Strlen30(&z[j]);
14920          break;
14921        }
14922        case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
14923        case 'W': /* Fall thru */
14924        case 'j': {
14925          int nDay;             /* Number of days since 1st day of year */
14926          DateTime y = x;
14927          y.validJD = 0;
14928          y.M = 1;
14929          y.D = 1;
14930          computeJD(&y);
14931          nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
14932          if( zFmt[i]=='W' ){
14933            int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
14934            wd = (int)(((x.iJD+43200000)/86400000)%7);
14935            sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
14936            j += 2;
14937          }else{
14938            sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
14939            j += 3;
14940          }
14941          break;
14942        }
14943        case 'J': {
14944          sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
14945          j+=sqlite3Strlen30(&z[j]);
14946          break;
14947        }
14948        case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
14949        case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
14950        case 's': {
14951          sqlite3_snprintf(30,&z[j],"%lld",
14952                           (i64)(x.iJD/1000 - 21086676*(i64)10000));
14953          j += sqlite3Strlen30(&z[j]);
14954          break;
14955        }
14956        case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
14957        case 'w': {
14958          z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
14959          break;
14960        }
14961        case 'Y': {
14962          sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
14963          break;
14964        }
14965        default:   z[j++] = '%'; break;
14966      }
14967    }
14968  }
14969  z[j] = 0;
14970  sqlite3_result_text(context, z, -1,
14971                      z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
14972}
14973
14974/*
14975** current_time()
14976**
14977** This function returns the same value as time('now').
14978*/
14979static void ctimeFunc(
14980  sqlite3_context *context,
14981  int NotUsed,
14982  sqlite3_value **NotUsed2
14983){
14984  UNUSED_PARAMETER2(NotUsed, NotUsed2);
14985  timeFunc(context, 0, 0);
14986}
14987
14988/*
14989** current_date()
14990**
14991** This function returns the same value as date('now').
14992*/
14993static void cdateFunc(
14994  sqlite3_context *context,
14995  int NotUsed,
14996  sqlite3_value **NotUsed2
14997){
14998  UNUSED_PARAMETER2(NotUsed, NotUsed2);
14999  dateFunc(context, 0, 0);
15000}
15001
15002/*
15003** current_timestamp()
15004**
15005** This function returns the same value as datetime('now').
15006*/
15007static void ctimestampFunc(
15008  sqlite3_context *context,
15009  int NotUsed,
15010  sqlite3_value **NotUsed2
15011){
15012  UNUSED_PARAMETER2(NotUsed, NotUsed2);
15013  datetimeFunc(context, 0, 0);
15014}
15015#endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
15016
15017#ifdef SQLITE_OMIT_DATETIME_FUNCS
15018/*
15019** If the library is compiled to omit the full-scale date and time
15020** handling (to get a smaller binary), the following minimal version
15021** of the functions current_time(), current_date() and current_timestamp()
15022** are included instead. This is to support column declarations that
15023** include "DEFAULT CURRENT_TIME" etc.
15024**
15025** This function uses the C-library functions time(), gmtime()
15026** and strftime(). The format string to pass to strftime() is supplied
15027** as the user-data for the function.
15028*/
15029static void currentTimeFunc(
15030  sqlite3_context *context,
15031  int argc,
15032  sqlite3_value **argv
15033){
15034  time_t t;
15035  char *zFormat = (char *)sqlite3_user_data(context);
15036  sqlite3 *db;
15037  sqlite3_int64 iT;
15038  struct tm *pTm;
15039  struct tm sNow;
15040  char zBuf[20];
15041
15042  UNUSED_PARAMETER(argc);
15043  UNUSED_PARAMETER(argv);
15044
15045  db = sqlite3_context_db_handle(context);
15046  if( sqlite3OsCurrentTimeInt64(db->pVfs, &iT) ) return;
15047  t = iT/1000 - 10000*(sqlite3_int64)21086676;
15048#ifdef HAVE_GMTIME_R
15049  pTm = gmtime_r(&t, &sNow);
15050#else
15051  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
15052  pTm = gmtime(&t);
15053  if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
15054  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
15055#endif
15056  if( pTm ){
15057    strftime(zBuf, 20, zFormat, &sNow);
15058    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
15059  }
15060}
15061#endif
15062
15063/*
15064** This function registered all of the above C functions as SQL
15065** functions.  This should be the only routine in this file with
15066** external linkage.
15067*/
15068SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
15069  static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
15070#ifndef SQLITE_OMIT_DATETIME_FUNCS
15071    FUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
15072    FUNCTION(date,             -1, 0, 0, dateFunc      ),
15073    FUNCTION(time,             -1, 0, 0, timeFunc      ),
15074    FUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
15075    FUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
15076    FUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
15077    FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
15078    FUNCTION(current_date,      0, 0, 0, cdateFunc     ),
15079#else
15080    STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
15081    STR_FUNCTION(current_date,      0, "%Y-%m-%d",          0, currentTimeFunc),
15082    STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
15083#endif
15084  };
15085  int i;
15086  FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
15087  FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
15088
15089  for(i=0; i<ArraySize(aDateTimeFuncs); i++){
15090    sqlite3FuncDefInsert(pHash, &aFunc[i]);
15091  }
15092}
15093
15094/************** End of date.c ************************************************/
15095/************** Begin file os.c **********************************************/
15096/*
15097** 2005 November 29
15098**
15099** The author disclaims copyright to this source code.  In place of
15100** a legal notice, here is a blessing:
15101**
15102**    May you do good and not evil.
15103**    May you find forgiveness for yourself and forgive others.
15104**    May you share freely, never taking more than you give.
15105**
15106******************************************************************************
15107**
15108** This file contains OS interface code that is common to all
15109** architectures.
15110*/
15111#define _SQLITE_OS_C_ 1
15112#undef _SQLITE_OS_C_
15113
15114/*
15115** The default SQLite sqlite3_vfs implementations do not allocate
15116** memory (actually, os_unix.c allocates a small amount of memory
15117** from within OsOpen()), but some third-party implementations may.
15118** So we test the effects of a malloc() failing and the sqlite3OsXXX()
15119** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
15120**
15121** The following functions are instrumented for malloc() failure
15122** testing:
15123**
15124**     sqlite3OsRead()
15125**     sqlite3OsWrite()
15126**     sqlite3OsSync()
15127**     sqlite3OsFileSize()
15128**     sqlite3OsLock()
15129**     sqlite3OsCheckReservedLock()
15130**     sqlite3OsFileControl()
15131**     sqlite3OsShmMap()
15132**     sqlite3OsOpen()
15133**     sqlite3OsDelete()
15134**     sqlite3OsAccess()
15135**     sqlite3OsFullPathname()
15136**
15137*/
15138#if defined(SQLITE_TEST)
15139SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
15140  #define DO_OS_MALLOC_TEST(x)                                       \
15141  if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) {  \
15142    void *pTstAlloc = sqlite3Malloc(10);                             \
15143    if (!pTstAlloc) return SQLITE_IOERR_NOMEM;                       \
15144    sqlite3_free(pTstAlloc);                                         \
15145  }
15146#else
15147  #define DO_OS_MALLOC_TEST(x)
15148#endif
15149
15150/*
15151** The following routines are convenience wrappers around methods
15152** of the sqlite3_file object.  This is mostly just syntactic sugar. All
15153** of this would be completely automatic if SQLite were coded using
15154** C++ instead of plain old C.
15155*/
15156SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
15157  int rc = SQLITE_OK;
15158  if( pId->pMethods ){
15159    rc = pId->pMethods->xClose(pId);
15160    pId->pMethods = 0;
15161  }
15162  return rc;
15163}
15164SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
15165  DO_OS_MALLOC_TEST(id);
15166  return id->pMethods->xRead(id, pBuf, amt, offset);
15167}
15168SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
15169  DO_OS_MALLOC_TEST(id);
15170  return id->pMethods->xWrite(id, pBuf, amt, offset);
15171}
15172SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
15173  return id->pMethods->xTruncate(id, size);
15174}
15175SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
15176  DO_OS_MALLOC_TEST(id);
15177  return id->pMethods->xSync(id, flags);
15178}
15179SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
15180  DO_OS_MALLOC_TEST(id);
15181  return id->pMethods->xFileSize(id, pSize);
15182}
15183SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
15184  DO_OS_MALLOC_TEST(id);
15185  return id->pMethods->xLock(id, lockType);
15186}
15187SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
15188  return id->pMethods->xUnlock(id, lockType);
15189}
15190SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
15191  DO_OS_MALLOC_TEST(id);
15192  return id->pMethods->xCheckReservedLock(id, pResOut);
15193}
15194
15195/*
15196** Use sqlite3OsFileControl() when we are doing something that might fail
15197** and we need to know about the failures.  Use sqlite3OsFileControlHint()
15198** when simply tossing information over the wall to the VFS and we do not
15199** really care if the VFS receives and understands the information since it
15200** is only a hint and can be safely ignored.  The sqlite3OsFileControlHint()
15201** routine has no return value since the return value would be meaningless.
15202*/
15203SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
15204  DO_OS_MALLOC_TEST(id);
15205  return id->pMethods->xFileControl(id, op, pArg);
15206}
15207SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
15208  (void)id->pMethods->xFileControl(id, op, pArg);
15209}
15210
15211SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
15212  int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
15213  return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
15214}
15215SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
15216  return id->pMethods->xDeviceCharacteristics(id);
15217}
15218SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
15219  return id->pMethods->xShmLock(id, offset, n, flags);
15220}
15221SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
15222  id->pMethods->xShmBarrier(id);
15223}
15224SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
15225  return id->pMethods->xShmUnmap(id, deleteFlag);
15226}
15227SQLITE_PRIVATE int sqlite3OsShmMap(
15228  sqlite3_file *id,               /* Database file handle */
15229  int iPage,
15230  int pgsz,
15231  int bExtend,                    /* True to extend file if necessary */
15232  void volatile **pp              /* OUT: Pointer to mapping */
15233){
15234  DO_OS_MALLOC_TEST(id);
15235  return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
15236}
15237
15238#if SQLITE_MAX_MMAP_SIZE>0
15239/* The real implementation of xFetch and xUnfetch */
15240SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
15241  DO_OS_MALLOC_TEST(id);
15242  return id->pMethods->xFetch(id, iOff, iAmt, pp);
15243}
15244SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
15245  return id->pMethods->xUnfetch(id, iOff, p);
15246}
15247#else
15248/* No-op stubs to use when memory-mapped I/O is disabled */
15249SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
15250  *pp = 0;
15251  return SQLITE_OK;
15252}
15253SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
15254  return SQLITE_OK;
15255}
15256#endif
15257
15258/*
15259** The next group of routines are convenience wrappers around the
15260** VFS methods.
15261*/
15262SQLITE_PRIVATE int sqlite3OsOpen(
15263  sqlite3_vfs *pVfs,
15264  const char *zPath,
15265  sqlite3_file *pFile,
15266  int flags,
15267  int *pFlagsOut
15268){
15269  int rc;
15270  DO_OS_MALLOC_TEST(0);
15271  /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
15272  ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
15273  ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
15274  ** reaching the VFS. */
15275  rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
15276  assert( rc==SQLITE_OK || pFile->pMethods==0 );
15277  return rc;
15278}
15279SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
15280  DO_OS_MALLOC_TEST(0);
15281  assert( dirSync==0 || dirSync==1 );
15282  return pVfs->xDelete(pVfs, zPath, dirSync);
15283}
15284SQLITE_PRIVATE int sqlite3OsAccess(
15285  sqlite3_vfs *pVfs,
15286  const char *zPath,
15287  int flags,
15288  int *pResOut
15289){
15290  DO_OS_MALLOC_TEST(0);
15291  return pVfs->xAccess(pVfs, zPath, flags, pResOut);
15292}
15293SQLITE_PRIVATE int sqlite3OsFullPathname(
15294  sqlite3_vfs *pVfs,
15295  const char *zPath,
15296  int nPathOut,
15297  char *zPathOut
15298){
15299  DO_OS_MALLOC_TEST(0);
15300  zPathOut[0] = 0;
15301  return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
15302}
15303#ifndef SQLITE_OMIT_LOAD_EXTENSION
15304SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
15305  return pVfs->xDlOpen(pVfs, zPath);
15306}
15307SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
15308  pVfs->xDlError(pVfs, nByte, zBufOut);
15309}
15310SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
15311  return pVfs->xDlSym(pVfs, pHdle, zSym);
15312}
15313SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
15314  pVfs->xDlClose(pVfs, pHandle);
15315}
15316#endif /* SQLITE_OMIT_LOAD_EXTENSION */
15317SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
15318  return pVfs->xRandomness(pVfs, nByte, zBufOut);
15319}
15320SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
15321  return pVfs->xSleep(pVfs, nMicro);
15322}
15323SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
15324  int rc;
15325  /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
15326  ** method to get the current date and time if that method is available
15327  ** (if iVersion is 2 or greater and the function pointer is not NULL) and
15328  ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
15329  ** unavailable.
15330  */
15331  if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
15332    rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
15333  }else{
15334    double r;
15335    rc = pVfs->xCurrentTime(pVfs, &r);
15336    *pTimeOut = (sqlite3_int64)(r*86400000.0);
15337  }
15338  return rc;
15339}
15340
15341SQLITE_PRIVATE int sqlite3OsOpenMalloc(
15342  sqlite3_vfs *pVfs,
15343  const char *zFile,
15344  sqlite3_file **ppFile,
15345  int flags,
15346  int *pOutFlags
15347){
15348  int rc = SQLITE_NOMEM;
15349  sqlite3_file *pFile;
15350  pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
15351  if( pFile ){
15352    rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
15353    if( rc!=SQLITE_OK ){
15354      sqlite3_free(pFile);
15355    }else{
15356      *ppFile = pFile;
15357    }
15358  }
15359  return rc;
15360}
15361SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
15362  int rc = SQLITE_OK;
15363  assert( pFile );
15364  rc = sqlite3OsClose(pFile);
15365  sqlite3_free(pFile);
15366  return rc;
15367}
15368
15369/*
15370** This function is a wrapper around the OS specific implementation of
15371** sqlite3_os_init(). The purpose of the wrapper is to provide the
15372** ability to simulate a malloc failure, so that the handling of an
15373** error in sqlite3_os_init() by the upper layers can be tested.
15374*/
15375SQLITE_PRIVATE int sqlite3OsInit(void){
15376  void *p = sqlite3_malloc(10);
15377  if( p==0 ) return SQLITE_NOMEM;
15378  sqlite3_free(p);
15379  return sqlite3_os_init();
15380}
15381
15382/*
15383** The list of all registered VFS implementations.
15384*/
15385static sqlite3_vfs * SQLITE_WSD vfsList = 0;
15386#define vfsList GLOBAL(sqlite3_vfs *, vfsList)
15387
15388/*
15389** Locate a VFS by name.  If no name is given, simply return the
15390** first VFS on the list.
15391*/
15392SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
15393  sqlite3_vfs *pVfs = 0;
15394#if SQLITE_THREADSAFE
15395  sqlite3_mutex *mutex;
15396#endif
15397#ifndef SQLITE_OMIT_AUTOINIT
15398  int rc = sqlite3_initialize();
15399  if( rc ) return 0;
15400#endif
15401#if SQLITE_THREADSAFE
15402  mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
15403#endif
15404  sqlite3_mutex_enter(mutex);
15405  for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
15406    if( zVfs==0 ) break;
15407    if( strcmp(zVfs, pVfs->zName)==0 ) break;
15408  }
15409  sqlite3_mutex_leave(mutex);
15410  return pVfs;
15411}
15412
15413/*
15414** Unlink a VFS from the linked list
15415*/
15416static void vfsUnlink(sqlite3_vfs *pVfs){
15417  assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
15418  if( pVfs==0 ){
15419    /* No-op */
15420  }else if( vfsList==pVfs ){
15421    vfsList = pVfs->pNext;
15422  }else if( vfsList ){
15423    sqlite3_vfs *p = vfsList;
15424    while( p->pNext && p->pNext!=pVfs ){
15425      p = p->pNext;
15426    }
15427    if( p->pNext==pVfs ){
15428      p->pNext = pVfs->pNext;
15429    }
15430  }
15431}
15432
15433/*
15434** Register a VFS with the system.  It is harmless to register the same
15435** VFS multiple times.  The new VFS becomes the default if makeDflt is
15436** true.
15437*/
15438SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
15439  MUTEX_LOGIC(sqlite3_mutex *mutex;)
15440#ifndef SQLITE_OMIT_AUTOINIT
15441  int rc = sqlite3_initialize();
15442  if( rc ) return rc;
15443#endif
15444  MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
15445  sqlite3_mutex_enter(mutex);
15446  vfsUnlink(pVfs);
15447  if( makeDflt || vfsList==0 ){
15448    pVfs->pNext = vfsList;
15449    vfsList = pVfs;
15450  }else{
15451    pVfs->pNext = vfsList->pNext;
15452    vfsList->pNext = pVfs;
15453  }
15454  assert(vfsList);
15455  sqlite3_mutex_leave(mutex);
15456  return SQLITE_OK;
15457}
15458
15459/*
15460** Unregister a VFS so that it is no longer accessible.
15461*/
15462SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
15463#if SQLITE_THREADSAFE
15464  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
15465#endif
15466  sqlite3_mutex_enter(mutex);
15467  vfsUnlink(pVfs);
15468  sqlite3_mutex_leave(mutex);
15469  return SQLITE_OK;
15470}
15471
15472/************** End of os.c **************************************************/
15473/************** Begin file fault.c *******************************************/
15474/*
15475** 2008 Jan 22
15476**
15477** The author disclaims copyright to this source code.  In place of
15478** a legal notice, here is a blessing:
15479**
15480**    May you do good and not evil.
15481**    May you find forgiveness for yourself and forgive others.
15482**    May you share freely, never taking more than you give.
15483**
15484*************************************************************************
15485**
15486** This file contains code to support the concept of "benign"
15487** malloc failures (when the xMalloc() or xRealloc() method of the
15488** sqlite3_mem_methods structure fails to allocate a block of memory
15489** and returns 0).
15490**
15491** Most malloc failures are non-benign. After they occur, SQLite
15492** abandons the current operation and returns an error code (usually
15493** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
15494** fatal. For example, if a malloc fails while resizing a hash table, this
15495** is completely recoverable simply by not carrying out the resize. The
15496** hash table will continue to function normally.  So a malloc failure
15497** during a hash table resize is a benign fault.
15498*/
15499
15500
15501#ifndef SQLITE_OMIT_BUILTIN_TEST
15502
15503/*
15504** Global variables.
15505*/
15506typedef struct BenignMallocHooks BenignMallocHooks;
15507static SQLITE_WSD struct BenignMallocHooks {
15508  void (*xBenignBegin)(void);
15509  void (*xBenignEnd)(void);
15510} sqlite3Hooks = { 0, 0 };
15511
15512/* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
15513** structure.  If writable static data is unsupported on the target,
15514** we have to locate the state vector at run-time.  In the more common
15515** case where writable static data is supported, wsdHooks can refer directly
15516** to the "sqlite3Hooks" state vector declared above.
15517*/
15518#ifdef SQLITE_OMIT_WSD
15519# define wsdHooksInit \
15520  BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
15521# define wsdHooks x[0]
15522#else
15523# define wsdHooksInit
15524# define wsdHooks sqlite3Hooks
15525#endif
15526
15527
15528/*
15529** Register hooks to call when sqlite3BeginBenignMalloc() and
15530** sqlite3EndBenignMalloc() are called, respectively.
15531*/
15532SQLITE_PRIVATE void sqlite3BenignMallocHooks(
15533  void (*xBenignBegin)(void),
15534  void (*xBenignEnd)(void)
15535){
15536  wsdHooksInit;
15537  wsdHooks.xBenignBegin = xBenignBegin;
15538  wsdHooks.xBenignEnd = xBenignEnd;
15539}
15540
15541/*
15542** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
15543** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
15544** indicates that subsequent malloc failures are non-benign.
15545*/
15546SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
15547  wsdHooksInit;
15548  if( wsdHooks.xBenignBegin ){
15549    wsdHooks.xBenignBegin();
15550  }
15551}
15552SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
15553  wsdHooksInit;
15554  if( wsdHooks.xBenignEnd ){
15555    wsdHooks.xBenignEnd();
15556  }
15557}
15558
15559#endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
15560
15561/************** End of fault.c ***********************************************/
15562/************** Begin file mem0.c ********************************************/
15563/*
15564** 2008 October 28
15565**
15566** The author disclaims copyright to this source code.  In place of
15567** a legal notice, here is a blessing:
15568**
15569**    May you do good and not evil.
15570**    May you find forgiveness for yourself and forgive others.
15571**    May you share freely, never taking more than you give.
15572**
15573*************************************************************************
15574**
15575** This file contains a no-op memory allocation drivers for use when
15576** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented
15577** here always fail.  SQLite will not operate with these drivers.  These
15578** are merely placeholders.  Real drivers must be substituted using
15579** sqlite3_config() before SQLite will operate.
15580*/
15581
15582/*
15583** This version of the memory allocator is the default.  It is
15584** used when no other memory allocator is specified using compile-time
15585** macros.
15586*/
15587#ifdef SQLITE_ZERO_MALLOC
15588
15589/*
15590** No-op versions of all memory allocation routines
15591*/
15592static void *sqlite3MemMalloc(int nByte){ return 0; }
15593static void sqlite3MemFree(void *pPrior){ return; }
15594static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
15595static int sqlite3MemSize(void *pPrior){ return 0; }
15596static int sqlite3MemRoundup(int n){ return n; }
15597static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
15598static void sqlite3MemShutdown(void *NotUsed){ return; }
15599
15600/*
15601** This routine is the only routine in this file with external linkage.
15602**
15603** Populate the low-level memory allocation function pointers in
15604** sqlite3GlobalConfig.m with pointers to the routines in this file.
15605*/
15606SQLITE_PRIVATE void sqlite3MemSetDefault(void){
15607  static const sqlite3_mem_methods defaultMethods = {
15608     sqlite3MemMalloc,
15609     sqlite3MemFree,
15610     sqlite3MemRealloc,
15611     sqlite3MemSize,
15612     sqlite3MemRoundup,
15613     sqlite3MemInit,
15614     sqlite3MemShutdown,
15615     0
15616  };
15617  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
15618}
15619
15620#endif /* SQLITE_ZERO_MALLOC */
15621
15622/************** End of mem0.c ************************************************/
15623/************** Begin file mem1.c ********************************************/
15624/*
15625** 2007 August 14
15626**
15627** The author disclaims copyright to this source code.  In place of
15628** a legal notice, here is a blessing:
15629**
15630**    May you do good and not evil.
15631**    May you find forgiveness for yourself and forgive others.
15632**    May you share freely, never taking more than you give.
15633**
15634*************************************************************************
15635**
15636** This file contains low-level memory allocation drivers for when
15637** SQLite will use the standard C-library malloc/realloc/free interface
15638** to obtain the memory it needs.
15639**
15640** This file contains implementations of the low-level memory allocation
15641** routines specified in the sqlite3_mem_methods object.  The content of
15642** this file is only used if SQLITE_SYSTEM_MALLOC is defined.  The
15643** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
15644** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined.  The
15645** default configuration is to use memory allocation routines in this
15646** file.
15647**
15648** C-preprocessor macro summary:
15649**
15650**    HAVE_MALLOC_USABLE_SIZE     The configure script sets this symbol if
15651**                                the malloc_usable_size() interface exists
15652**                                on the target platform.  Or, this symbol
15653**                                can be set manually, if desired.
15654**                                If an equivalent interface exists by
15655**                                a different name, using a separate -D
15656**                                option to rename it.
15657**
15658**    SQLITE_WITHOUT_ZONEMALLOC   Some older macs lack support for the zone
15659**                                memory allocator.  Set this symbol to enable
15660**                                building on older macs.
15661**
15662**    SQLITE_WITHOUT_MSIZE        Set this symbol to disable the use of
15663**                                _msize() on windows systems.  This might
15664**                                be necessary when compiling for Delphi,
15665**                                for example.
15666*/
15667
15668/*
15669** This version of the memory allocator is the default.  It is
15670** used when no other memory allocator is specified using compile-time
15671** macros.
15672*/
15673#ifdef SQLITE_SYSTEM_MALLOC
15674
15675/*
15676** The MSVCRT has malloc_usable_size() but it is called _msize().
15677** The use of _msize() is automatic, but can be disabled by compiling
15678** with -DSQLITE_WITHOUT_MSIZE
15679*/
15680#if defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
15681# define SQLITE_MALLOCSIZE _msize
15682#endif
15683
15684#if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
15685
15686/*
15687** Use the zone allocator available on apple products unless the
15688** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
15689*/
15690#include <sys/sysctl.h>
15691#include <malloc/malloc.h>
15692#include <libkern/OSAtomic.h>
15693static malloc_zone_t* _sqliteZone_;
15694#define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
15695#define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
15696#define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
15697#define SQLITE_MALLOCSIZE(x) \
15698        (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
15699
15700#else /* if not __APPLE__ */
15701
15702/*
15703** Use standard C library malloc and free on non-Apple systems.
15704** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
15705*/
15706#define SQLITE_MALLOC(x)    malloc(x)
15707#define SQLITE_FREE(x)      free(x)
15708#define SQLITE_REALLOC(x,y) realloc((x),(y))
15709
15710#if (defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)) \
15711      || (defined(HAVE_MALLOC_H) && defined(HAVE_MALLOC_USABLE_SIZE))
15712# include <malloc.h>    /* Needed for malloc_usable_size on linux */
15713#endif
15714#ifdef HAVE_MALLOC_USABLE_SIZE
15715# ifndef SQLITE_MALLOCSIZE
15716#  define SQLITE_MALLOCSIZE(x) malloc_usable_size(x)
15717# endif
15718#else
15719# undef SQLITE_MALLOCSIZE
15720#endif
15721
15722#endif /* __APPLE__ or not __APPLE__ */
15723
15724/*
15725** Like malloc(), but remember the size of the allocation
15726** so that we can find it later using sqlite3MemSize().
15727**
15728** For this low-level routine, we are guaranteed that nByte>0 because
15729** cases of nByte<=0 will be intercepted and dealt with by higher level
15730** routines.
15731*/
15732static void *sqlite3MemMalloc(int nByte){
15733#ifdef SQLITE_MALLOCSIZE
15734  void *p = SQLITE_MALLOC( nByte );
15735  if( p==0 ){
15736    testcase( sqlite3GlobalConfig.xLog!=0 );
15737    sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
15738  }
15739  return p;
15740#else
15741  sqlite3_int64 *p;
15742  assert( nByte>0 );
15743  nByte = ROUND8(nByte);
15744  p = SQLITE_MALLOC( nByte+8 );
15745  if( p ){
15746    p[0] = nByte;
15747    p++;
15748  }else{
15749    testcase( sqlite3GlobalConfig.xLog!=0 );
15750    sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
15751  }
15752  return (void *)p;
15753#endif
15754}
15755
15756/*
15757** Like free() but works for allocations obtained from sqlite3MemMalloc()
15758** or sqlite3MemRealloc().
15759**
15760** For this low-level routine, we already know that pPrior!=0 since
15761** cases where pPrior==0 will have been intecepted and dealt with
15762** by higher-level routines.
15763*/
15764static void sqlite3MemFree(void *pPrior){
15765#ifdef SQLITE_MALLOCSIZE
15766  SQLITE_FREE(pPrior);
15767#else
15768  sqlite3_int64 *p = (sqlite3_int64*)pPrior;
15769  assert( pPrior!=0 );
15770  p--;
15771  SQLITE_FREE(p);
15772#endif
15773}
15774
15775/*
15776** Report the allocated size of a prior return from xMalloc()
15777** or xRealloc().
15778*/
15779static int sqlite3MemSize(void *pPrior){
15780#ifdef SQLITE_MALLOCSIZE
15781  return pPrior ? (int)SQLITE_MALLOCSIZE(pPrior) : 0;
15782#else
15783  sqlite3_int64 *p;
15784  if( pPrior==0 ) return 0;
15785  p = (sqlite3_int64*)pPrior;
15786  p--;
15787  return (int)p[0];
15788#endif
15789}
15790
15791/*
15792** Like realloc().  Resize an allocation previously obtained from
15793** sqlite3MemMalloc().
15794**
15795** For this low-level interface, we know that pPrior!=0.  Cases where
15796** pPrior==0 while have been intercepted by higher-level routine and
15797** redirected to xMalloc.  Similarly, we know that nByte>0 becauses
15798** cases where nByte<=0 will have been intercepted by higher-level
15799** routines and redirected to xFree.
15800*/
15801static void *sqlite3MemRealloc(void *pPrior, int nByte){
15802#ifdef SQLITE_MALLOCSIZE
15803  void *p = SQLITE_REALLOC(pPrior, nByte);
15804  if( p==0 ){
15805    testcase( sqlite3GlobalConfig.xLog!=0 );
15806    sqlite3_log(SQLITE_NOMEM,
15807      "failed memory resize %u to %u bytes",
15808      SQLITE_MALLOCSIZE(pPrior), nByte);
15809  }
15810  return p;
15811#else
15812  sqlite3_int64 *p = (sqlite3_int64*)pPrior;
15813  assert( pPrior!=0 && nByte>0 );
15814  assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
15815  p--;
15816  p = SQLITE_REALLOC(p, nByte+8 );
15817  if( p ){
15818    p[0] = nByte;
15819    p++;
15820  }else{
15821    testcase( sqlite3GlobalConfig.xLog!=0 );
15822    sqlite3_log(SQLITE_NOMEM,
15823      "failed memory resize %u to %u bytes",
15824      sqlite3MemSize(pPrior), nByte);
15825  }
15826  return (void*)p;
15827#endif
15828}
15829
15830/*
15831** Round up a request size to the next valid allocation size.
15832*/
15833static int sqlite3MemRoundup(int n){
15834  return ROUND8(n);
15835}
15836
15837/*
15838** Initialize this module.
15839*/
15840static int sqlite3MemInit(void *NotUsed){
15841#if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
15842  int cpuCount;
15843  size_t len;
15844  if( _sqliteZone_ ){
15845    return SQLITE_OK;
15846  }
15847  len = sizeof(cpuCount);
15848  /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
15849  sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
15850  if( cpuCount>1 ){
15851    /* defer MT decisions to system malloc */
15852    _sqliteZone_ = malloc_default_zone();
15853  }else{
15854    /* only 1 core, use our own zone to contention over global locks,
15855    ** e.g. we have our own dedicated locks */
15856    bool success;
15857    malloc_zone_t* newzone = malloc_create_zone(4096, 0);
15858    malloc_set_zone_name(newzone, "Sqlite_Heap");
15859    do{
15860      success = OSAtomicCompareAndSwapPtrBarrier(NULL, newzone,
15861                                 (void * volatile *)&_sqliteZone_);
15862    }while(!_sqliteZone_);
15863    if( !success ){
15864      /* somebody registered a zone first */
15865      malloc_destroy_zone(newzone);
15866    }
15867  }
15868#endif
15869  UNUSED_PARAMETER(NotUsed);
15870  return SQLITE_OK;
15871}
15872
15873/*
15874** Deinitialize this module.
15875*/
15876static void sqlite3MemShutdown(void *NotUsed){
15877  UNUSED_PARAMETER(NotUsed);
15878  return;
15879}
15880
15881/*
15882** This routine is the only routine in this file with external linkage.
15883**
15884** Populate the low-level memory allocation function pointers in
15885** sqlite3GlobalConfig.m with pointers to the routines in this file.
15886*/
15887SQLITE_PRIVATE void sqlite3MemSetDefault(void){
15888  static const sqlite3_mem_methods defaultMethods = {
15889     sqlite3MemMalloc,
15890     sqlite3MemFree,
15891     sqlite3MemRealloc,
15892     sqlite3MemSize,
15893     sqlite3MemRoundup,
15894     sqlite3MemInit,
15895     sqlite3MemShutdown,
15896     0
15897  };
15898  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
15899}
15900
15901#endif /* SQLITE_SYSTEM_MALLOC */
15902
15903/************** End of mem1.c ************************************************/
15904/************** Begin file mem2.c ********************************************/
15905/*
15906** 2007 August 15
15907**
15908** The author disclaims copyright to this source code.  In place of
15909** a legal notice, here is a blessing:
15910**
15911**    May you do good and not evil.
15912**    May you find forgiveness for yourself and forgive others.
15913**    May you share freely, never taking more than you give.
15914**
15915*************************************************************************
15916**
15917** This file contains low-level memory allocation drivers for when
15918** SQLite will use the standard C-library malloc/realloc/free interface
15919** to obtain the memory it needs while adding lots of additional debugging
15920** information to each allocation in order to help detect and fix memory
15921** leaks and memory usage errors.
15922**
15923** This file contains implementations of the low-level memory allocation
15924** routines specified in the sqlite3_mem_methods object.
15925*/
15926
15927/*
15928** This version of the memory allocator is used only if the
15929** SQLITE_MEMDEBUG macro is defined
15930*/
15931#ifdef SQLITE_MEMDEBUG
15932
15933/*
15934** The backtrace functionality is only available with GLIBC
15935*/
15936#ifdef __GLIBC__
15937  extern int backtrace(void**,int);
15938  extern void backtrace_symbols_fd(void*const*,int,int);
15939#else
15940# define backtrace(A,B) 1
15941# define backtrace_symbols_fd(A,B,C)
15942#endif
15943/* #include <stdio.h> */
15944
15945/*
15946** Each memory allocation looks like this:
15947**
15948**  ------------------------------------------------------------------------
15949**  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
15950**  ------------------------------------------------------------------------
15951**
15952** The application code sees only a pointer to the allocation.  We have
15953** to back up from the allocation pointer to find the MemBlockHdr.  The
15954** MemBlockHdr tells us the size of the allocation and the number of
15955** backtrace pointers.  There is also a guard word at the end of the
15956** MemBlockHdr.
15957*/
15958struct MemBlockHdr {
15959  i64 iSize;                          /* Size of this allocation */
15960  struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
15961  char nBacktrace;                    /* Number of backtraces on this alloc */
15962  char nBacktraceSlots;               /* Available backtrace slots */
15963  u8 nTitle;                          /* Bytes of title; includes '\0' */
15964  u8 eType;                           /* Allocation type code */
15965  int iForeGuard;                     /* Guard word for sanity */
15966};
15967
15968/*
15969** Guard words
15970*/
15971#define FOREGUARD 0x80F5E153
15972#define REARGUARD 0xE4676B53
15973
15974/*
15975** Number of malloc size increments to track.
15976*/
15977#define NCSIZE  1000
15978
15979/*
15980** All of the static variables used by this module are collected
15981** into a single structure named "mem".  This is to keep the
15982** static variables organized and to reduce namespace pollution
15983** when this module is combined with other in the amalgamation.
15984*/
15985static struct {
15986
15987  /*
15988  ** Mutex to control access to the memory allocation subsystem.
15989  */
15990  sqlite3_mutex *mutex;
15991
15992  /*
15993  ** Head and tail of a linked list of all outstanding allocations
15994  */
15995  struct MemBlockHdr *pFirst;
15996  struct MemBlockHdr *pLast;
15997
15998  /*
15999  ** The number of levels of backtrace to save in new allocations.
16000  */
16001  int nBacktrace;
16002  void (*xBacktrace)(int, int, void **);
16003
16004  /*
16005  ** Title text to insert in front of each block
16006  */
16007  int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
16008  char zTitle[100];  /* The title text */
16009
16010  /*
16011  ** sqlite3MallocDisallow() increments the following counter.
16012  ** sqlite3MallocAllow() decrements it.
16013  */
16014  int disallow; /* Do not allow memory allocation */
16015
16016  /*
16017  ** Gather statistics on the sizes of memory allocations.
16018  ** nAlloc[i] is the number of allocation attempts of i*8
16019  ** bytes.  i==NCSIZE is the number of allocation attempts for
16020  ** sizes more than NCSIZE*8 bytes.
16021  */
16022  int nAlloc[NCSIZE];      /* Total number of allocations */
16023  int nCurrent[NCSIZE];    /* Current number of allocations */
16024  int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
16025
16026} mem;
16027
16028
16029/*
16030** Adjust memory usage statistics
16031*/
16032static void adjustStats(int iSize, int increment){
16033  int i = ROUND8(iSize)/8;
16034  if( i>NCSIZE-1 ){
16035    i = NCSIZE - 1;
16036  }
16037  if( increment>0 ){
16038    mem.nAlloc[i]++;
16039    mem.nCurrent[i]++;
16040    if( mem.nCurrent[i]>mem.mxCurrent[i] ){
16041      mem.mxCurrent[i] = mem.nCurrent[i];
16042    }
16043  }else{
16044    mem.nCurrent[i]--;
16045    assert( mem.nCurrent[i]>=0 );
16046  }
16047}
16048
16049/*
16050** Given an allocation, find the MemBlockHdr for that allocation.
16051**
16052** This routine checks the guards at either end of the allocation and
16053** if they are incorrect it asserts.
16054*/
16055static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
16056  struct MemBlockHdr *p;
16057  int *pInt;
16058  u8 *pU8;
16059  int nReserve;
16060
16061  p = (struct MemBlockHdr*)pAllocation;
16062  p--;
16063  assert( p->iForeGuard==(int)FOREGUARD );
16064  nReserve = ROUND8(p->iSize);
16065  pInt = (int*)pAllocation;
16066  pU8 = (u8*)pAllocation;
16067  assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
16068  /* This checks any of the "extra" bytes allocated due
16069  ** to rounding up to an 8 byte boundary to ensure
16070  ** they haven't been overwritten.
16071  */
16072  while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
16073  return p;
16074}
16075
16076/*
16077** Return the number of bytes currently allocated at address p.
16078*/
16079static int sqlite3MemSize(void *p){
16080  struct MemBlockHdr *pHdr;
16081  if( !p ){
16082    return 0;
16083  }
16084  pHdr = sqlite3MemsysGetHeader(p);
16085  return pHdr->iSize;
16086}
16087
16088/*
16089** Initialize the memory allocation subsystem.
16090*/
16091static int sqlite3MemInit(void *NotUsed){
16092  UNUSED_PARAMETER(NotUsed);
16093  assert( (sizeof(struct MemBlockHdr)&7) == 0 );
16094  if( !sqlite3GlobalConfig.bMemstat ){
16095    /* If memory status is enabled, then the malloc.c wrapper will already
16096    ** hold the STATIC_MEM mutex when the routines here are invoked. */
16097    mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
16098  }
16099  return SQLITE_OK;
16100}
16101
16102/*
16103** Deinitialize the memory allocation subsystem.
16104*/
16105static void sqlite3MemShutdown(void *NotUsed){
16106  UNUSED_PARAMETER(NotUsed);
16107  mem.mutex = 0;
16108}
16109
16110/*
16111** Round up a request size to the next valid allocation size.
16112*/
16113static int sqlite3MemRoundup(int n){
16114  return ROUND8(n);
16115}
16116
16117/*
16118** Fill a buffer with pseudo-random bytes.  This is used to preset
16119** the content of a new memory allocation to unpredictable values and
16120** to clear the content of a freed allocation to unpredictable values.
16121*/
16122static void randomFill(char *pBuf, int nByte){
16123  unsigned int x, y, r;
16124  x = SQLITE_PTR_TO_INT(pBuf);
16125  y = nByte | 1;
16126  while( nByte >= 4 ){
16127    x = (x>>1) ^ (-(x&1) & 0xd0000001);
16128    y = y*1103515245 + 12345;
16129    r = x ^ y;
16130    *(int*)pBuf = r;
16131    pBuf += 4;
16132    nByte -= 4;
16133  }
16134  while( nByte-- > 0 ){
16135    x = (x>>1) ^ (-(x&1) & 0xd0000001);
16136    y = y*1103515245 + 12345;
16137    r = x ^ y;
16138    *(pBuf++) = r & 0xff;
16139  }
16140}
16141
16142/*
16143** Allocate nByte bytes of memory.
16144*/
16145static void *sqlite3MemMalloc(int nByte){
16146  struct MemBlockHdr *pHdr;
16147  void **pBt;
16148  char *z;
16149  int *pInt;
16150  void *p = 0;
16151  int totalSize;
16152  int nReserve;
16153  sqlite3_mutex_enter(mem.mutex);
16154  assert( mem.disallow==0 );
16155  nReserve = ROUND8(nByte);
16156  totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
16157               mem.nBacktrace*sizeof(void*) + mem.nTitle;
16158  p = malloc(totalSize);
16159  if( p ){
16160    z = p;
16161    pBt = (void**)&z[mem.nTitle];
16162    pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
16163    pHdr->pNext = 0;
16164    pHdr->pPrev = mem.pLast;
16165    if( mem.pLast ){
16166      mem.pLast->pNext = pHdr;
16167    }else{
16168      mem.pFirst = pHdr;
16169    }
16170    mem.pLast = pHdr;
16171    pHdr->iForeGuard = FOREGUARD;
16172    pHdr->eType = MEMTYPE_HEAP;
16173    pHdr->nBacktraceSlots = mem.nBacktrace;
16174    pHdr->nTitle = mem.nTitle;
16175    if( mem.nBacktrace ){
16176      void *aAddr[40];
16177      pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
16178      memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
16179      assert(pBt[0]);
16180      if( mem.xBacktrace ){
16181        mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
16182      }
16183    }else{
16184      pHdr->nBacktrace = 0;
16185    }
16186    if( mem.nTitle ){
16187      memcpy(z, mem.zTitle, mem.nTitle);
16188    }
16189    pHdr->iSize = nByte;
16190    adjustStats(nByte, +1);
16191    pInt = (int*)&pHdr[1];
16192    pInt[nReserve/sizeof(int)] = REARGUARD;
16193    randomFill((char*)pInt, nByte);
16194    memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
16195    p = (void*)pInt;
16196  }
16197  sqlite3_mutex_leave(mem.mutex);
16198  return p;
16199}
16200
16201/*
16202** Free memory.
16203*/
16204static void sqlite3MemFree(void *pPrior){
16205  struct MemBlockHdr *pHdr;
16206  void **pBt;
16207  char *z;
16208  assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
16209       || mem.mutex!=0 );
16210  pHdr = sqlite3MemsysGetHeader(pPrior);
16211  pBt = (void**)pHdr;
16212  pBt -= pHdr->nBacktraceSlots;
16213  sqlite3_mutex_enter(mem.mutex);
16214  if( pHdr->pPrev ){
16215    assert( pHdr->pPrev->pNext==pHdr );
16216    pHdr->pPrev->pNext = pHdr->pNext;
16217  }else{
16218    assert( mem.pFirst==pHdr );
16219    mem.pFirst = pHdr->pNext;
16220  }
16221  if( pHdr->pNext ){
16222    assert( pHdr->pNext->pPrev==pHdr );
16223    pHdr->pNext->pPrev = pHdr->pPrev;
16224  }else{
16225    assert( mem.pLast==pHdr );
16226    mem.pLast = pHdr->pPrev;
16227  }
16228  z = (char*)pBt;
16229  z -= pHdr->nTitle;
16230  adjustStats(pHdr->iSize, -1);
16231  randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
16232                pHdr->iSize + sizeof(int) + pHdr->nTitle);
16233  free(z);
16234  sqlite3_mutex_leave(mem.mutex);
16235}
16236
16237/*
16238** Change the size of an existing memory allocation.
16239**
16240** For this debugging implementation, we *always* make a copy of the
16241** allocation into a new place in memory.  In this way, if the
16242** higher level code is using pointer to the old allocation, it is
16243** much more likely to break and we are much more liking to find
16244** the error.
16245*/
16246static void *sqlite3MemRealloc(void *pPrior, int nByte){
16247  struct MemBlockHdr *pOldHdr;
16248  void *pNew;
16249  assert( mem.disallow==0 );
16250  assert( (nByte & 7)==0 );     /* EV: R-46199-30249 */
16251  pOldHdr = sqlite3MemsysGetHeader(pPrior);
16252  pNew = sqlite3MemMalloc(nByte);
16253  if( pNew ){
16254    memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
16255    if( nByte>pOldHdr->iSize ){
16256      randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - pOldHdr->iSize);
16257    }
16258    sqlite3MemFree(pPrior);
16259  }
16260  return pNew;
16261}
16262
16263/*
16264** Populate the low-level memory allocation function pointers in
16265** sqlite3GlobalConfig.m with pointers to the routines in this file.
16266*/
16267SQLITE_PRIVATE void sqlite3MemSetDefault(void){
16268  static const sqlite3_mem_methods defaultMethods = {
16269     sqlite3MemMalloc,
16270     sqlite3MemFree,
16271     sqlite3MemRealloc,
16272     sqlite3MemSize,
16273     sqlite3MemRoundup,
16274     sqlite3MemInit,
16275     sqlite3MemShutdown,
16276     0
16277  };
16278  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
16279}
16280
16281/*
16282** Set the "type" of an allocation.
16283*/
16284SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
16285  if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
16286    struct MemBlockHdr *pHdr;
16287    pHdr = sqlite3MemsysGetHeader(p);
16288    assert( pHdr->iForeGuard==FOREGUARD );
16289    pHdr->eType = eType;
16290  }
16291}
16292
16293/*
16294** Return TRUE if the mask of type in eType matches the type of the
16295** allocation p.  Also return true if p==NULL.
16296**
16297** This routine is designed for use within an assert() statement, to
16298** verify the type of an allocation.  For example:
16299**
16300**     assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
16301*/
16302SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
16303  int rc = 1;
16304  if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
16305    struct MemBlockHdr *pHdr;
16306    pHdr = sqlite3MemsysGetHeader(p);
16307    assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
16308    if( (pHdr->eType&eType)==0 ){
16309      rc = 0;
16310    }
16311  }
16312  return rc;
16313}
16314
16315/*
16316** Return TRUE if the mask of type in eType matches no bits of the type of the
16317** allocation p.  Also return true if p==NULL.
16318**
16319** This routine is designed for use within an assert() statement, to
16320** verify the type of an allocation.  For example:
16321**
16322**     assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
16323*/
16324SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
16325  int rc = 1;
16326  if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
16327    struct MemBlockHdr *pHdr;
16328    pHdr = sqlite3MemsysGetHeader(p);
16329    assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
16330    if( (pHdr->eType&eType)!=0 ){
16331      rc = 0;
16332    }
16333  }
16334  return rc;
16335}
16336
16337/*
16338** Set the number of backtrace levels kept for each allocation.
16339** A value of zero turns off backtracing.  The number is always rounded
16340** up to a multiple of 2.
16341*/
16342SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
16343  if( depth<0 ){ depth = 0; }
16344  if( depth>20 ){ depth = 20; }
16345  depth = (depth+1)&0xfe;
16346  mem.nBacktrace = depth;
16347}
16348
16349SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
16350  mem.xBacktrace = xBacktrace;
16351}
16352
16353/*
16354** Set the title string for subsequent allocations.
16355*/
16356SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
16357  unsigned int n = sqlite3Strlen30(zTitle) + 1;
16358  sqlite3_mutex_enter(mem.mutex);
16359  if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
16360  memcpy(mem.zTitle, zTitle, n);
16361  mem.zTitle[n] = 0;
16362  mem.nTitle = ROUND8(n);
16363  sqlite3_mutex_leave(mem.mutex);
16364}
16365
16366SQLITE_PRIVATE void sqlite3MemdebugSync(){
16367  struct MemBlockHdr *pHdr;
16368  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
16369    void **pBt = (void**)pHdr;
16370    pBt -= pHdr->nBacktraceSlots;
16371    mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
16372  }
16373}
16374
16375/*
16376** Open the file indicated and write a log of all unfreed memory
16377** allocations into that log.
16378*/
16379SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
16380  FILE *out;
16381  struct MemBlockHdr *pHdr;
16382  void **pBt;
16383  int i;
16384  out = fopen(zFilename, "w");
16385  if( out==0 ){
16386    fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
16387                    zFilename);
16388    return;
16389  }
16390  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
16391    char *z = (char*)pHdr;
16392    z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
16393    fprintf(out, "**** %lld bytes at %p from %s ****\n",
16394            pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
16395    if( pHdr->nBacktrace ){
16396      fflush(out);
16397      pBt = (void**)pHdr;
16398      pBt -= pHdr->nBacktraceSlots;
16399      backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
16400      fprintf(out, "\n");
16401    }
16402  }
16403  fprintf(out, "COUNTS:\n");
16404  for(i=0; i<NCSIZE-1; i++){
16405    if( mem.nAlloc[i] ){
16406      fprintf(out, "   %5d: %10d %10d %10d\n",
16407            i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
16408    }
16409  }
16410  if( mem.nAlloc[NCSIZE-1] ){
16411    fprintf(out, "   %5d: %10d %10d %10d\n",
16412             NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
16413             mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
16414  }
16415  fclose(out);
16416}
16417
16418/*
16419** Return the number of times sqlite3MemMalloc() has been called.
16420*/
16421SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
16422  int i;
16423  int nTotal = 0;
16424  for(i=0; i<NCSIZE; i++){
16425    nTotal += mem.nAlloc[i];
16426  }
16427  return nTotal;
16428}
16429
16430
16431#endif /* SQLITE_MEMDEBUG */
16432
16433/************** End of mem2.c ************************************************/
16434/************** Begin file mem3.c ********************************************/
16435/*
16436** 2007 October 14
16437**
16438** The author disclaims copyright to this source code.  In place of
16439** a legal notice, here is a blessing:
16440**
16441**    May you do good and not evil.
16442**    May you find forgiveness for yourself and forgive others.
16443**    May you share freely, never taking more than you give.
16444**
16445*************************************************************************
16446** This file contains the C functions that implement a memory
16447** allocation subsystem for use by SQLite.
16448**
16449** This version of the memory allocation subsystem omits all
16450** use of malloc(). The SQLite user supplies a block of memory
16451** before calling sqlite3_initialize() from which allocations
16452** are made and returned by the xMalloc() and xRealloc()
16453** implementations. Once sqlite3_initialize() has been called,
16454** the amount of memory available to SQLite is fixed and cannot
16455** be changed.
16456**
16457** This version of the memory allocation subsystem is included
16458** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
16459*/
16460
16461/*
16462** This version of the memory allocator is only built into the library
16463** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
16464** mean that the library will use a memory-pool by default, just that
16465** it is available. The mempool allocator is activated by calling
16466** sqlite3_config().
16467*/
16468#ifdef SQLITE_ENABLE_MEMSYS3
16469
16470/*
16471** Maximum size (in Mem3Blocks) of a "small" chunk.
16472*/
16473#define MX_SMALL 10
16474
16475
16476/*
16477** Number of freelist hash slots
16478*/
16479#define N_HASH  61
16480
16481/*
16482** A memory allocation (also called a "chunk") consists of two or
16483** more blocks where each block is 8 bytes.  The first 8 bytes are
16484** a header that is not returned to the user.
16485**
16486** A chunk is two or more blocks that is either checked out or
16487** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
16488** size of the allocation in blocks if the allocation is free.
16489** The u.hdr.size4x&1 bit is true if the chunk is checked out and
16490** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
16491** is true if the previous chunk is checked out and false if the
16492** previous chunk is free.  The u.hdr.prevSize field is the size of
16493** the previous chunk in blocks if the previous chunk is on the
16494** freelist. If the previous chunk is checked out, then
16495** u.hdr.prevSize can be part of the data for that chunk and should
16496** not be read or written.
16497**
16498** We often identify a chunk by its index in mem3.aPool[].  When
16499** this is done, the chunk index refers to the second block of
16500** the chunk.  In this way, the first chunk has an index of 1.
16501** A chunk index of 0 means "no such chunk" and is the equivalent
16502** of a NULL pointer.
16503**
16504** The second block of free chunks is of the form u.list.  The
16505** two fields form a double-linked list of chunks of related sizes.
16506** Pointers to the head of the list are stored in mem3.aiSmall[]
16507** for smaller chunks and mem3.aiHash[] for larger chunks.
16508**
16509** The second block of a chunk is user data if the chunk is checked
16510** out.  If a chunk is checked out, the user data may extend into
16511** the u.hdr.prevSize value of the following chunk.
16512*/
16513typedef struct Mem3Block Mem3Block;
16514struct Mem3Block {
16515  union {
16516    struct {
16517      u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
16518      u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
16519    } hdr;
16520    struct {
16521      u32 next;       /* Index in mem3.aPool[] of next free chunk */
16522      u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
16523    } list;
16524  } u;
16525};
16526
16527/*
16528** All of the static variables used by this module are collected
16529** into a single structure named "mem3".  This is to keep the
16530** static variables organized and to reduce namespace pollution
16531** when this module is combined with other in the amalgamation.
16532*/
16533static SQLITE_WSD struct Mem3Global {
16534  /*
16535  ** Memory available for allocation. nPool is the size of the array
16536  ** (in Mem3Blocks) pointed to by aPool less 2.
16537  */
16538  u32 nPool;
16539  Mem3Block *aPool;
16540
16541  /*
16542  ** True if we are evaluating an out-of-memory callback.
16543  */
16544  int alarmBusy;
16545
16546  /*
16547  ** Mutex to control access to the memory allocation subsystem.
16548  */
16549  sqlite3_mutex *mutex;
16550
16551  /*
16552  ** The minimum amount of free space that we have seen.
16553  */
16554  u32 mnMaster;
16555
16556  /*
16557  ** iMaster is the index of the master chunk.  Most new allocations
16558  ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
16559  ** of the current master.  iMaster is 0 if there is not master chunk.
16560  ** The master chunk is not in either the aiHash[] or aiSmall[].
16561  */
16562  u32 iMaster;
16563  u32 szMaster;
16564
16565  /*
16566  ** Array of lists of free blocks according to the block size
16567  ** for smaller chunks, or a hash on the block size for larger
16568  ** chunks.
16569  */
16570  u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
16571  u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
16572} mem3 = { 97535575 };
16573
16574#define mem3 GLOBAL(struct Mem3Global, mem3)
16575
16576/*
16577** Unlink the chunk at mem3.aPool[i] from list it is currently
16578** on.  *pRoot is the list that i is a member of.
16579*/
16580static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
16581  u32 next = mem3.aPool[i].u.list.next;
16582  u32 prev = mem3.aPool[i].u.list.prev;
16583  assert( sqlite3_mutex_held(mem3.mutex) );
16584  if( prev==0 ){
16585    *pRoot = next;
16586  }else{
16587    mem3.aPool[prev].u.list.next = next;
16588  }
16589  if( next ){
16590    mem3.aPool[next].u.list.prev = prev;
16591  }
16592  mem3.aPool[i].u.list.next = 0;
16593  mem3.aPool[i].u.list.prev = 0;
16594}
16595
16596/*
16597** Unlink the chunk at index i from
16598** whatever list is currently a member of.
16599*/
16600static void memsys3Unlink(u32 i){
16601  u32 size, hash;
16602  assert( sqlite3_mutex_held(mem3.mutex) );
16603  assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
16604  assert( i>=1 );
16605  size = mem3.aPool[i-1].u.hdr.size4x/4;
16606  assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
16607  assert( size>=2 );
16608  if( size <= MX_SMALL ){
16609    memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
16610  }else{
16611    hash = size % N_HASH;
16612    memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
16613  }
16614}
16615
16616/*
16617** Link the chunk at mem3.aPool[i] so that is on the list rooted
16618** at *pRoot.
16619*/
16620static void memsys3LinkIntoList(u32 i, u32 *pRoot){
16621  assert( sqlite3_mutex_held(mem3.mutex) );
16622  mem3.aPool[i].u.list.next = *pRoot;
16623  mem3.aPool[i].u.list.prev = 0;
16624  if( *pRoot ){
16625    mem3.aPool[*pRoot].u.list.prev = i;
16626  }
16627  *pRoot = i;
16628}
16629
16630/*
16631** Link the chunk at index i into either the appropriate
16632** small chunk list, or into the large chunk hash table.
16633*/
16634static void memsys3Link(u32 i){
16635  u32 size, hash;
16636  assert( sqlite3_mutex_held(mem3.mutex) );
16637  assert( i>=1 );
16638  assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
16639  size = mem3.aPool[i-1].u.hdr.size4x/4;
16640  assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
16641  assert( size>=2 );
16642  if( size <= MX_SMALL ){
16643    memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
16644  }else{
16645    hash = size % N_HASH;
16646    memsys3LinkIntoList(i, &mem3.aiHash[hash]);
16647  }
16648}
16649
16650/*
16651** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
16652** will already be held (obtained by code in malloc.c) if
16653** sqlite3GlobalConfig.bMemStat is true.
16654*/
16655static void memsys3Enter(void){
16656  if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
16657    mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
16658  }
16659  sqlite3_mutex_enter(mem3.mutex);
16660}
16661static void memsys3Leave(void){
16662  sqlite3_mutex_leave(mem3.mutex);
16663}
16664
16665/*
16666** Called when we are unable to satisfy an allocation of nBytes.
16667*/
16668static void memsys3OutOfMemory(int nByte){
16669  if( !mem3.alarmBusy ){
16670    mem3.alarmBusy = 1;
16671    assert( sqlite3_mutex_held(mem3.mutex) );
16672    sqlite3_mutex_leave(mem3.mutex);
16673    sqlite3_release_memory(nByte);
16674    sqlite3_mutex_enter(mem3.mutex);
16675    mem3.alarmBusy = 0;
16676  }
16677}
16678
16679
16680/*
16681** Chunk i is a free chunk that has been unlinked.  Adjust its
16682** size parameters for check-out and return a pointer to the
16683** user portion of the chunk.
16684*/
16685static void *memsys3Checkout(u32 i, u32 nBlock){
16686  u32 x;
16687  assert( sqlite3_mutex_held(mem3.mutex) );
16688  assert( i>=1 );
16689  assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
16690  assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
16691  x = mem3.aPool[i-1].u.hdr.size4x;
16692  mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
16693  mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
16694  mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
16695  return &mem3.aPool[i];
16696}
16697
16698/*
16699** Carve a piece off of the end of the mem3.iMaster free chunk.
16700** Return a pointer to the new allocation.  Or, if the master chunk
16701** is not large enough, return 0.
16702*/
16703static void *memsys3FromMaster(u32 nBlock){
16704  assert( sqlite3_mutex_held(mem3.mutex) );
16705  assert( mem3.szMaster>=nBlock );
16706  if( nBlock>=mem3.szMaster-1 ){
16707    /* Use the entire master */
16708    void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
16709    mem3.iMaster = 0;
16710    mem3.szMaster = 0;
16711    mem3.mnMaster = 0;
16712    return p;
16713  }else{
16714    /* Split the master block.  Return the tail. */
16715    u32 newi, x;
16716    newi = mem3.iMaster + mem3.szMaster - nBlock;
16717    assert( newi > mem3.iMaster+1 );
16718    mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
16719    mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
16720    mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
16721    mem3.szMaster -= nBlock;
16722    mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
16723    x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
16724    mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
16725    if( mem3.szMaster < mem3.mnMaster ){
16726      mem3.mnMaster = mem3.szMaster;
16727    }
16728    return (void*)&mem3.aPool[newi];
16729  }
16730}
16731
16732/*
16733** *pRoot is the head of a list of free chunks of the same size
16734** or same size hash.  In other words, *pRoot is an entry in either
16735** mem3.aiSmall[] or mem3.aiHash[].
16736**
16737** This routine examines all entries on the given list and tries
16738** to coalesce each entries with adjacent free chunks.
16739**
16740** If it sees a chunk that is larger than mem3.iMaster, it replaces
16741** the current mem3.iMaster with the new larger chunk.  In order for
16742** this mem3.iMaster replacement to work, the master chunk must be
16743** linked into the hash tables.  That is not the normal state of
16744** affairs, of course.  The calling routine must link the master
16745** chunk before invoking this routine, then must unlink the (possibly
16746** changed) master chunk once this routine has finished.
16747*/
16748static void memsys3Merge(u32 *pRoot){
16749  u32 iNext, prev, size, i, x;
16750
16751  assert( sqlite3_mutex_held(mem3.mutex) );
16752  for(i=*pRoot; i>0; i=iNext){
16753    iNext = mem3.aPool[i].u.list.next;
16754    size = mem3.aPool[i-1].u.hdr.size4x;
16755    assert( (size&1)==0 );
16756    if( (size&2)==0 ){
16757      memsys3UnlinkFromList(i, pRoot);
16758      assert( i > mem3.aPool[i-1].u.hdr.prevSize );
16759      prev = i - mem3.aPool[i-1].u.hdr.prevSize;
16760      if( prev==iNext ){
16761        iNext = mem3.aPool[prev].u.list.next;
16762      }
16763      memsys3Unlink(prev);
16764      size = i + size/4 - prev;
16765      x = mem3.aPool[prev-1].u.hdr.size4x & 2;
16766      mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
16767      mem3.aPool[prev+size-1].u.hdr.prevSize = size;
16768      memsys3Link(prev);
16769      i = prev;
16770    }else{
16771      size /= 4;
16772    }
16773    if( size>mem3.szMaster ){
16774      mem3.iMaster = i;
16775      mem3.szMaster = size;
16776    }
16777  }
16778}
16779
16780/*
16781** Return a block of memory of at least nBytes in size.
16782** Return NULL if unable.
16783**
16784** This function assumes that the necessary mutexes, if any, are
16785** already held by the caller. Hence "Unsafe".
16786*/
16787static void *memsys3MallocUnsafe(int nByte){
16788  u32 i;
16789  u32 nBlock;
16790  u32 toFree;
16791
16792  assert( sqlite3_mutex_held(mem3.mutex) );
16793  assert( sizeof(Mem3Block)==8 );
16794  if( nByte<=12 ){
16795    nBlock = 2;
16796  }else{
16797    nBlock = (nByte + 11)/8;
16798  }
16799  assert( nBlock>=2 );
16800
16801  /* STEP 1:
16802  ** Look for an entry of the correct size in either the small
16803  ** chunk table or in the large chunk hash table.  This is
16804  ** successful most of the time (about 9 times out of 10).
16805  */
16806  if( nBlock <= MX_SMALL ){
16807    i = mem3.aiSmall[nBlock-2];
16808    if( i>0 ){
16809      memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
16810      return memsys3Checkout(i, nBlock);
16811    }
16812  }else{
16813    int hash = nBlock % N_HASH;
16814    for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
16815      if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
16816        memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
16817        return memsys3Checkout(i, nBlock);
16818      }
16819    }
16820  }
16821
16822  /* STEP 2:
16823  ** Try to satisfy the allocation by carving a piece off of the end
16824  ** of the master chunk.  This step usually works if step 1 fails.
16825  */
16826  if( mem3.szMaster>=nBlock ){
16827    return memsys3FromMaster(nBlock);
16828  }
16829
16830
16831  /* STEP 3:
16832  ** Loop through the entire memory pool.  Coalesce adjacent free
16833  ** chunks.  Recompute the master chunk as the largest free chunk.
16834  ** Then try again to satisfy the allocation by carving a piece off
16835  ** of the end of the master chunk.  This step happens very
16836  ** rarely (we hope!)
16837  */
16838  for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
16839    memsys3OutOfMemory(toFree);
16840    if( mem3.iMaster ){
16841      memsys3Link(mem3.iMaster);
16842      mem3.iMaster = 0;
16843      mem3.szMaster = 0;
16844    }
16845    for(i=0; i<N_HASH; i++){
16846      memsys3Merge(&mem3.aiHash[i]);
16847    }
16848    for(i=0; i<MX_SMALL-1; i++){
16849      memsys3Merge(&mem3.aiSmall[i]);
16850    }
16851    if( mem3.szMaster ){
16852      memsys3Unlink(mem3.iMaster);
16853      if( mem3.szMaster>=nBlock ){
16854        return memsys3FromMaster(nBlock);
16855      }
16856    }
16857  }
16858
16859  /* If none of the above worked, then we fail. */
16860  return 0;
16861}
16862
16863/*
16864** Free an outstanding memory allocation.
16865**
16866** This function assumes that the necessary mutexes, if any, are
16867** already held by the caller. Hence "Unsafe".
16868*/
16869static void memsys3FreeUnsafe(void *pOld){
16870  Mem3Block *p = (Mem3Block*)pOld;
16871  int i;
16872  u32 size, x;
16873  assert( sqlite3_mutex_held(mem3.mutex) );
16874  assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
16875  i = p - mem3.aPool;
16876  assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
16877  size = mem3.aPool[i-1].u.hdr.size4x/4;
16878  assert( i+size<=mem3.nPool+1 );
16879  mem3.aPool[i-1].u.hdr.size4x &= ~1;
16880  mem3.aPool[i+size-1].u.hdr.prevSize = size;
16881  mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
16882  memsys3Link(i);
16883
16884  /* Try to expand the master using the newly freed chunk */
16885  if( mem3.iMaster ){
16886    while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
16887      size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
16888      mem3.iMaster -= size;
16889      mem3.szMaster += size;
16890      memsys3Unlink(mem3.iMaster);
16891      x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
16892      mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
16893      mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
16894    }
16895    x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
16896    while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
16897      memsys3Unlink(mem3.iMaster+mem3.szMaster);
16898      mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
16899      mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
16900      mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
16901    }
16902  }
16903}
16904
16905/*
16906** Return the size of an outstanding allocation, in bytes.  The
16907** size returned omits the 8-byte header overhead.  This only
16908** works for chunks that are currently checked out.
16909*/
16910static int memsys3Size(void *p){
16911  Mem3Block *pBlock;
16912  if( p==0 ) return 0;
16913  pBlock = (Mem3Block*)p;
16914  assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
16915  return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
16916}
16917
16918/*
16919** Round up a request size to the next valid allocation size.
16920*/
16921static int memsys3Roundup(int n){
16922  if( n<=12 ){
16923    return 12;
16924  }else{
16925    return ((n+11)&~7) - 4;
16926  }
16927}
16928
16929/*
16930** Allocate nBytes of memory.
16931*/
16932static void *memsys3Malloc(int nBytes){
16933  sqlite3_int64 *p;
16934  assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
16935  memsys3Enter();
16936  p = memsys3MallocUnsafe(nBytes);
16937  memsys3Leave();
16938  return (void*)p;
16939}
16940
16941/*
16942** Free memory.
16943*/
16944static void memsys3Free(void *pPrior){
16945  assert( pPrior );
16946  memsys3Enter();
16947  memsys3FreeUnsafe(pPrior);
16948  memsys3Leave();
16949}
16950
16951/*
16952** Change the size of an existing memory allocation
16953*/
16954static void *memsys3Realloc(void *pPrior, int nBytes){
16955  int nOld;
16956  void *p;
16957  if( pPrior==0 ){
16958    return sqlite3_malloc(nBytes);
16959  }
16960  if( nBytes<=0 ){
16961    sqlite3_free(pPrior);
16962    return 0;
16963  }
16964  nOld = memsys3Size(pPrior);
16965  if( nBytes<=nOld && nBytes>=nOld-128 ){
16966    return pPrior;
16967  }
16968  memsys3Enter();
16969  p = memsys3MallocUnsafe(nBytes);
16970  if( p ){
16971    if( nOld<nBytes ){
16972      memcpy(p, pPrior, nOld);
16973    }else{
16974      memcpy(p, pPrior, nBytes);
16975    }
16976    memsys3FreeUnsafe(pPrior);
16977  }
16978  memsys3Leave();
16979  return p;
16980}
16981
16982/*
16983** Initialize this module.
16984*/
16985static int memsys3Init(void *NotUsed){
16986  UNUSED_PARAMETER(NotUsed);
16987  if( !sqlite3GlobalConfig.pHeap ){
16988    return SQLITE_ERROR;
16989  }
16990
16991  /* Store a pointer to the memory block in global structure mem3. */
16992  assert( sizeof(Mem3Block)==8 );
16993  mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
16994  mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
16995
16996  /* Initialize the master block. */
16997  mem3.szMaster = mem3.nPool;
16998  mem3.mnMaster = mem3.szMaster;
16999  mem3.iMaster = 1;
17000  mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
17001  mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
17002  mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
17003
17004  return SQLITE_OK;
17005}
17006
17007/*
17008** Deinitialize this module.
17009*/
17010static void memsys3Shutdown(void *NotUsed){
17011  UNUSED_PARAMETER(NotUsed);
17012  mem3.mutex = 0;
17013  return;
17014}
17015
17016
17017
17018/*
17019** Open the file indicated and write a log of all unfreed memory
17020** allocations into that log.
17021*/
17022SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
17023#ifdef SQLITE_DEBUG
17024  FILE *out;
17025  u32 i, j;
17026  u32 size;
17027  if( zFilename==0 || zFilename[0]==0 ){
17028    out = stdout;
17029  }else{
17030    out = fopen(zFilename, "w");
17031    if( out==0 ){
17032      fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
17033                      zFilename);
17034      return;
17035    }
17036  }
17037  memsys3Enter();
17038  fprintf(out, "CHUNKS:\n");
17039  for(i=1; i<=mem3.nPool; i+=size/4){
17040    size = mem3.aPool[i-1].u.hdr.size4x;
17041    if( size/4<=1 ){
17042      fprintf(out, "%p size error\n", &mem3.aPool[i]);
17043      assert( 0 );
17044      break;
17045    }
17046    if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
17047      fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
17048      assert( 0 );
17049      break;
17050    }
17051    if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
17052      fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
17053      assert( 0 );
17054      break;
17055    }
17056    if( size&1 ){
17057      fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
17058    }else{
17059      fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
17060                  i==mem3.iMaster ? " **master**" : "");
17061    }
17062  }
17063  for(i=0; i<MX_SMALL-1; i++){
17064    if( mem3.aiSmall[i]==0 ) continue;
17065    fprintf(out, "small(%2d):", i);
17066    for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
17067      fprintf(out, " %p(%d)", &mem3.aPool[j],
17068              (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
17069    }
17070    fprintf(out, "\n");
17071  }
17072  for(i=0; i<N_HASH; i++){
17073    if( mem3.aiHash[i]==0 ) continue;
17074    fprintf(out, "hash(%2d):", i);
17075    for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
17076      fprintf(out, " %p(%d)", &mem3.aPool[j],
17077              (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
17078    }
17079    fprintf(out, "\n");
17080  }
17081  fprintf(out, "master=%d\n", mem3.iMaster);
17082  fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
17083  fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
17084  sqlite3_mutex_leave(mem3.mutex);
17085  if( out==stdout ){
17086    fflush(stdout);
17087  }else{
17088    fclose(out);
17089  }
17090#else
17091  UNUSED_PARAMETER(zFilename);
17092#endif
17093}
17094
17095/*
17096** This routine is the only routine in this file with external
17097** linkage.
17098**
17099** Populate the low-level memory allocation function pointers in
17100** sqlite3GlobalConfig.m with pointers to the routines in this file. The
17101** arguments specify the block of memory to manage.
17102**
17103** This routine is only called by sqlite3_config(), and therefore
17104** is not required to be threadsafe (it is not).
17105*/
17106SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
17107  static const sqlite3_mem_methods mempoolMethods = {
17108     memsys3Malloc,
17109     memsys3Free,
17110     memsys3Realloc,
17111     memsys3Size,
17112     memsys3Roundup,
17113     memsys3Init,
17114     memsys3Shutdown,
17115     0
17116  };
17117  return &mempoolMethods;
17118}
17119
17120#endif /* SQLITE_ENABLE_MEMSYS3 */
17121
17122/************** End of mem3.c ************************************************/
17123/************** Begin file mem5.c ********************************************/
17124/*
17125** 2007 October 14
17126**
17127** The author disclaims copyright to this source code.  In place of
17128** a legal notice, here is a blessing:
17129**
17130**    May you do good and not evil.
17131**    May you find forgiveness for yourself and forgive others.
17132**    May you share freely, never taking more than you give.
17133**
17134*************************************************************************
17135** This file contains the C functions that implement a memory
17136** allocation subsystem for use by SQLite.
17137**
17138** This version of the memory allocation subsystem omits all
17139** use of malloc(). The application gives SQLite a block of memory
17140** before calling sqlite3_initialize() from which allocations
17141** are made and returned by the xMalloc() and xRealloc()
17142** implementations. Once sqlite3_initialize() has been called,
17143** the amount of memory available to SQLite is fixed and cannot
17144** be changed.
17145**
17146** This version of the memory allocation subsystem is included
17147** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
17148**
17149** This memory allocator uses the following algorithm:
17150**
17151**   1.  All memory allocations sizes are rounded up to a power of 2.
17152**
17153**   2.  If two adjacent free blocks are the halves of a larger block,
17154**       then the two blocks are coalesed into the single larger block.
17155**
17156**   3.  New memory is allocated from the first available free block.
17157**
17158** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
17159** Concerning Dynamic Storage Allocation". Journal of the Association for
17160** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
17161**
17162** Let n be the size of the largest allocation divided by the minimum
17163** allocation size (after rounding all sizes up to a power of 2.)  Let M
17164** be the maximum amount of memory ever outstanding at one time.  Let
17165** N be the total amount of memory available for allocation.  Robson
17166** proved that this memory allocator will never breakdown due to
17167** fragmentation as long as the following constraint holds:
17168**
17169**      N >=  M*(1 + log2(n)/2) - n + 1
17170**
17171** The sqlite3_status() logic tracks the maximum values of n and M so
17172** that an application can, at any time, verify this constraint.
17173*/
17174
17175/*
17176** This version of the memory allocator is used only when
17177** SQLITE_ENABLE_MEMSYS5 is defined.
17178*/
17179#ifdef SQLITE_ENABLE_MEMSYS5
17180
17181/*
17182** A minimum allocation is an instance of the following structure.
17183** Larger allocations are an array of these structures where the
17184** size of the array is a power of 2.
17185**
17186** The size of this object must be a power of two.  That fact is
17187** verified in memsys5Init().
17188*/
17189typedef struct Mem5Link Mem5Link;
17190struct Mem5Link {
17191  int next;       /* Index of next free chunk */
17192  int prev;       /* Index of previous free chunk */
17193};
17194
17195/*
17196** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
17197** mem5.szAtom is always at least 8 and 32-bit integers are used,
17198** it is not actually possible to reach this limit.
17199*/
17200#define LOGMAX 30
17201
17202/*
17203** Masks used for mem5.aCtrl[] elements.
17204*/
17205#define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */
17206#define CTRL_FREE     0x20    /* True if not checked out */
17207
17208/*
17209** All of the static variables used by this module are collected
17210** into a single structure named "mem5".  This is to keep the
17211** static variables organized and to reduce namespace pollution
17212** when this module is combined with other in the amalgamation.
17213*/
17214static SQLITE_WSD struct Mem5Global {
17215  /*
17216  ** Memory available for allocation
17217  */
17218  int szAtom;      /* Smallest possible allocation in bytes */
17219  int nBlock;      /* Number of szAtom sized blocks in zPool */
17220  u8 *zPool;       /* Memory available to be allocated */
17221
17222  /*
17223  ** Mutex to control access to the memory allocation subsystem.
17224  */
17225  sqlite3_mutex *mutex;
17226
17227  /*
17228  ** Performance statistics
17229  */
17230  u64 nAlloc;         /* Total number of calls to malloc */
17231  u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
17232  u64 totalExcess;    /* Total internal fragmentation */
17233  u32 currentOut;     /* Current checkout, including internal fragmentation */
17234  u32 currentCount;   /* Current number of distinct checkouts */
17235  u32 maxOut;         /* Maximum instantaneous currentOut */
17236  u32 maxCount;       /* Maximum instantaneous currentCount */
17237  u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
17238
17239  /*
17240  ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of
17241  ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.
17242  ** and so forth.
17243  */
17244  int aiFreelist[LOGMAX+1];
17245
17246  /*
17247  ** Space for tracking which blocks are checked out and the size
17248  ** of each block.  One byte per block.
17249  */
17250  u8 *aCtrl;
17251
17252} mem5;
17253
17254/*
17255** Access the static variable through a macro for SQLITE_OMIT_WSD
17256*/
17257#define mem5 GLOBAL(struct Mem5Global, mem5)
17258
17259/*
17260** Assuming mem5.zPool is divided up into an array of Mem5Link
17261** structures, return a pointer to the idx-th such lik.
17262*/
17263#define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
17264
17265/*
17266** Unlink the chunk at mem5.aPool[i] from list it is currently
17267** on.  It should be found on mem5.aiFreelist[iLogsize].
17268*/
17269static void memsys5Unlink(int i, int iLogsize){
17270  int next, prev;
17271  assert( i>=0 && i<mem5.nBlock );
17272  assert( iLogsize>=0 && iLogsize<=LOGMAX );
17273  assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
17274
17275  next = MEM5LINK(i)->next;
17276  prev = MEM5LINK(i)->prev;
17277  if( prev<0 ){
17278    mem5.aiFreelist[iLogsize] = next;
17279  }else{
17280    MEM5LINK(prev)->next = next;
17281  }
17282  if( next>=0 ){
17283    MEM5LINK(next)->prev = prev;
17284  }
17285}
17286
17287/*
17288** Link the chunk at mem5.aPool[i] so that is on the iLogsize
17289** free list.
17290*/
17291static void memsys5Link(int i, int iLogsize){
17292  int x;
17293  assert( sqlite3_mutex_held(mem5.mutex) );
17294  assert( i>=0 && i<mem5.nBlock );
17295  assert( iLogsize>=0 && iLogsize<=LOGMAX );
17296  assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
17297
17298  x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
17299  MEM5LINK(i)->prev = -1;
17300  if( x>=0 ){
17301    assert( x<mem5.nBlock );
17302    MEM5LINK(x)->prev = i;
17303  }
17304  mem5.aiFreelist[iLogsize] = i;
17305}
17306
17307/*
17308** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
17309** will already be held (obtained by code in malloc.c) if
17310** sqlite3GlobalConfig.bMemStat is true.
17311*/
17312static void memsys5Enter(void){
17313  sqlite3_mutex_enter(mem5.mutex);
17314}
17315static void memsys5Leave(void){
17316  sqlite3_mutex_leave(mem5.mutex);
17317}
17318
17319/*
17320** Return the size of an outstanding allocation, in bytes.  The
17321** size returned omits the 8-byte header overhead.  This only
17322** works for chunks that are currently checked out.
17323*/
17324static int memsys5Size(void *p){
17325  int iSize = 0;
17326  if( p ){
17327    int i = ((u8 *)p-mem5.zPool)/mem5.szAtom;
17328    assert( i>=0 && i<mem5.nBlock );
17329    iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
17330  }
17331  return iSize;
17332}
17333
17334/*
17335** Find the first entry on the freelist iLogsize.  Unlink that
17336** entry and return its index.
17337*/
17338static int memsys5UnlinkFirst(int iLogsize){
17339  int i;
17340  int iFirst;
17341
17342  assert( iLogsize>=0 && iLogsize<=LOGMAX );
17343  i = iFirst = mem5.aiFreelist[iLogsize];
17344  assert( iFirst>=0 );
17345  while( i>0 ){
17346    if( i<iFirst ) iFirst = i;
17347    i = MEM5LINK(i)->next;
17348  }
17349  memsys5Unlink(iFirst, iLogsize);
17350  return iFirst;
17351}
17352
17353/*
17354** Return a block of memory of at least nBytes in size.
17355** Return NULL if unable.  Return NULL if nBytes==0.
17356**
17357** The caller guarantees that nByte positive.
17358**
17359** The caller has obtained a mutex prior to invoking this
17360** routine so there is never any chance that two or more
17361** threads can be in this routine at the same time.
17362*/
17363static void *memsys5MallocUnsafe(int nByte){
17364  int i;           /* Index of a mem5.aPool[] slot */
17365  int iBin;        /* Index into mem5.aiFreelist[] */
17366  int iFullSz;     /* Size of allocation rounded up to power of 2 */
17367  int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
17368
17369  /* nByte must be a positive */
17370  assert( nByte>0 );
17371
17372  /* Keep track of the maximum allocation request.  Even unfulfilled
17373  ** requests are counted */
17374  if( (u32)nByte>mem5.maxRequest ){
17375    mem5.maxRequest = nByte;
17376  }
17377
17378  /* Abort if the requested allocation size is larger than the largest
17379  ** power of two that we can represent using 32-bit signed integers.
17380  */
17381  if( nByte > 0x40000000 ){
17382    return 0;
17383  }
17384
17385  /* Round nByte up to the next valid power of two */
17386  for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
17387
17388  /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
17389  ** block.  If not, then split a block of the next larger power of
17390  ** two in order to create a new free block of size iLogsize.
17391  */
17392  for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
17393  if( iBin>LOGMAX ){
17394    testcase( sqlite3GlobalConfig.xLog!=0 );
17395    sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
17396    return 0;
17397  }
17398  i = memsys5UnlinkFirst(iBin);
17399  while( iBin>iLogsize ){
17400    int newSize;
17401
17402    iBin--;
17403    newSize = 1 << iBin;
17404    mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
17405    memsys5Link(i+newSize, iBin);
17406  }
17407  mem5.aCtrl[i] = iLogsize;
17408
17409  /* Update allocator performance statistics. */
17410  mem5.nAlloc++;
17411  mem5.totalAlloc += iFullSz;
17412  mem5.totalExcess += iFullSz - nByte;
17413  mem5.currentCount++;
17414  mem5.currentOut += iFullSz;
17415  if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
17416  if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
17417
17418  /* Return a pointer to the allocated memory. */
17419  return (void*)&mem5.zPool[i*mem5.szAtom];
17420}
17421
17422/*
17423** Free an outstanding memory allocation.
17424*/
17425static void memsys5FreeUnsafe(void *pOld){
17426  u32 size, iLogsize;
17427  int iBlock;
17428
17429  /* Set iBlock to the index of the block pointed to by pOld in
17430  ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
17431  */
17432  iBlock = ((u8 *)pOld-mem5.zPool)/mem5.szAtom;
17433
17434  /* Check that the pointer pOld points to a valid, non-free block. */
17435  assert( iBlock>=0 && iBlock<mem5.nBlock );
17436  assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
17437  assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
17438
17439  iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
17440  size = 1<<iLogsize;
17441  assert( iBlock+size-1<(u32)mem5.nBlock );
17442
17443  mem5.aCtrl[iBlock] |= CTRL_FREE;
17444  mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
17445  assert( mem5.currentCount>0 );
17446  assert( mem5.currentOut>=(size*mem5.szAtom) );
17447  mem5.currentCount--;
17448  mem5.currentOut -= size*mem5.szAtom;
17449  assert( mem5.currentOut>0 || mem5.currentCount==0 );
17450  assert( mem5.currentCount>0 || mem5.currentOut==0 );
17451
17452  mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
17453  while( ALWAYS(iLogsize<LOGMAX) ){
17454    int iBuddy;
17455    if( (iBlock>>iLogsize) & 1 ){
17456      iBuddy = iBlock - size;
17457    }else{
17458      iBuddy = iBlock + size;
17459    }
17460    assert( iBuddy>=0 );
17461    if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
17462    if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
17463    memsys5Unlink(iBuddy, iLogsize);
17464    iLogsize++;
17465    if( iBuddy<iBlock ){
17466      mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
17467      mem5.aCtrl[iBlock] = 0;
17468      iBlock = iBuddy;
17469    }else{
17470      mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
17471      mem5.aCtrl[iBuddy] = 0;
17472    }
17473    size *= 2;
17474  }
17475  memsys5Link(iBlock, iLogsize);
17476}
17477
17478/*
17479** Allocate nBytes of memory
17480*/
17481static void *memsys5Malloc(int nBytes){
17482  sqlite3_int64 *p = 0;
17483  if( nBytes>0 ){
17484    memsys5Enter();
17485    p = memsys5MallocUnsafe(nBytes);
17486    memsys5Leave();
17487  }
17488  return (void*)p;
17489}
17490
17491/*
17492** Free memory.
17493**
17494** The outer layer memory allocator prevents this routine from
17495** being called with pPrior==0.
17496*/
17497static void memsys5Free(void *pPrior){
17498  assert( pPrior!=0 );
17499  memsys5Enter();
17500  memsys5FreeUnsafe(pPrior);
17501  memsys5Leave();
17502}
17503
17504/*
17505** Change the size of an existing memory allocation.
17506**
17507** The outer layer memory allocator prevents this routine from
17508** being called with pPrior==0.
17509**
17510** nBytes is always a value obtained from a prior call to
17511** memsys5Round().  Hence nBytes is always a non-negative power
17512** of two.  If nBytes==0 that means that an oversize allocation
17513** (an allocation larger than 0x40000000) was requested and this
17514** routine should return 0 without freeing pPrior.
17515*/
17516static void *memsys5Realloc(void *pPrior, int nBytes){
17517  int nOld;
17518  void *p;
17519  assert( pPrior!=0 );
17520  assert( (nBytes&(nBytes-1))==0 );  /* EV: R-46199-30249 */
17521  assert( nBytes>=0 );
17522  if( nBytes==0 ){
17523    return 0;
17524  }
17525  nOld = memsys5Size(pPrior);
17526  if( nBytes<=nOld ){
17527    return pPrior;
17528  }
17529  memsys5Enter();
17530  p = memsys5MallocUnsafe(nBytes);
17531  if( p ){
17532    memcpy(p, pPrior, nOld);
17533    memsys5FreeUnsafe(pPrior);
17534  }
17535  memsys5Leave();
17536  return p;
17537}
17538
17539/*
17540** Round up a request size to the next valid allocation size.  If
17541** the allocation is too large to be handled by this allocation system,
17542** return 0.
17543**
17544** All allocations must be a power of two and must be expressed by a
17545** 32-bit signed integer.  Hence the largest allocation is 0x40000000
17546** or 1073741824 bytes.
17547*/
17548static int memsys5Roundup(int n){
17549  int iFullSz;
17550  if( n > 0x40000000 ) return 0;
17551  for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
17552  return iFullSz;
17553}
17554
17555/*
17556** Return the ceiling of the logarithm base 2 of iValue.
17557**
17558** Examples:   memsys5Log(1) -> 0
17559**             memsys5Log(2) -> 1
17560**             memsys5Log(4) -> 2
17561**             memsys5Log(5) -> 3
17562**             memsys5Log(8) -> 3
17563**             memsys5Log(9) -> 4
17564*/
17565static int memsys5Log(int iValue){
17566  int iLog;
17567  for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
17568  return iLog;
17569}
17570
17571/*
17572** Initialize the memory allocator.
17573**
17574** This routine is not threadsafe.  The caller must be holding a mutex
17575** to prevent multiple threads from entering at the same time.
17576*/
17577static int memsys5Init(void *NotUsed){
17578  int ii;            /* Loop counter */
17579  int nByte;         /* Number of bytes of memory available to this allocator */
17580  u8 *zByte;         /* Memory usable by this allocator */
17581  int nMinLog;       /* Log base 2 of minimum allocation size in bytes */
17582  int iOffset;       /* An offset into mem5.aCtrl[] */
17583
17584  UNUSED_PARAMETER(NotUsed);
17585
17586  /* For the purposes of this routine, disable the mutex */
17587  mem5.mutex = 0;
17588
17589  /* The size of a Mem5Link object must be a power of two.  Verify that
17590  ** this is case.
17591  */
17592  assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
17593
17594  nByte = sqlite3GlobalConfig.nHeap;
17595  zByte = (u8*)sqlite3GlobalConfig.pHeap;
17596  assert( zByte!=0 );  /* sqlite3_config() does not allow otherwise */
17597
17598  /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
17599  nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
17600  mem5.szAtom = (1<<nMinLog);
17601  while( (int)sizeof(Mem5Link)>mem5.szAtom ){
17602    mem5.szAtom = mem5.szAtom << 1;
17603  }
17604
17605  mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
17606  mem5.zPool = zByte;
17607  mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
17608
17609  for(ii=0; ii<=LOGMAX; ii++){
17610    mem5.aiFreelist[ii] = -1;
17611  }
17612
17613  iOffset = 0;
17614  for(ii=LOGMAX; ii>=0; ii--){
17615    int nAlloc = (1<<ii);
17616    if( (iOffset+nAlloc)<=mem5.nBlock ){
17617      mem5.aCtrl[iOffset] = ii | CTRL_FREE;
17618      memsys5Link(iOffset, ii);
17619      iOffset += nAlloc;
17620    }
17621    assert((iOffset+nAlloc)>mem5.nBlock);
17622  }
17623
17624  /* If a mutex is required for normal operation, allocate one */
17625  if( sqlite3GlobalConfig.bMemstat==0 ){
17626    mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
17627  }
17628
17629  return SQLITE_OK;
17630}
17631
17632/*
17633** Deinitialize this module.
17634*/
17635static void memsys5Shutdown(void *NotUsed){
17636  UNUSED_PARAMETER(NotUsed);
17637  mem5.mutex = 0;
17638  return;
17639}
17640
17641#ifdef SQLITE_TEST
17642/*
17643** Open the file indicated and write a log of all unfreed memory
17644** allocations into that log.
17645*/
17646SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
17647  FILE *out;
17648  int i, j, n;
17649  int nMinLog;
17650
17651  if( zFilename==0 || zFilename[0]==0 ){
17652    out = stdout;
17653  }else{
17654    out = fopen(zFilename, "w");
17655    if( out==0 ){
17656      fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
17657                      zFilename);
17658      return;
17659    }
17660  }
17661  memsys5Enter();
17662  nMinLog = memsys5Log(mem5.szAtom);
17663  for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
17664    for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
17665    fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
17666  }
17667  fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
17668  fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
17669  fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
17670  fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
17671  fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
17672  fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
17673  fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
17674  fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
17675  memsys5Leave();
17676  if( out==stdout ){
17677    fflush(stdout);
17678  }else{
17679    fclose(out);
17680  }
17681}
17682#endif
17683
17684/*
17685** This routine is the only routine in this file with external
17686** linkage. It returns a pointer to a static sqlite3_mem_methods
17687** struct populated with the memsys5 methods.
17688*/
17689SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
17690  static const sqlite3_mem_methods memsys5Methods = {
17691     memsys5Malloc,
17692     memsys5Free,
17693     memsys5Realloc,
17694     memsys5Size,
17695     memsys5Roundup,
17696     memsys5Init,
17697     memsys5Shutdown,
17698     0
17699  };
17700  return &memsys5Methods;
17701}
17702
17703#endif /* SQLITE_ENABLE_MEMSYS5 */
17704
17705/************** End of mem5.c ************************************************/
17706/************** Begin file mutex.c *******************************************/
17707/*
17708** 2007 August 14
17709**
17710** The author disclaims copyright to this source code.  In place of
17711** a legal notice, here is a blessing:
17712**
17713**    May you do good and not evil.
17714**    May you find forgiveness for yourself and forgive others.
17715**    May you share freely, never taking more than you give.
17716**
17717*************************************************************************
17718** This file contains the C functions that implement mutexes.
17719**
17720** This file contains code that is common across all mutex implementations.
17721*/
17722
17723#if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
17724/*
17725** For debugging purposes, record when the mutex subsystem is initialized
17726** and uninitialized so that we can assert() if there is an attempt to
17727** allocate a mutex while the system is uninitialized.
17728*/
17729static SQLITE_WSD int mutexIsInit = 0;
17730#endif /* SQLITE_DEBUG */
17731
17732
17733#ifndef SQLITE_MUTEX_OMIT
17734/*
17735** Initialize the mutex system.
17736*/
17737SQLITE_PRIVATE int sqlite3MutexInit(void){
17738  int rc = SQLITE_OK;
17739  if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
17740    /* If the xMutexAlloc method has not been set, then the user did not
17741    ** install a mutex implementation via sqlite3_config() prior to
17742    ** sqlite3_initialize() being called. This block copies pointers to
17743    ** the default implementation into the sqlite3GlobalConfig structure.
17744    */
17745    sqlite3_mutex_methods const *pFrom;
17746    sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
17747
17748    if( sqlite3GlobalConfig.bCoreMutex ){
17749      pFrom = sqlite3DefaultMutex();
17750    }else{
17751      pFrom = sqlite3NoopMutex();
17752    }
17753    memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
17754    memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
17755           sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
17756    pTo->xMutexAlloc = pFrom->xMutexAlloc;
17757  }
17758  rc = sqlite3GlobalConfig.mutex.xMutexInit();
17759
17760#ifdef SQLITE_DEBUG
17761  GLOBAL(int, mutexIsInit) = 1;
17762#endif
17763
17764  return rc;
17765}
17766
17767/*
17768** Shutdown the mutex system. This call frees resources allocated by
17769** sqlite3MutexInit().
17770*/
17771SQLITE_PRIVATE int sqlite3MutexEnd(void){
17772  int rc = SQLITE_OK;
17773  if( sqlite3GlobalConfig.mutex.xMutexEnd ){
17774    rc = sqlite3GlobalConfig.mutex.xMutexEnd();
17775  }
17776
17777#ifdef SQLITE_DEBUG
17778  GLOBAL(int, mutexIsInit) = 0;
17779#endif
17780
17781  return rc;
17782}
17783
17784/*
17785** Retrieve a pointer to a static mutex or allocate a new dynamic one.
17786*/
17787SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
17788#ifndef SQLITE_OMIT_AUTOINIT
17789  if( sqlite3_initialize() ) return 0;
17790#endif
17791  return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
17792}
17793
17794SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
17795  if( !sqlite3GlobalConfig.bCoreMutex ){
17796    return 0;
17797  }
17798  assert( GLOBAL(int, mutexIsInit) );
17799  return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
17800}
17801
17802/*
17803** Free a dynamic mutex.
17804*/
17805SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
17806  if( p ){
17807    sqlite3GlobalConfig.mutex.xMutexFree(p);
17808  }
17809}
17810
17811/*
17812** Obtain the mutex p. If some other thread already has the mutex, block
17813** until it can be obtained.
17814*/
17815SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
17816  if( p ){
17817    sqlite3GlobalConfig.mutex.xMutexEnter(p);
17818  }
17819}
17820
17821/*
17822** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
17823** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
17824*/
17825SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
17826  int rc = SQLITE_OK;
17827  if( p ){
17828    return sqlite3GlobalConfig.mutex.xMutexTry(p);
17829  }
17830  return rc;
17831}
17832
17833/*
17834** The sqlite3_mutex_leave() routine exits a mutex that was previously
17835** entered by the same thread.  The behavior is undefined if the mutex
17836** is not currently entered. If a NULL pointer is passed as an argument
17837** this function is a no-op.
17838*/
17839SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
17840  if( p ){
17841    sqlite3GlobalConfig.mutex.xMutexLeave(p);
17842  }
17843}
17844
17845#ifndef NDEBUG
17846/*
17847** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
17848** intended for use inside assert() statements.
17849*/
17850SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
17851  return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
17852}
17853SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
17854  return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
17855}
17856#endif
17857
17858#endif /* !defined(SQLITE_MUTEX_OMIT) */
17859
17860/************** End of mutex.c ***********************************************/
17861/************** Begin file mutex_noop.c **************************************/
17862/*
17863** 2008 October 07
17864**
17865** The author disclaims copyright to this source code.  In place of
17866** a legal notice, here is a blessing:
17867**
17868**    May you do good and not evil.
17869**    May you find forgiveness for yourself and forgive others.
17870**    May you share freely, never taking more than you give.
17871**
17872*************************************************************************
17873** This file contains the C functions that implement mutexes.
17874**
17875** This implementation in this file does not provide any mutual
17876** exclusion and is thus suitable for use only in applications
17877** that use SQLite in a single thread.  The routines defined
17878** here are place-holders.  Applications can substitute working
17879** mutex routines at start-time using the
17880**
17881**     sqlite3_config(SQLITE_CONFIG_MUTEX,...)
17882**
17883** interface.
17884**
17885** If compiled with SQLITE_DEBUG, then additional logic is inserted
17886** that does error checking on mutexes to make sure they are being
17887** called correctly.
17888*/
17889
17890#ifndef SQLITE_MUTEX_OMIT
17891
17892#ifndef SQLITE_DEBUG
17893/*
17894** Stub routines for all mutex methods.
17895**
17896** This routines provide no mutual exclusion or error checking.
17897*/
17898static int noopMutexInit(void){ return SQLITE_OK; }
17899static int noopMutexEnd(void){ return SQLITE_OK; }
17900static sqlite3_mutex *noopMutexAlloc(int id){
17901  UNUSED_PARAMETER(id);
17902  return (sqlite3_mutex*)8;
17903}
17904static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
17905static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
17906static int noopMutexTry(sqlite3_mutex *p){
17907  UNUSED_PARAMETER(p);
17908  return SQLITE_OK;
17909}
17910static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
17911
17912SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
17913  static const sqlite3_mutex_methods sMutex = {
17914    noopMutexInit,
17915    noopMutexEnd,
17916    noopMutexAlloc,
17917    noopMutexFree,
17918    noopMutexEnter,
17919    noopMutexTry,
17920    noopMutexLeave,
17921
17922    0,
17923    0,
17924  };
17925
17926  return &sMutex;
17927}
17928#endif /* !SQLITE_DEBUG */
17929
17930#ifdef SQLITE_DEBUG
17931/*
17932** In this implementation, error checking is provided for testing
17933** and debugging purposes.  The mutexes still do not provide any
17934** mutual exclusion.
17935*/
17936
17937/*
17938** The mutex object
17939*/
17940typedef struct sqlite3_debug_mutex {
17941  int id;     /* The mutex type */
17942  int cnt;    /* Number of entries without a matching leave */
17943} sqlite3_debug_mutex;
17944
17945/*
17946** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
17947** intended for use inside assert() statements.
17948*/
17949static int debugMutexHeld(sqlite3_mutex *pX){
17950  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17951  return p==0 || p->cnt>0;
17952}
17953static int debugMutexNotheld(sqlite3_mutex *pX){
17954  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17955  return p==0 || p->cnt==0;
17956}
17957
17958/*
17959** Initialize and deinitialize the mutex subsystem.
17960*/
17961static int debugMutexInit(void){ return SQLITE_OK; }
17962static int debugMutexEnd(void){ return SQLITE_OK; }
17963
17964/*
17965** The sqlite3_mutex_alloc() routine allocates a new
17966** mutex and returns a pointer to it.  If it returns NULL
17967** that means that a mutex could not be allocated.
17968*/
17969static sqlite3_mutex *debugMutexAlloc(int id){
17970  static sqlite3_debug_mutex aStatic[6];
17971  sqlite3_debug_mutex *pNew = 0;
17972  switch( id ){
17973    case SQLITE_MUTEX_FAST:
17974    case SQLITE_MUTEX_RECURSIVE: {
17975      pNew = sqlite3Malloc(sizeof(*pNew));
17976      if( pNew ){
17977        pNew->id = id;
17978        pNew->cnt = 0;
17979      }
17980      break;
17981    }
17982    default: {
17983      assert( id-2 >= 0 );
17984      assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
17985      pNew = &aStatic[id-2];
17986      pNew->id = id;
17987      break;
17988    }
17989  }
17990  return (sqlite3_mutex*)pNew;
17991}
17992
17993/*
17994** This routine deallocates a previously allocated mutex.
17995*/
17996static void debugMutexFree(sqlite3_mutex *pX){
17997  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17998  assert( p->cnt==0 );
17999  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
18000  sqlite3_free(p);
18001}
18002
18003/*
18004** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
18005** to enter a mutex.  If another thread is already within the mutex,
18006** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
18007** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
18008** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
18009** be entered multiple times by the same thread.  In such cases the,
18010** mutex must be exited an equal number of times before another thread
18011** can enter.  If the same thread tries to enter any other kind of mutex
18012** more than once, the behavior is undefined.
18013*/
18014static void debugMutexEnter(sqlite3_mutex *pX){
18015  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
18016  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
18017  p->cnt++;
18018}
18019static int debugMutexTry(sqlite3_mutex *pX){
18020  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
18021  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
18022  p->cnt++;
18023  return SQLITE_OK;
18024}
18025
18026/*
18027** The sqlite3_mutex_leave() routine exits a mutex that was
18028** previously entered by the same thread.  The behavior
18029** is undefined if the mutex is not currently entered or
18030** is not currently allocated.  SQLite will never do either.
18031*/
18032static void debugMutexLeave(sqlite3_mutex *pX){
18033  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
18034  assert( debugMutexHeld(pX) );
18035  p->cnt--;
18036  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
18037}
18038
18039SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
18040  static const sqlite3_mutex_methods sMutex = {
18041    debugMutexInit,
18042    debugMutexEnd,
18043    debugMutexAlloc,
18044    debugMutexFree,
18045    debugMutexEnter,
18046    debugMutexTry,
18047    debugMutexLeave,
18048
18049    debugMutexHeld,
18050    debugMutexNotheld
18051  };
18052
18053  return &sMutex;
18054}
18055#endif /* SQLITE_DEBUG */
18056
18057/*
18058** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
18059** is used regardless of the run-time threadsafety setting.
18060*/
18061#ifdef SQLITE_MUTEX_NOOP
18062SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
18063  return sqlite3NoopMutex();
18064}
18065#endif /* defined(SQLITE_MUTEX_NOOP) */
18066#endif /* !defined(SQLITE_MUTEX_OMIT) */
18067
18068/************** End of mutex_noop.c ******************************************/
18069/************** Begin file mutex_unix.c **************************************/
18070/*
18071** 2007 August 28
18072**
18073** The author disclaims copyright to this source code.  In place of
18074** a legal notice, here is a blessing:
18075**
18076**    May you do good and not evil.
18077**    May you find forgiveness for yourself and forgive others.
18078**    May you share freely, never taking more than you give.
18079**
18080*************************************************************************
18081** This file contains the C functions that implement mutexes for pthreads
18082*/
18083
18084/*
18085** The code in this file is only used if we are compiling threadsafe
18086** under unix with pthreads.
18087**
18088** Note that this implementation requires a version of pthreads that
18089** supports recursive mutexes.
18090*/
18091#ifdef SQLITE_MUTEX_PTHREADS
18092
18093#include <pthread.h>
18094
18095/*
18096** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
18097** are necessary under two condidtions:  (1) Debug builds and (2) using
18098** home-grown mutexes.  Encapsulate these conditions into a single #define.
18099*/
18100#if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
18101# define SQLITE_MUTEX_NREF 1
18102#else
18103# define SQLITE_MUTEX_NREF 0
18104#endif
18105
18106/*
18107** Each recursive mutex is an instance of the following structure.
18108*/
18109struct sqlite3_mutex {
18110  pthread_mutex_t mutex;     /* Mutex controlling the lock */
18111#if SQLITE_MUTEX_NREF
18112  int id;                    /* Mutex type */
18113  volatile int nRef;         /* Number of entrances */
18114  volatile pthread_t owner;  /* Thread that is within this mutex */
18115  int trace;                 /* True to trace changes */
18116#endif
18117};
18118#if SQLITE_MUTEX_NREF
18119#define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
18120#else
18121#define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
18122#endif
18123
18124/*
18125** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
18126** intended for use only inside assert() statements.  On some platforms,
18127** there might be race conditions that can cause these routines to
18128** deliver incorrect results.  In particular, if pthread_equal() is
18129** not an atomic operation, then these routines might delivery
18130** incorrect results.  On most platforms, pthread_equal() is a
18131** comparison of two integers and is therefore atomic.  But we are
18132** told that HPUX is not such a platform.  If so, then these routines
18133** will not always work correctly on HPUX.
18134**
18135** On those platforms where pthread_equal() is not atomic, SQLite
18136** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
18137** make sure no assert() statements are evaluated and hence these
18138** routines are never called.
18139*/
18140#if !defined(NDEBUG) || defined(SQLITE_DEBUG)
18141static int pthreadMutexHeld(sqlite3_mutex *p){
18142  return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
18143}
18144static int pthreadMutexNotheld(sqlite3_mutex *p){
18145  return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
18146}
18147#endif
18148
18149/*
18150** Initialize and deinitialize the mutex subsystem.
18151*/
18152static int pthreadMutexInit(void){ return SQLITE_OK; }
18153static int pthreadMutexEnd(void){ return SQLITE_OK; }
18154
18155/*
18156** The sqlite3_mutex_alloc() routine allocates a new
18157** mutex and returns a pointer to it.  If it returns NULL
18158** that means that a mutex could not be allocated.  SQLite
18159** will unwind its stack and return an error.  The argument
18160** to sqlite3_mutex_alloc() is one of these integer constants:
18161**
18162** <ul>
18163** <li>  SQLITE_MUTEX_FAST
18164** <li>  SQLITE_MUTEX_RECURSIVE
18165** <li>  SQLITE_MUTEX_STATIC_MASTER
18166** <li>  SQLITE_MUTEX_STATIC_MEM
18167** <li>  SQLITE_MUTEX_STATIC_MEM2
18168** <li>  SQLITE_MUTEX_STATIC_PRNG
18169** <li>  SQLITE_MUTEX_STATIC_LRU
18170** <li>  SQLITE_MUTEX_STATIC_PMEM
18171** </ul>
18172**
18173** The first two constants cause sqlite3_mutex_alloc() to create
18174** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
18175** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
18176** The mutex implementation does not need to make a distinction
18177** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
18178** not want to.  But SQLite will only request a recursive mutex in
18179** cases where it really needs one.  If a faster non-recursive mutex
18180** implementation is available on the host platform, the mutex subsystem
18181** might return such a mutex in response to SQLITE_MUTEX_FAST.
18182**
18183** The other allowed parameters to sqlite3_mutex_alloc() each return
18184** a pointer to a static preexisting mutex.  Six static mutexes are
18185** used by the current version of SQLite.  Future versions of SQLite
18186** may add additional static mutexes.  Static mutexes are for internal
18187** use by SQLite only.  Applications that use SQLite mutexes should
18188** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
18189** SQLITE_MUTEX_RECURSIVE.
18190**
18191** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
18192** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
18193** returns a different mutex on every call.  But for the static
18194** mutex types, the same mutex is returned on every call that has
18195** the same type number.
18196*/
18197static sqlite3_mutex *pthreadMutexAlloc(int iType){
18198  static sqlite3_mutex staticMutexes[] = {
18199    SQLITE3_MUTEX_INITIALIZER,
18200    SQLITE3_MUTEX_INITIALIZER,
18201    SQLITE3_MUTEX_INITIALIZER,
18202    SQLITE3_MUTEX_INITIALIZER,
18203    SQLITE3_MUTEX_INITIALIZER,
18204    SQLITE3_MUTEX_INITIALIZER
18205  };
18206  sqlite3_mutex *p;
18207  switch( iType ){
18208    case SQLITE_MUTEX_RECURSIVE: {
18209      p = sqlite3MallocZero( sizeof(*p) );
18210      if( p ){
18211#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
18212        /* If recursive mutexes are not available, we will have to
18213        ** build our own.  See below. */
18214        pthread_mutex_init(&p->mutex, 0);
18215#else
18216        /* Use a recursive mutex if it is available */
18217        pthread_mutexattr_t recursiveAttr;
18218        pthread_mutexattr_init(&recursiveAttr);
18219        pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
18220        pthread_mutex_init(&p->mutex, &recursiveAttr);
18221        pthread_mutexattr_destroy(&recursiveAttr);
18222#endif
18223#if SQLITE_MUTEX_NREF
18224        p->id = iType;
18225#endif
18226      }
18227      break;
18228    }
18229    case SQLITE_MUTEX_FAST: {
18230      p = sqlite3MallocZero( sizeof(*p) );
18231      if( p ){
18232#if SQLITE_MUTEX_NREF
18233        p->id = iType;
18234#endif
18235        pthread_mutex_init(&p->mutex, 0);
18236      }
18237      break;
18238    }
18239    default: {
18240      assert( iType-2 >= 0 );
18241      assert( iType-2 < ArraySize(staticMutexes) );
18242      p = &staticMutexes[iType-2];
18243#if SQLITE_MUTEX_NREF
18244      p->id = iType;
18245#endif
18246      break;
18247    }
18248  }
18249  return p;
18250}
18251
18252
18253/*
18254** This routine deallocates a previously
18255** allocated mutex.  SQLite is careful to deallocate every
18256** mutex that it allocates.
18257*/
18258static void pthreadMutexFree(sqlite3_mutex *p){
18259  assert( p->nRef==0 );
18260  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
18261  pthread_mutex_destroy(&p->mutex);
18262  sqlite3_free(p);
18263}
18264
18265/*
18266** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
18267** to enter a mutex.  If another thread is already within the mutex,
18268** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
18269** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
18270** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
18271** be entered multiple times by the same thread.  In such cases the,
18272** mutex must be exited an equal number of times before another thread
18273** can enter.  If the same thread tries to enter any other kind of mutex
18274** more than once, the behavior is undefined.
18275*/
18276static void pthreadMutexEnter(sqlite3_mutex *p){
18277  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
18278
18279#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
18280  /* If recursive mutexes are not available, then we have to grow
18281  ** our own.  This implementation assumes that pthread_equal()
18282  ** is atomic - that it cannot be deceived into thinking self
18283  ** and p->owner are equal if p->owner changes between two values
18284  ** that are not equal to self while the comparison is taking place.
18285  ** This implementation also assumes a coherent cache - that
18286  ** separate processes cannot read different values from the same
18287  ** address at the same time.  If either of these two conditions
18288  ** are not met, then the mutexes will fail and problems will result.
18289  */
18290  {
18291    pthread_t self = pthread_self();
18292    if( p->nRef>0 && pthread_equal(p->owner, self) ){
18293      p->nRef++;
18294    }else{
18295      pthread_mutex_lock(&p->mutex);
18296      assert( p->nRef==0 );
18297      p->owner = self;
18298      p->nRef = 1;
18299    }
18300  }
18301#else
18302  /* Use the built-in recursive mutexes if they are available.
18303  */
18304  pthread_mutex_lock(&p->mutex);
18305#if SQLITE_MUTEX_NREF
18306  assert( p->nRef>0 || p->owner==0 );
18307  p->owner = pthread_self();
18308  p->nRef++;
18309#endif
18310#endif
18311
18312#ifdef SQLITE_DEBUG
18313  if( p->trace ){
18314    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18315  }
18316#endif
18317}
18318static int pthreadMutexTry(sqlite3_mutex *p){
18319  int rc;
18320  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
18321
18322#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
18323  /* If recursive mutexes are not available, then we have to grow
18324  ** our own.  This implementation assumes that pthread_equal()
18325  ** is atomic - that it cannot be deceived into thinking self
18326  ** and p->owner are equal if p->owner changes between two values
18327  ** that are not equal to self while the comparison is taking place.
18328  ** This implementation also assumes a coherent cache - that
18329  ** separate processes cannot read different values from the same
18330  ** address at the same time.  If either of these two conditions
18331  ** are not met, then the mutexes will fail and problems will result.
18332  */
18333  {
18334    pthread_t self = pthread_self();
18335    if( p->nRef>0 && pthread_equal(p->owner, self) ){
18336      p->nRef++;
18337      rc = SQLITE_OK;
18338    }else if( pthread_mutex_trylock(&p->mutex)==0 ){
18339      assert( p->nRef==0 );
18340      p->owner = self;
18341      p->nRef = 1;
18342      rc = SQLITE_OK;
18343    }else{
18344      rc = SQLITE_BUSY;
18345    }
18346  }
18347#else
18348  /* Use the built-in recursive mutexes if they are available.
18349  */
18350  if( pthread_mutex_trylock(&p->mutex)==0 ){
18351#if SQLITE_MUTEX_NREF
18352    p->owner = pthread_self();
18353    p->nRef++;
18354#endif
18355    rc = SQLITE_OK;
18356  }else{
18357    rc = SQLITE_BUSY;
18358  }
18359#endif
18360
18361#ifdef SQLITE_DEBUG
18362  if( rc==SQLITE_OK && p->trace ){
18363    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18364  }
18365#endif
18366  return rc;
18367}
18368
18369/*
18370** The sqlite3_mutex_leave() routine exits a mutex that was
18371** previously entered by the same thread.  The behavior
18372** is undefined if the mutex is not currently entered or
18373** is not currently allocated.  SQLite will never do either.
18374*/
18375static void pthreadMutexLeave(sqlite3_mutex *p){
18376  assert( pthreadMutexHeld(p) );
18377#if SQLITE_MUTEX_NREF
18378  p->nRef--;
18379  if( p->nRef==0 ) p->owner = 0;
18380#endif
18381  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
18382
18383#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
18384  if( p->nRef==0 ){
18385    pthread_mutex_unlock(&p->mutex);
18386  }
18387#else
18388  pthread_mutex_unlock(&p->mutex);
18389#endif
18390
18391#ifdef SQLITE_DEBUG
18392  if( p->trace ){
18393    printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18394  }
18395#endif
18396}
18397
18398SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
18399  static const sqlite3_mutex_methods sMutex = {
18400    pthreadMutexInit,
18401    pthreadMutexEnd,
18402    pthreadMutexAlloc,
18403    pthreadMutexFree,
18404    pthreadMutexEnter,
18405    pthreadMutexTry,
18406    pthreadMutexLeave,
18407#ifdef SQLITE_DEBUG
18408    pthreadMutexHeld,
18409    pthreadMutexNotheld
18410#else
18411    0,
18412    0
18413#endif
18414  };
18415
18416  return &sMutex;
18417}
18418
18419#endif /* SQLITE_MUTEX_PTHREADS */
18420
18421/************** End of mutex_unix.c ******************************************/
18422/************** Begin file mutex_w32.c ***************************************/
18423/*
18424** 2007 August 14
18425**
18426** The author disclaims copyright to this source code.  In place of
18427** a legal notice, here is a blessing:
18428**
18429**    May you do good and not evil.
18430**    May you find forgiveness for yourself and forgive others.
18431**    May you share freely, never taking more than you give.
18432**
18433*************************************************************************
18434** This file contains the C functions that implement mutexes for win32
18435*/
18436
18437/*
18438** The code in this file is only used if we are compiling multithreaded
18439** on a win32 system.
18440*/
18441#ifdef SQLITE_MUTEX_W32
18442
18443/*
18444** Each recursive mutex is an instance of the following structure.
18445*/
18446struct sqlite3_mutex {
18447  CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
18448  int id;                    /* Mutex type */
18449#ifdef SQLITE_DEBUG
18450  volatile int nRef;         /* Number of enterances */
18451  volatile DWORD owner;      /* Thread holding this mutex */
18452  int trace;                 /* True to trace changes */
18453#endif
18454};
18455#define SQLITE_W32_MUTEX_INITIALIZER { 0 }
18456#ifdef SQLITE_DEBUG
18457#define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0, 0 }
18458#else
18459#define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
18460#endif
18461
18462/*
18463** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
18464** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
18465**
18466** Here is an interesting observation:  Win95, Win98, and WinME lack
18467** the LockFileEx() API.  But we can still statically link against that
18468** API as long as we don't call it win running Win95/98/ME.  A call to
18469** this routine is used to determine if the host is Win95/98/ME or
18470** WinNT/2K/XP so that we will know whether or not we can safely call
18471** the LockFileEx() API.
18472**
18473** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
18474** which is only available if your application was compiled with
18475** _WIN32_WINNT defined to a value >= 0x0400.  Currently, the only
18476** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef
18477** this out as well.
18478*/
18479#if 0
18480#if SQLITE_OS_WINCE || SQLITE_OS_WINRT
18481# define mutexIsNT()  (1)
18482#else
18483  static int mutexIsNT(void){
18484    static int osType = 0;
18485    if( osType==0 ){
18486      OSVERSIONINFO sInfo;
18487      sInfo.dwOSVersionInfoSize = sizeof(sInfo);
18488      GetVersionEx(&sInfo);
18489      osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
18490    }
18491    return osType==2;
18492  }
18493#endif /* SQLITE_OS_WINCE */
18494#endif
18495
18496#ifdef SQLITE_DEBUG
18497/*
18498** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
18499** intended for use only inside assert() statements.
18500*/
18501static int winMutexHeld(sqlite3_mutex *p){
18502  return p->nRef!=0 && p->owner==GetCurrentThreadId();
18503}
18504static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
18505  return p->nRef==0 || p->owner!=tid;
18506}
18507static int winMutexNotheld(sqlite3_mutex *p){
18508  DWORD tid = GetCurrentThreadId();
18509  return winMutexNotheld2(p, tid);
18510}
18511#endif
18512
18513
18514/*
18515** Initialize and deinitialize the mutex subsystem.
18516*/
18517static sqlite3_mutex winMutex_staticMutexes[6] = {
18518  SQLITE3_MUTEX_INITIALIZER,
18519  SQLITE3_MUTEX_INITIALIZER,
18520  SQLITE3_MUTEX_INITIALIZER,
18521  SQLITE3_MUTEX_INITIALIZER,
18522  SQLITE3_MUTEX_INITIALIZER,
18523  SQLITE3_MUTEX_INITIALIZER
18524};
18525static int winMutex_isInit = 0;
18526/* As winMutexInit() and winMutexEnd() are called as part
18527** of the sqlite3_initialize and sqlite3_shutdown()
18528** processing, the "interlocked" magic is probably not
18529** strictly necessary.
18530*/
18531static long winMutex_lock = 0;
18532
18533SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
18534
18535static int winMutexInit(void){
18536  /* The first to increment to 1 does actual initialization */
18537  if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
18538    int i;
18539    for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
18540#if SQLITE_OS_WINRT
18541      InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
18542#else
18543      InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
18544#endif
18545    }
18546    winMutex_isInit = 1;
18547  }else{
18548    /* Someone else is in the process of initing the static mutexes */
18549    while( !winMutex_isInit ){
18550      sqlite3_win32_sleep(1);
18551    }
18552  }
18553  return SQLITE_OK;
18554}
18555
18556static int winMutexEnd(void){
18557  /* The first to decrement to 0 does actual shutdown
18558  ** (which should be the last to shutdown.) */
18559  if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
18560    if( winMutex_isInit==1 ){
18561      int i;
18562      for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
18563        DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
18564      }
18565      winMutex_isInit = 0;
18566    }
18567  }
18568  return SQLITE_OK;
18569}
18570
18571/*
18572** The sqlite3_mutex_alloc() routine allocates a new
18573** mutex and returns a pointer to it.  If it returns NULL
18574** that means that a mutex could not be allocated.  SQLite
18575** will unwind its stack and return an error.  The argument
18576** to sqlite3_mutex_alloc() is one of these integer constants:
18577**
18578** <ul>
18579** <li>  SQLITE_MUTEX_FAST
18580** <li>  SQLITE_MUTEX_RECURSIVE
18581** <li>  SQLITE_MUTEX_STATIC_MASTER
18582** <li>  SQLITE_MUTEX_STATIC_MEM
18583** <li>  SQLITE_MUTEX_STATIC_MEM2
18584** <li>  SQLITE_MUTEX_STATIC_PRNG
18585** <li>  SQLITE_MUTEX_STATIC_LRU
18586** <li>  SQLITE_MUTEX_STATIC_PMEM
18587** </ul>
18588**
18589** The first two constants cause sqlite3_mutex_alloc() to create
18590** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
18591** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
18592** The mutex implementation does not need to make a distinction
18593** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
18594** not want to.  But SQLite will only request a recursive mutex in
18595** cases where it really needs one.  If a faster non-recursive mutex
18596** implementation is available on the host platform, the mutex subsystem
18597** might return such a mutex in response to SQLITE_MUTEX_FAST.
18598**
18599** The other allowed parameters to sqlite3_mutex_alloc() each return
18600** a pointer to a static preexisting mutex.  Six static mutexes are
18601** used by the current version of SQLite.  Future versions of SQLite
18602** may add additional static mutexes.  Static mutexes are for internal
18603** use by SQLite only.  Applications that use SQLite mutexes should
18604** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
18605** SQLITE_MUTEX_RECURSIVE.
18606**
18607** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
18608** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
18609** returns a different mutex on every call.  But for the static
18610** mutex types, the same mutex is returned on every call that has
18611** the same type number.
18612*/
18613static sqlite3_mutex *winMutexAlloc(int iType){
18614  sqlite3_mutex *p;
18615
18616  switch( iType ){
18617    case SQLITE_MUTEX_FAST:
18618    case SQLITE_MUTEX_RECURSIVE: {
18619      p = sqlite3MallocZero( sizeof(*p) );
18620      if( p ){
18621#ifdef SQLITE_DEBUG
18622        p->id = iType;
18623#endif
18624#if SQLITE_OS_WINRT
18625        InitializeCriticalSectionEx(&p->mutex, 0, 0);
18626#else
18627        InitializeCriticalSection(&p->mutex);
18628#endif
18629      }
18630      break;
18631    }
18632    default: {
18633      assert( winMutex_isInit==1 );
18634      assert( iType-2 >= 0 );
18635      assert( iType-2 < ArraySize(winMutex_staticMutexes) );
18636      p = &winMutex_staticMutexes[iType-2];
18637#ifdef SQLITE_DEBUG
18638      p->id = iType;
18639#endif
18640      break;
18641    }
18642  }
18643  return p;
18644}
18645
18646
18647/*
18648** This routine deallocates a previously
18649** allocated mutex.  SQLite is careful to deallocate every
18650** mutex that it allocates.
18651*/
18652static void winMutexFree(sqlite3_mutex *p){
18653  assert( p );
18654  assert( p->nRef==0 && p->owner==0 );
18655  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
18656  DeleteCriticalSection(&p->mutex);
18657  sqlite3_free(p);
18658}
18659
18660/*
18661** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
18662** to enter a mutex.  If another thread is already within the mutex,
18663** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
18664** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
18665** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
18666** be entered multiple times by the same thread.  In such cases the,
18667** mutex must be exited an equal number of times before another thread
18668** can enter.  If the same thread tries to enter any other kind of mutex
18669** more than once, the behavior is undefined.
18670*/
18671static void winMutexEnter(sqlite3_mutex *p){
18672#ifdef SQLITE_DEBUG
18673  DWORD tid = GetCurrentThreadId();
18674  assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
18675#endif
18676  EnterCriticalSection(&p->mutex);
18677#ifdef SQLITE_DEBUG
18678  assert( p->nRef>0 || p->owner==0 );
18679  p->owner = tid;
18680  p->nRef++;
18681  if( p->trace ){
18682    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18683  }
18684#endif
18685}
18686static int winMutexTry(sqlite3_mutex *p){
18687#ifndef NDEBUG
18688  DWORD tid = GetCurrentThreadId();
18689#endif
18690  int rc = SQLITE_BUSY;
18691  assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
18692  /*
18693  ** The sqlite3_mutex_try() routine is very rarely used, and when it
18694  ** is used it is merely an optimization.  So it is OK for it to always
18695  ** fail.
18696  **
18697  ** The TryEnterCriticalSection() interface is only available on WinNT.
18698  ** And some windows compilers complain if you try to use it without
18699  ** first doing some #defines that prevent SQLite from building on Win98.
18700  ** For that reason, we will omit this optimization for now.  See
18701  ** ticket #2685.
18702  */
18703#if 0
18704  if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
18705    p->owner = tid;
18706    p->nRef++;
18707    rc = SQLITE_OK;
18708  }
18709#else
18710  UNUSED_PARAMETER(p);
18711#endif
18712#ifdef SQLITE_DEBUG
18713  if( rc==SQLITE_OK && p->trace ){
18714    printf("try mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18715  }
18716#endif
18717  return rc;
18718}
18719
18720/*
18721** The sqlite3_mutex_leave() routine exits a mutex that was
18722** previously entered by the same thread.  The behavior
18723** is undefined if the mutex is not currently entered or
18724** is not currently allocated.  SQLite will never do either.
18725*/
18726static void winMutexLeave(sqlite3_mutex *p){
18727#ifndef NDEBUG
18728  DWORD tid = GetCurrentThreadId();
18729  assert( p->nRef>0 );
18730  assert( p->owner==tid );
18731  p->nRef--;
18732  if( p->nRef==0 ) p->owner = 0;
18733  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
18734#endif
18735  LeaveCriticalSection(&p->mutex);
18736#ifdef SQLITE_DEBUG
18737  if( p->trace ){
18738    printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18739  }
18740#endif
18741}
18742
18743SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
18744  static const sqlite3_mutex_methods sMutex = {
18745    winMutexInit,
18746    winMutexEnd,
18747    winMutexAlloc,
18748    winMutexFree,
18749    winMutexEnter,
18750    winMutexTry,
18751    winMutexLeave,
18752#ifdef SQLITE_DEBUG
18753    winMutexHeld,
18754    winMutexNotheld
18755#else
18756    0,
18757    0
18758#endif
18759  };
18760
18761  return &sMutex;
18762}
18763#endif /* SQLITE_MUTEX_W32 */
18764
18765/************** End of mutex_w32.c *******************************************/
18766/************** Begin file malloc.c ******************************************/
18767/*
18768** 2001 September 15
18769**
18770** The author disclaims copyright to this source code.  In place of
18771** a legal notice, here is a blessing:
18772**
18773**    May you do good and not evil.
18774**    May you find forgiveness for yourself and forgive others.
18775**    May you share freely, never taking more than you give.
18776**
18777*************************************************************************
18778**
18779** Memory allocation functions used throughout sqlite.
18780*/
18781/* #include <stdarg.h> */
18782
18783/*
18784** Attempt to release up to n bytes of non-essential memory currently
18785** held by SQLite. An example of non-essential memory is memory used to
18786** cache database pages that are not currently in use.
18787*/
18788SQLITE_API int sqlite3_release_memory(int n){
18789#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
18790  return sqlite3PcacheReleaseMemory(n);
18791#else
18792  /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
18793  ** is a no-op returning zero if SQLite is not compiled with
18794  ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
18795  UNUSED_PARAMETER(n);
18796  return 0;
18797#endif
18798}
18799
18800/*
18801** An instance of the following object records the location of
18802** each unused scratch buffer.
18803*/
18804typedef struct ScratchFreeslot {
18805  struct ScratchFreeslot *pNext;   /* Next unused scratch buffer */
18806} ScratchFreeslot;
18807
18808/*
18809** State information local to the memory allocation subsystem.
18810*/
18811static SQLITE_WSD struct Mem0Global {
18812  sqlite3_mutex *mutex;         /* Mutex to serialize access */
18813
18814  /*
18815  ** The alarm callback and its arguments.  The mem0.mutex lock will
18816  ** be held while the callback is running.  Recursive calls into
18817  ** the memory subsystem are allowed, but no new callbacks will be
18818  ** issued.
18819  */
18820  sqlite3_int64 alarmThreshold;
18821  void (*alarmCallback)(void*, sqlite3_int64,int);
18822  void *alarmArg;
18823
18824  /*
18825  ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
18826  ** (so that a range test can be used to determine if an allocation
18827  ** being freed came from pScratch) and a pointer to the list of
18828  ** unused scratch allocations.
18829  */
18830  void *pScratchEnd;
18831  ScratchFreeslot *pScratchFree;
18832  u32 nScratchFree;
18833
18834  /*
18835  ** True if heap is nearly "full" where "full" is defined by the
18836  ** sqlite3_soft_heap_limit() setting.
18837  */
18838  int nearlyFull;
18839} mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
18840
18841#define mem0 GLOBAL(struct Mem0Global, mem0)
18842
18843/*
18844** This routine runs when the memory allocator sees that the
18845** total memory allocation is about to exceed the soft heap
18846** limit.
18847*/
18848static void softHeapLimitEnforcer(
18849  void *NotUsed,
18850  sqlite3_int64 NotUsed2,
18851  int allocSize
18852){
18853  UNUSED_PARAMETER2(NotUsed, NotUsed2);
18854  sqlite3_release_memory(allocSize);
18855}
18856
18857/*
18858** Change the alarm callback
18859*/
18860static int sqlite3MemoryAlarm(
18861  void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
18862  void *pArg,
18863  sqlite3_int64 iThreshold
18864){
18865  int nUsed;
18866  sqlite3_mutex_enter(mem0.mutex);
18867  mem0.alarmCallback = xCallback;
18868  mem0.alarmArg = pArg;
18869  mem0.alarmThreshold = iThreshold;
18870  nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
18871  mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed);
18872  sqlite3_mutex_leave(mem0.mutex);
18873  return SQLITE_OK;
18874}
18875
18876#ifndef SQLITE_OMIT_DEPRECATED
18877/*
18878** Deprecated external interface.  Internal/core SQLite code
18879** should call sqlite3MemoryAlarm.
18880*/
18881SQLITE_API int sqlite3_memory_alarm(
18882  void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
18883  void *pArg,
18884  sqlite3_int64 iThreshold
18885){
18886  return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
18887}
18888#endif
18889
18890/*
18891** Set the soft heap-size limit for the library. Passing a zero or
18892** negative value indicates no limit.
18893*/
18894SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
18895  sqlite3_int64 priorLimit;
18896  sqlite3_int64 excess;
18897#ifndef SQLITE_OMIT_AUTOINIT
18898  int rc = sqlite3_initialize();
18899  if( rc ) return -1;
18900#endif
18901  sqlite3_mutex_enter(mem0.mutex);
18902  priorLimit = mem0.alarmThreshold;
18903  sqlite3_mutex_leave(mem0.mutex);
18904  if( n<0 ) return priorLimit;
18905  if( n>0 ){
18906    sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, n);
18907  }else{
18908    sqlite3MemoryAlarm(0, 0, 0);
18909  }
18910  excess = sqlite3_memory_used() - n;
18911  if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
18912  return priorLimit;
18913}
18914SQLITE_API void sqlite3_soft_heap_limit(int n){
18915  if( n<0 ) n = 0;
18916  sqlite3_soft_heap_limit64(n);
18917}
18918
18919/*
18920** Initialize the memory allocation subsystem.
18921*/
18922SQLITE_PRIVATE int sqlite3MallocInit(void){
18923  if( sqlite3GlobalConfig.m.xMalloc==0 ){
18924    sqlite3MemSetDefault();
18925  }
18926  memset(&mem0, 0, sizeof(mem0));
18927  if( sqlite3GlobalConfig.bCoreMutex ){
18928    mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
18929  }
18930  if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
18931      && sqlite3GlobalConfig.nScratch>0 ){
18932    int i, n, sz;
18933    ScratchFreeslot *pSlot;
18934    sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
18935    sqlite3GlobalConfig.szScratch = sz;
18936    pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
18937    n = sqlite3GlobalConfig.nScratch;
18938    mem0.pScratchFree = pSlot;
18939    mem0.nScratchFree = n;
18940    for(i=0; i<n-1; i++){
18941      pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
18942      pSlot = pSlot->pNext;
18943    }
18944    pSlot->pNext = 0;
18945    mem0.pScratchEnd = (void*)&pSlot[1];
18946  }else{
18947    mem0.pScratchEnd = 0;
18948    sqlite3GlobalConfig.pScratch = 0;
18949    sqlite3GlobalConfig.szScratch = 0;
18950    sqlite3GlobalConfig.nScratch = 0;
18951  }
18952  if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
18953      || sqlite3GlobalConfig.nPage<1 ){
18954    sqlite3GlobalConfig.pPage = 0;
18955    sqlite3GlobalConfig.szPage = 0;
18956    sqlite3GlobalConfig.nPage = 0;
18957  }
18958  return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
18959}
18960
18961/*
18962** Return true if the heap is currently under memory pressure - in other
18963** words if the amount of heap used is close to the limit set by
18964** sqlite3_soft_heap_limit().
18965*/
18966SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
18967  return mem0.nearlyFull;
18968}
18969
18970/*
18971** Deinitialize the memory allocation subsystem.
18972*/
18973SQLITE_PRIVATE void sqlite3MallocEnd(void){
18974  if( sqlite3GlobalConfig.m.xShutdown ){
18975    sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
18976  }
18977  memset(&mem0, 0, sizeof(mem0));
18978}
18979
18980/*
18981** Return the amount of memory currently checked out.
18982*/
18983SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
18984  int n, mx;
18985  sqlite3_int64 res;
18986  sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
18987  res = (sqlite3_int64)n;  /* Work around bug in Borland C. Ticket #3216 */
18988  return res;
18989}
18990
18991/*
18992** Return the maximum amount of memory that has ever been
18993** checked out since either the beginning of this process
18994** or since the most recent reset.
18995*/
18996SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
18997  int n, mx;
18998  sqlite3_int64 res;
18999  sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
19000  res = (sqlite3_int64)mx;  /* Work around bug in Borland C. Ticket #3216 */
19001  return res;
19002}
19003
19004/*
19005** Trigger the alarm
19006*/
19007static void sqlite3MallocAlarm(int nByte){
19008  void (*xCallback)(void*,sqlite3_int64,int);
19009  sqlite3_int64 nowUsed;
19010  void *pArg;
19011  if( mem0.alarmCallback==0 ) return;
19012  xCallback = mem0.alarmCallback;
19013  nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
19014  pArg = mem0.alarmArg;
19015  mem0.alarmCallback = 0;
19016  sqlite3_mutex_leave(mem0.mutex);
19017  xCallback(pArg, nowUsed, nByte);
19018  sqlite3_mutex_enter(mem0.mutex);
19019  mem0.alarmCallback = xCallback;
19020  mem0.alarmArg = pArg;
19021}
19022
19023/*
19024** Do a memory allocation with statistics and alarms.  Assume the
19025** lock is already held.
19026*/
19027static int mallocWithAlarm(int n, void **pp){
19028  int nFull;
19029  void *p;
19030  assert( sqlite3_mutex_held(mem0.mutex) );
19031  nFull = sqlite3GlobalConfig.m.xRoundup(n);
19032  sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
19033  if( mem0.alarmCallback!=0 ){
19034    int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
19035    if( nUsed >= mem0.alarmThreshold - nFull ){
19036      mem0.nearlyFull = 1;
19037      sqlite3MallocAlarm(nFull);
19038    }else{
19039      mem0.nearlyFull = 0;
19040    }
19041  }
19042  p = sqlite3GlobalConfig.m.xMalloc(nFull);
19043#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
19044  if( p==0 && mem0.alarmCallback ){
19045    sqlite3MallocAlarm(nFull);
19046    p = sqlite3GlobalConfig.m.xMalloc(nFull);
19047  }
19048#endif
19049  if( p ){
19050    nFull = sqlite3MallocSize(p);
19051    sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
19052    sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, 1);
19053  }
19054  *pp = p;
19055  return nFull;
19056}
19057
19058/*
19059** Allocate memory.  This routine is like sqlite3_malloc() except that it
19060** assumes the memory subsystem has already been initialized.
19061*/
19062SQLITE_PRIVATE void *sqlite3Malloc(int n){
19063  void *p;
19064  if( n<=0               /* IMP: R-65312-04917 */
19065   || n>=0x7fffff00
19066  ){
19067    /* A memory allocation of a number of bytes which is near the maximum
19068    ** signed integer value might cause an integer overflow inside of the
19069    ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
19070    ** 255 bytes of overhead.  SQLite itself will never use anything near
19071    ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
19072    p = 0;
19073  }else if( sqlite3GlobalConfig.bMemstat ){
19074    sqlite3_mutex_enter(mem0.mutex);
19075    mallocWithAlarm(n, &p);
19076    sqlite3_mutex_leave(mem0.mutex);
19077  }else{
19078    p = sqlite3GlobalConfig.m.xMalloc(n);
19079  }
19080  assert( EIGHT_BYTE_ALIGNMENT(p) );  /* IMP: R-04675-44850 */
19081  return p;
19082}
19083
19084/*
19085** This version of the memory allocation is for use by the application.
19086** First make sure the memory subsystem is initialized, then do the
19087** allocation.
19088*/
19089SQLITE_API void *sqlite3_malloc(int n){
19090#ifndef SQLITE_OMIT_AUTOINIT
19091  if( sqlite3_initialize() ) return 0;
19092#endif
19093  return sqlite3Malloc(n);
19094}
19095
19096/*
19097** Each thread may only have a single outstanding allocation from
19098** xScratchMalloc().  We verify this constraint in the single-threaded
19099** case by setting scratchAllocOut to 1 when an allocation
19100** is outstanding clearing it when the allocation is freed.
19101*/
19102#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
19103static int scratchAllocOut = 0;
19104#endif
19105
19106
19107/*
19108** Allocate memory that is to be used and released right away.
19109** This routine is similar to alloca() in that it is not intended
19110** for situations where the memory might be held long-term.  This
19111** routine is intended to get memory to old large transient data
19112** structures that would not normally fit on the stack of an
19113** embedded processor.
19114*/
19115SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
19116  void *p;
19117  assert( n>0 );
19118
19119  sqlite3_mutex_enter(mem0.mutex);
19120  if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
19121    p = mem0.pScratchFree;
19122    mem0.pScratchFree = mem0.pScratchFree->pNext;
19123    mem0.nScratchFree--;
19124    sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
19125    sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
19126    sqlite3_mutex_leave(mem0.mutex);
19127  }else{
19128    if( sqlite3GlobalConfig.bMemstat ){
19129      sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
19130      n = mallocWithAlarm(n, &p);
19131      if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
19132      sqlite3_mutex_leave(mem0.mutex);
19133    }else{
19134      sqlite3_mutex_leave(mem0.mutex);
19135      p = sqlite3GlobalConfig.m.xMalloc(n);
19136    }
19137    sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
19138  }
19139  assert( sqlite3_mutex_notheld(mem0.mutex) );
19140
19141
19142#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
19143  /* Verify that no more than two scratch allocations per thread
19144  ** are outstanding at one time.  (This is only checked in the
19145  ** single-threaded case since checking in the multi-threaded case
19146  ** would be much more complicated.) */
19147  assert( scratchAllocOut<=1 );
19148  if( p ) scratchAllocOut++;
19149#endif
19150
19151  return p;
19152}
19153SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
19154  if( p ){
19155
19156#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
19157    /* Verify that no more than two scratch allocation per thread
19158    ** is outstanding at one time.  (This is only checked in the
19159    ** single-threaded case since checking in the multi-threaded case
19160    ** would be much more complicated.) */
19161    assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
19162    scratchAllocOut--;
19163#endif
19164
19165    if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
19166      /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
19167      ScratchFreeslot *pSlot;
19168      pSlot = (ScratchFreeslot*)p;
19169      sqlite3_mutex_enter(mem0.mutex);
19170      pSlot->pNext = mem0.pScratchFree;
19171      mem0.pScratchFree = pSlot;
19172      mem0.nScratchFree++;
19173      assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
19174      sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
19175      sqlite3_mutex_leave(mem0.mutex);
19176    }else{
19177      /* Release memory back to the heap */
19178      assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
19179      assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) );
19180      sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
19181      if( sqlite3GlobalConfig.bMemstat ){
19182        int iSize = sqlite3MallocSize(p);
19183        sqlite3_mutex_enter(mem0.mutex);
19184        sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
19185        sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
19186        sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
19187        sqlite3GlobalConfig.m.xFree(p);
19188        sqlite3_mutex_leave(mem0.mutex);
19189      }else{
19190        sqlite3GlobalConfig.m.xFree(p);
19191      }
19192    }
19193  }
19194}
19195
19196/*
19197** TRUE if p is a lookaside memory allocation from db
19198*/
19199#ifndef SQLITE_OMIT_LOOKASIDE
19200static int isLookaside(sqlite3 *db, void *p){
19201  return p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
19202}
19203#else
19204#define isLookaside(A,B) 0
19205#endif
19206
19207/*
19208** Return the size of a memory allocation previously obtained from
19209** sqlite3Malloc() or sqlite3_malloc().
19210*/
19211SQLITE_PRIVATE int sqlite3MallocSize(void *p){
19212  assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
19213  assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
19214  return sqlite3GlobalConfig.m.xSize(p);
19215}
19216SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
19217  assert( db==0 || sqlite3_mutex_held(db->mutex) );
19218  if( db && isLookaside(db, p) ){
19219    return db->lookaside.sz;
19220  }else{
19221    assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
19222    assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
19223    assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
19224    return sqlite3GlobalConfig.m.xSize(p);
19225  }
19226}
19227
19228/*
19229** Free memory previously obtained from sqlite3Malloc().
19230*/
19231SQLITE_API void sqlite3_free(void *p){
19232  if( p==0 ) return;  /* IMP: R-49053-54554 */
19233  assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
19234  assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
19235  if( sqlite3GlobalConfig.bMemstat ){
19236    sqlite3_mutex_enter(mem0.mutex);
19237    sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
19238    sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
19239    sqlite3GlobalConfig.m.xFree(p);
19240    sqlite3_mutex_leave(mem0.mutex);
19241  }else{
19242    sqlite3GlobalConfig.m.xFree(p);
19243  }
19244}
19245
19246/*
19247** Free memory that might be associated with a particular database
19248** connection.
19249*/
19250SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
19251  assert( db==0 || sqlite3_mutex_held(db->mutex) );
19252  if( db ){
19253    if( db->pnBytesFreed ){
19254      *db->pnBytesFreed += sqlite3DbMallocSize(db, p);
19255      return;
19256    }
19257    if( isLookaside(db, p) ){
19258      LookasideSlot *pBuf = (LookasideSlot*)p;
19259#if SQLITE_DEBUG
19260      /* Trash all content in the buffer being freed */
19261      memset(p, 0xaa, db->lookaside.sz);
19262#endif
19263      pBuf->pNext = db->lookaside.pFree;
19264      db->lookaside.pFree = pBuf;
19265      db->lookaside.nOut--;
19266      return;
19267    }
19268  }
19269  assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
19270  assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
19271  assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
19272  sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
19273  sqlite3_free(p);
19274}
19275
19276/*
19277** Change the size of an existing memory allocation
19278*/
19279SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
19280  int nOld, nNew, nDiff;
19281  void *pNew;
19282  if( pOld==0 ){
19283    return sqlite3Malloc(nBytes); /* IMP: R-28354-25769 */
19284  }
19285  if( nBytes<=0 ){
19286    sqlite3_free(pOld); /* IMP: R-31593-10574 */
19287    return 0;
19288  }
19289  if( nBytes>=0x7fffff00 ){
19290    /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
19291    return 0;
19292  }
19293  nOld = sqlite3MallocSize(pOld);
19294  /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
19295  ** argument to xRealloc is always a value returned by a prior call to
19296  ** xRoundup. */
19297  nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
19298  if( nOld==nNew ){
19299    pNew = pOld;
19300  }else if( sqlite3GlobalConfig.bMemstat ){
19301    sqlite3_mutex_enter(mem0.mutex);
19302    sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
19303    nDiff = nNew - nOld;
19304    if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >=
19305          mem0.alarmThreshold-nDiff ){
19306      sqlite3MallocAlarm(nDiff);
19307    }
19308    assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
19309    assert( sqlite3MemdebugNoType(pOld, ~MEMTYPE_HEAP) );
19310    pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
19311    if( pNew==0 && mem0.alarmCallback ){
19312      sqlite3MallocAlarm(nBytes);
19313      pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
19314    }
19315    if( pNew ){
19316      nNew = sqlite3MallocSize(pNew);
19317      sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
19318    }
19319    sqlite3_mutex_leave(mem0.mutex);
19320  }else{
19321    pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
19322  }
19323  assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-04675-44850 */
19324  return pNew;
19325}
19326
19327/*
19328** The public interface to sqlite3Realloc.  Make sure that the memory
19329** subsystem is initialized prior to invoking sqliteRealloc.
19330*/
19331SQLITE_API void *sqlite3_realloc(void *pOld, int n){
19332#ifndef SQLITE_OMIT_AUTOINIT
19333  if( sqlite3_initialize() ) return 0;
19334#endif
19335  return sqlite3Realloc(pOld, n);
19336}
19337
19338
19339/*
19340** Allocate and zero memory.
19341*/
19342SQLITE_PRIVATE void *sqlite3MallocZero(int n){
19343  void *p = sqlite3Malloc(n);
19344  if( p ){
19345    memset(p, 0, n);
19346  }
19347  return p;
19348}
19349
19350/*
19351** Allocate and zero memory.  If the allocation fails, make
19352** the mallocFailed flag in the connection pointer.
19353*/
19354SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
19355  void *p = sqlite3DbMallocRaw(db, n);
19356  if( p ){
19357    memset(p, 0, n);
19358  }
19359  return p;
19360}
19361
19362/*
19363** Allocate and zero memory.  If the allocation fails, make
19364** the mallocFailed flag in the connection pointer.
19365**
19366** If db!=0 and db->mallocFailed is true (indicating a prior malloc
19367** failure on the same database connection) then always return 0.
19368** Hence for a particular database connection, once malloc starts
19369** failing, it fails consistently until mallocFailed is reset.
19370** This is an important assumption.  There are many places in the
19371** code that do things like this:
19372**
19373**         int *a = (int*)sqlite3DbMallocRaw(db, 100);
19374**         int *b = (int*)sqlite3DbMallocRaw(db, 200);
19375**         if( b ) a[10] = 9;
19376**
19377** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
19378** that all prior mallocs (ex: "a") worked too.
19379*/
19380SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
19381  void *p;
19382  assert( db==0 || sqlite3_mutex_held(db->mutex) );
19383  assert( db==0 || db->pnBytesFreed==0 );
19384#ifndef SQLITE_OMIT_LOOKASIDE
19385  if( db ){
19386    LookasideSlot *pBuf;
19387    if( db->mallocFailed ){
19388      return 0;
19389    }
19390    if( db->lookaside.bEnabled ){
19391      if( n>db->lookaside.sz ){
19392        db->lookaside.anStat[1]++;
19393      }else if( (pBuf = db->lookaside.pFree)==0 ){
19394        db->lookaside.anStat[2]++;
19395      }else{
19396        db->lookaside.pFree = pBuf->pNext;
19397        db->lookaside.nOut++;
19398        db->lookaside.anStat[0]++;
19399        if( db->lookaside.nOut>db->lookaside.mxOut ){
19400          db->lookaside.mxOut = db->lookaside.nOut;
19401        }
19402        return (void*)pBuf;
19403      }
19404    }
19405  }
19406#else
19407  if( db && db->mallocFailed ){
19408    return 0;
19409  }
19410#endif
19411  p = sqlite3Malloc(n);
19412  if( !p && db ){
19413    db->mallocFailed = 1;
19414  }
19415  sqlite3MemdebugSetType(p, MEMTYPE_DB |
19416         ((db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
19417  return p;
19418}
19419
19420/*
19421** Resize the block of memory pointed to by p to n bytes. If the
19422** resize fails, set the mallocFailed flag in the connection object.
19423*/
19424SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
19425  void *pNew = 0;
19426  assert( db!=0 );
19427  assert( sqlite3_mutex_held(db->mutex) );
19428  if( db->mallocFailed==0 ){
19429    if( p==0 ){
19430      return sqlite3DbMallocRaw(db, n);
19431    }
19432    if( isLookaside(db, p) ){
19433      if( n<=db->lookaside.sz ){
19434        return p;
19435      }
19436      pNew = sqlite3DbMallocRaw(db, n);
19437      if( pNew ){
19438        memcpy(pNew, p, db->lookaside.sz);
19439        sqlite3DbFree(db, p);
19440      }
19441    }else{
19442      assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
19443      assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
19444      sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
19445      pNew = sqlite3_realloc(p, n);
19446      if( !pNew ){
19447        sqlite3MemdebugSetType(p, MEMTYPE_DB|MEMTYPE_HEAP);
19448        db->mallocFailed = 1;
19449      }
19450      sqlite3MemdebugSetType(pNew, MEMTYPE_DB |
19451            (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
19452    }
19453  }
19454  return pNew;
19455}
19456
19457/*
19458** Attempt to reallocate p.  If the reallocation fails, then free p
19459** and set the mallocFailed flag in the database connection.
19460*/
19461SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
19462  void *pNew;
19463  pNew = sqlite3DbRealloc(db, p, n);
19464  if( !pNew ){
19465    sqlite3DbFree(db, p);
19466  }
19467  return pNew;
19468}
19469
19470/*
19471** Make a copy of a string in memory obtained from sqliteMalloc(). These
19472** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
19473** is because when memory debugging is turned on, these two functions are
19474** called via macros that record the current file and line number in the
19475** ThreadData structure.
19476*/
19477SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
19478  char *zNew;
19479  size_t n;
19480  if( z==0 ){
19481    return 0;
19482  }
19483  n = sqlite3Strlen30(z) + 1;
19484  assert( (n&0x7fffffff)==n );
19485  zNew = sqlite3DbMallocRaw(db, (int)n);
19486  if( zNew ){
19487    memcpy(zNew, z, n);
19488  }
19489  return zNew;
19490}
19491SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
19492  char *zNew;
19493  if( z==0 ){
19494    return 0;
19495  }
19496  assert( (n&0x7fffffff)==n );
19497  zNew = sqlite3DbMallocRaw(db, n+1);
19498  if( zNew ){
19499    memcpy(zNew, z, n);
19500    zNew[n] = 0;
19501  }
19502  return zNew;
19503}
19504
19505/*
19506** Create a string from the zFromat argument and the va_list that follows.
19507** Store the string in memory obtained from sqliteMalloc() and make *pz
19508** point to that string.
19509*/
19510SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
19511  va_list ap;
19512  char *z;
19513
19514  va_start(ap, zFormat);
19515  z = sqlite3VMPrintf(db, zFormat, ap);
19516  va_end(ap);
19517  sqlite3DbFree(db, *pz);
19518  *pz = z;
19519}
19520
19521
19522/*
19523** This function must be called before exiting any API function (i.e.
19524** returning control to the user) that has called sqlite3_malloc or
19525** sqlite3_realloc.
19526**
19527** The returned value is normally a copy of the second argument to this
19528** function. However, if a malloc() failure has occurred since the previous
19529** invocation SQLITE_NOMEM is returned instead.
19530**
19531** If the first argument, db, is not NULL and a malloc() error has occurred,
19532** then the connection error-code (the value returned by sqlite3_errcode())
19533** is set to SQLITE_NOMEM.
19534*/
19535SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
19536  /* If the db handle is not NULL, then we must hold the connection handle
19537  ** mutex here. Otherwise the read (and possible write) of db->mallocFailed
19538  ** is unsafe, as is the call to sqlite3Error().
19539  */
19540  assert( !db || sqlite3_mutex_held(db->mutex) );
19541  if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
19542    sqlite3Error(db, SQLITE_NOMEM, 0);
19543    db->mallocFailed = 0;
19544    rc = SQLITE_NOMEM;
19545  }
19546  return rc & (db ? db->errMask : 0xff);
19547}
19548
19549/************** End of malloc.c **********************************************/
19550/************** Begin file printf.c ******************************************/
19551/*
19552** The "printf" code that follows dates from the 1980's.  It is in
19553** the public domain.  The original comments are included here for
19554** completeness.  They are very out-of-date but might be useful as
19555** an historical reference.  Most of the "enhancements" have been backed
19556** out so that the functionality is now the same as standard printf().
19557**
19558**************************************************************************
19559**
19560** This file contains code for a set of "printf"-like routines.  These
19561** routines format strings much like the printf() from the standard C
19562** library, though the implementation here has enhancements to support
19563** SQLlite.
19564*/
19565
19566/*
19567** Conversion types fall into various categories as defined by the
19568** following enumeration.
19569*/
19570#define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
19571#define etFLOAT       2 /* Floating point.  %f */
19572#define etEXP         3 /* Exponentional notation. %e and %E */
19573#define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
19574#define etSIZE        5 /* Return number of characters processed so far. %n */
19575#define etSTRING      6 /* Strings. %s */
19576#define etDYNSTRING   7 /* Dynamically allocated strings. %z */
19577#define etPERCENT     8 /* Percent symbol. %% */
19578#define etCHARX       9 /* Characters. %c */
19579/* The rest are extensions, not normally found in printf() */
19580#define etSQLESCAPE  10 /* Strings with '\'' doubled.  %q */
19581#define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
19582                          NULL pointers replaced by SQL NULL.  %Q */
19583#define etTOKEN      12 /* a pointer to a Token structure */
19584#define etSRCLIST    13 /* a pointer to a SrcList */
19585#define etPOINTER    14 /* The %p conversion */
19586#define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
19587#define etORDINAL    16 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
19588
19589#define etINVALID     0 /* Any unrecognized conversion type */
19590
19591
19592/*
19593** An "etByte" is an 8-bit unsigned value.
19594*/
19595typedef unsigned char etByte;
19596
19597/*
19598** Each builtin conversion character (ex: the 'd' in "%d") is described
19599** by an instance of the following structure
19600*/
19601typedef struct et_info {   /* Information about each format field */
19602  char fmttype;            /* The format field code letter */
19603  etByte base;             /* The base for radix conversion */
19604  etByte flags;            /* One or more of FLAG_ constants below */
19605  etByte type;             /* Conversion paradigm */
19606  etByte charset;          /* Offset into aDigits[] of the digits string */
19607  etByte prefix;           /* Offset into aPrefix[] of the prefix string */
19608} et_info;
19609
19610/*
19611** Allowed values for et_info.flags
19612*/
19613#define FLAG_SIGNED  1     /* True if the value to convert is signed */
19614#define FLAG_INTERN  2     /* True if for internal use only */
19615#define FLAG_STRING  4     /* Allow infinity precision */
19616
19617
19618/*
19619** The following table is searched linearly, so it is good to put the
19620** most frequently used conversion types first.
19621*/
19622static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
19623static const char aPrefix[] = "-x0\000X0";
19624static const et_info fmtinfo[] = {
19625  {  'd', 10, 1, etRADIX,      0,  0 },
19626  {  's',  0, 4, etSTRING,     0,  0 },
19627  {  'g',  0, 1, etGENERIC,    30, 0 },
19628  {  'z',  0, 4, etDYNSTRING,  0,  0 },
19629  {  'q',  0, 4, etSQLESCAPE,  0,  0 },
19630  {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
19631  {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
19632  {  'c',  0, 0, etCHARX,      0,  0 },
19633  {  'o',  8, 0, etRADIX,      0,  2 },
19634  {  'u', 10, 0, etRADIX,      0,  0 },
19635  {  'x', 16, 0, etRADIX,      16, 1 },
19636  {  'X', 16, 0, etRADIX,      0,  4 },
19637#ifndef SQLITE_OMIT_FLOATING_POINT
19638  {  'f',  0, 1, etFLOAT,      0,  0 },
19639  {  'e',  0, 1, etEXP,        30, 0 },
19640  {  'E',  0, 1, etEXP,        14, 0 },
19641  {  'G',  0, 1, etGENERIC,    14, 0 },
19642#endif
19643  {  'i', 10, 1, etRADIX,      0,  0 },
19644  {  'n',  0, 0, etSIZE,       0,  0 },
19645  {  '%',  0, 0, etPERCENT,    0,  0 },
19646  {  'p', 16, 0, etPOINTER,    0,  1 },
19647
19648/* All the rest have the FLAG_INTERN bit set and are thus for internal
19649** use only */
19650  {  'T',  0, 2, etTOKEN,      0,  0 },
19651  {  'S',  0, 2, etSRCLIST,    0,  0 },
19652  {  'r', 10, 3, etORDINAL,    0,  0 },
19653};
19654
19655/*
19656** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
19657** conversions will work.
19658*/
19659#ifndef SQLITE_OMIT_FLOATING_POINT
19660/*
19661** "*val" is a double such that 0.1 <= *val < 10.0
19662** Return the ascii code for the leading digit of *val, then
19663** multiply "*val" by 10.0 to renormalize.
19664**
19665** Example:
19666**     input:     *val = 3.14159
19667**     output:    *val = 1.4159    function return = '3'
19668**
19669** The counter *cnt is incremented each time.  After counter exceeds
19670** 16 (the number of significant digits in a 64-bit float) '0' is
19671** always returned.
19672*/
19673static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
19674  int digit;
19675  LONGDOUBLE_TYPE d;
19676  if( (*cnt)<=0 ) return '0';
19677  (*cnt)--;
19678  digit = (int)*val;
19679  d = digit;
19680  digit += '0';
19681  *val = (*val - d)*10.0;
19682  return (char)digit;
19683}
19684#endif /* SQLITE_OMIT_FLOATING_POINT */
19685
19686/*
19687** Append N space characters to the given string buffer.
19688*/
19689SQLITE_PRIVATE void sqlite3AppendSpace(StrAccum *pAccum, int N){
19690  static const char zSpaces[] = "                             ";
19691  while( N>=(int)sizeof(zSpaces)-1 ){
19692    sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
19693    N -= sizeof(zSpaces)-1;
19694  }
19695  if( N>0 ){
19696    sqlite3StrAccumAppend(pAccum, zSpaces, N);
19697  }
19698}
19699
19700/*
19701** On machines with a small stack size, you can redefine the
19702** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
19703*/
19704#ifndef SQLITE_PRINT_BUF_SIZE
19705# define SQLITE_PRINT_BUF_SIZE 70
19706#endif
19707#define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
19708
19709/*
19710** Render a string given by "fmt" into the StrAccum object.
19711*/
19712SQLITE_PRIVATE void sqlite3VXPrintf(
19713  StrAccum *pAccum,                  /* Accumulate results here */
19714  int useExtended,                   /* Allow extended %-conversions */
19715  const char *fmt,                   /* Format string */
19716  va_list ap                         /* arguments */
19717){
19718  int c;                     /* Next character in the format string */
19719  char *bufpt;               /* Pointer to the conversion buffer */
19720  int precision;             /* Precision of the current field */
19721  int length;                /* Length of the field */
19722  int idx;                   /* A general purpose loop counter */
19723  int width;                 /* Width of the current field */
19724  etByte flag_leftjustify;   /* True if "-" flag is present */
19725  etByte flag_plussign;      /* True if "+" flag is present */
19726  etByte flag_blanksign;     /* True if " " flag is present */
19727  etByte flag_alternateform; /* True if "#" flag is present */
19728  etByte flag_altform2;      /* True if "!" flag is present */
19729  etByte flag_zeropad;       /* True if field width constant starts with zero */
19730  etByte flag_long;          /* True if "l" flag is present */
19731  etByte flag_longlong;      /* True if the "ll" flag is present */
19732  etByte done;               /* Loop termination flag */
19733  etByte xtype = 0;          /* Conversion paradigm */
19734  char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
19735  sqlite_uint64 longvalue;   /* Value for integer types */
19736  LONGDOUBLE_TYPE realvalue; /* Value for real types */
19737  const et_info *infop;      /* Pointer to the appropriate info structure */
19738  char *zOut;                /* Rendering buffer */
19739  int nOut;                  /* Size of the rendering buffer */
19740  char *zExtra;              /* Malloced memory used by some conversion */
19741#ifndef SQLITE_OMIT_FLOATING_POINT
19742  int  exp, e2;              /* exponent of real numbers */
19743  int nsd;                   /* Number of significant digits returned */
19744  double rounder;            /* Used for rounding floating point values */
19745  etByte flag_dp;            /* True if decimal point should be shown */
19746  etByte flag_rtz;           /* True if trailing zeros should be removed */
19747#endif
19748  char buf[etBUFSIZE];       /* Conversion buffer */
19749
19750  bufpt = 0;
19751  for(; (c=(*fmt))!=0; ++fmt){
19752    if( c!='%' ){
19753      int amt;
19754      bufpt = (char *)fmt;
19755      amt = 1;
19756      while( (c=(*++fmt))!='%' && c!=0 ) amt++;
19757      sqlite3StrAccumAppend(pAccum, bufpt, amt);
19758      if( c==0 ) break;
19759    }
19760    if( (c=(*++fmt))==0 ){
19761      sqlite3StrAccumAppend(pAccum, "%", 1);
19762      break;
19763    }
19764    /* Find out what flags are present */
19765    flag_leftjustify = flag_plussign = flag_blanksign =
19766     flag_alternateform = flag_altform2 = flag_zeropad = 0;
19767    done = 0;
19768    do{
19769      switch( c ){
19770        case '-':   flag_leftjustify = 1;     break;
19771        case '+':   flag_plussign = 1;        break;
19772        case ' ':   flag_blanksign = 1;       break;
19773        case '#':   flag_alternateform = 1;   break;
19774        case '!':   flag_altform2 = 1;        break;
19775        case '0':   flag_zeropad = 1;         break;
19776        default:    done = 1;                 break;
19777      }
19778    }while( !done && (c=(*++fmt))!=0 );
19779    /* Get the field width */
19780    width = 0;
19781    if( c=='*' ){
19782      width = va_arg(ap,int);
19783      if( width<0 ){
19784        flag_leftjustify = 1;
19785        width = -width;
19786      }
19787      c = *++fmt;
19788    }else{
19789      while( c>='0' && c<='9' ){
19790        width = width*10 + c - '0';
19791        c = *++fmt;
19792      }
19793    }
19794    /* Get the precision */
19795    if( c=='.' ){
19796      precision = 0;
19797      c = *++fmt;
19798      if( c=='*' ){
19799        precision = va_arg(ap,int);
19800        if( precision<0 ) precision = -precision;
19801        c = *++fmt;
19802      }else{
19803        while( c>='0' && c<='9' ){
19804          precision = precision*10 + c - '0';
19805          c = *++fmt;
19806        }
19807      }
19808    }else{
19809      precision = -1;
19810    }
19811    /* Get the conversion type modifier */
19812    if( c=='l' ){
19813      flag_long = 1;
19814      c = *++fmt;
19815      if( c=='l' ){
19816        flag_longlong = 1;
19817        c = *++fmt;
19818      }else{
19819        flag_longlong = 0;
19820      }
19821    }else{
19822      flag_long = flag_longlong = 0;
19823    }
19824    /* Fetch the info entry for the field */
19825    infop = &fmtinfo[0];
19826    xtype = etINVALID;
19827    for(idx=0; idx<ArraySize(fmtinfo); idx++){
19828      if( c==fmtinfo[idx].fmttype ){
19829        infop = &fmtinfo[idx];
19830        if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
19831          xtype = infop->type;
19832        }else{
19833          return;
19834        }
19835        break;
19836      }
19837    }
19838    zExtra = 0;
19839
19840    /*
19841    ** At this point, variables are initialized as follows:
19842    **
19843    **   flag_alternateform          TRUE if a '#' is present.
19844    **   flag_altform2               TRUE if a '!' is present.
19845    **   flag_plussign               TRUE if a '+' is present.
19846    **   flag_leftjustify            TRUE if a '-' is present or if the
19847    **                               field width was negative.
19848    **   flag_zeropad                TRUE if the width began with 0.
19849    **   flag_long                   TRUE if the letter 'l' (ell) prefixed
19850    **                               the conversion character.
19851    **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
19852    **                               the conversion character.
19853    **   flag_blanksign              TRUE if a ' ' is present.
19854    **   width                       The specified field width.  This is
19855    **                               always non-negative.  Zero is the default.
19856    **   precision                   The specified precision.  The default
19857    **                               is -1.
19858    **   xtype                       The class of the conversion.
19859    **   infop                       Pointer to the appropriate info struct.
19860    */
19861    switch( xtype ){
19862      case etPOINTER:
19863        flag_longlong = sizeof(char*)==sizeof(i64);
19864        flag_long = sizeof(char*)==sizeof(long int);
19865        /* Fall through into the next case */
19866      case etORDINAL:
19867      case etRADIX:
19868        if( infop->flags & FLAG_SIGNED ){
19869          i64 v;
19870          if( flag_longlong ){
19871            v = va_arg(ap,i64);
19872          }else if( flag_long ){
19873            v = va_arg(ap,long int);
19874          }else{
19875            v = va_arg(ap,int);
19876          }
19877          if( v<0 ){
19878            if( v==SMALLEST_INT64 ){
19879              longvalue = ((u64)1)<<63;
19880            }else{
19881              longvalue = -v;
19882            }
19883            prefix = '-';
19884          }else{
19885            longvalue = v;
19886            if( flag_plussign )        prefix = '+';
19887            else if( flag_blanksign )  prefix = ' ';
19888            else                       prefix = 0;
19889          }
19890        }else{
19891          if( flag_longlong ){
19892            longvalue = va_arg(ap,u64);
19893          }else if( flag_long ){
19894            longvalue = va_arg(ap,unsigned long int);
19895          }else{
19896            longvalue = va_arg(ap,unsigned int);
19897          }
19898          prefix = 0;
19899        }
19900        if( longvalue==0 ) flag_alternateform = 0;
19901        if( flag_zeropad && precision<width-(prefix!=0) ){
19902          precision = width-(prefix!=0);
19903        }
19904        if( precision<etBUFSIZE-10 ){
19905          nOut = etBUFSIZE;
19906          zOut = buf;
19907        }else{
19908          nOut = precision + 10;
19909          zOut = zExtra = sqlite3Malloc( nOut );
19910          if( zOut==0 ){
19911            pAccum->mallocFailed = 1;
19912            return;
19913          }
19914        }
19915        bufpt = &zOut[nOut-1];
19916        if( xtype==etORDINAL ){
19917          static const char zOrd[] = "thstndrd";
19918          int x = (int)(longvalue % 10);
19919          if( x>=4 || (longvalue/10)%10==1 ){
19920            x = 0;
19921          }
19922          *(--bufpt) = zOrd[x*2+1];
19923          *(--bufpt) = zOrd[x*2];
19924        }
19925        {
19926          register const char *cset;      /* Use registers for speed */
19927          register int base;
19928          cset = &aDigits[infop->charset];
19929          base = infop->base;
19930          do{                                           /* Convert to ascii */
19931            *(--bufpt) = cset[longvalue%base];
19932            longvalue = longvalue/base;
19933          }while( longvalue>0 );
19934        }
19935        length = (int)(&zOut[nOut-1]-bufpt);
19936        for(idx=precision-length; idx>0; idx--){
19937          *(--bufpt) = '0';                             /* Zero pad */
19938        }
19939        if( prefix ) *(--bufpt) = prefix;               /* Add sign */
19940        if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
19941          const char *pre;
19942          char x;
19943          pre = &aPrefix[infop->prefix];
19944          for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
19945        }
19946        length = (int)(&zOut[nOut-1]-bufpt);
19947        break;
19948      case etFLOAT:
19949      case etEXP:
19950      case etGENERIC:
19951        realvalue = va_arg(ap,double);
19952#ifdef SQLITE_OMIT_FLOATING_POINT
19953        length = 0;
19954#else
19955        if( precision<0 ) precision = 6;         /* Set default precision */
19956        if( realvalue<0.0 ){
19957          realvalue = -realvalue;
19958          prefix = '-';
19959        }else{
19960          if( flag_plussign )          prefix = '+';
19961          else if( flag_blanksign )    prefix = ' ';
19962          else                         prefix = 0;
19963        }
19964        if( xtype==etGENERIC && precision>0 ) precision--;
19965#if 0
19966        /* Rounding works like BSD when the constant 0.4999 is used.  Wierd! */
19967        for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
19968#else
19969        /* It makes more sense to use 0.5 */
19970        for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
19971#endif
19972        if( xtype==etFLOAT ) realvalue += rounder;
19973        /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
19974        exp = 0;
19975        if( sqlite3IsNaN((double)realvalue) ){
19976          bufpt = "NaN";
19977          length = 3;
19978          break;
19979        }
19980        if( realvalue>0.0 ){
19981          LONGDOUBLE_TYPE scale = 1.0;
19982          while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
19983          while( realvalue>=1e64*scale && exp<=350 ){ scale *= 1e64; exp+=64; }
19984          while( realvalue>=1e8*scale && exp<=350 ){ scale *= 1e8; exp+=8; }
19985          while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
19986          realvalue /= scale;
19987          while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
19988          while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
19989          if( exp>350 ){
19990            if( prefix=='-' ){
19991              bufpt = "-Inf";
19992            }else if( prefix=='+' ){
19993              bufpt = "+Inf";
19994            }else{
19995              bufpt = "Inf";
19996            }
19997            length = sqlite3Strlen30(bufpt);
19998            break;
19999          }
20000        }
20001        bufpt = buf;
20002        /*
20003        ** If the field type is etGENERIC, then convert to either etEXP
20004        ** or etFLOAT, as appropriate.
20005        */
20006        if( xtype!=etFLOAT ){
20007          realvalue += rounder;
20008          if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
20009        }
20010        if( xtype==etGENERIC ){
20011          flag_rtz = !flag_alternateform;
20012          if( exp<-4 || exp>precision ){
20013            xtype = etEXP;
20014          }else{
20015            precision = precision - exp;
20016            xtype = etFLOAT;
20017          }
20018        }else{
20019          flag_rtz = flag_altform2;
20020        }
20021        if( xtype==etEXP ){
20022          e2 = 0;
20023        }else{
20024          e2 = exp;
20025        }
20026        if( e2+precision+width > etBUFSIZE - 15 ){
20027          bufpt = zExtra = sqlite3Malloc( e2+precision+width+15 );
20028          if( bufpt==0 ){
20029            pAccum->mallocFailed = 1;
20030            return;
20031          }
20032        }
20033        zOut = bufpt;
20034        nsd = 16 + flag_altform2*10;
20035        flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
20036        /* The sign in front of the number */
20037        if( prefix ){
20038          *(bufpt++) = prefix;
20039        }
20040        /* Digits prior to the decimal point */
20041        if( e2<0 ){
20042          *(bufpt++) = '0';
20043        }else{
20044          for(; e2>=0; e2--){
20045            *(bufpt++) = et_getdigit(&realvalue,&nsd);
20046          }
20047        }
20048        /* The decimal point */
20049        if( flag_dp ){
20050          *(bufpt++) = '.';
20051        }
20052        /* "0" digits after the decimal point but before the first
20053        ** significant digit of the number */
20054        for(e2++; e2<0; precision--, e2++){
20055          assert( precision>0 );
20056          *(bufpt++) = '0';
20057        }
20058        /* Significant digits after the decimal point */
20059        while( (precision--)>0 ){
20060          *(bufpt++) = et_getdigit(&realvalue,&nsd);
20061        }
20062        /* Remove trailing zeros and the "." if no digits follow the "." */
20063        if( flag_rtz && flag_dp ){
20064          while( bufpt[-1]=='0' ) *(--bufpt) = 0;
20065          assert( bufpt>zOut );
20066          if( bufpt[-1]=='.' ){
20067            if( flag_altform2 ){
20068              *(bufpt++) = '0';
20069            }else{
20070              *(--bufpt) = 0;
20071            }
20072          }
20073        }
20074        /* Add the "eNNN" suffix */
20075        if( xtype==etEXP ){
20076          *(bufpt++) = aDigits[infop->charset];
20077          if( exp<0 ){
20078            *(bufpt++) = '-'; exp = -exp;
20079          }else{
20080            *(bufpt++) = '+';
20081          }
20082          if( exp>=100 ){
20083            *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
20084            exp %= 100;
20085          }
20086          *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
20087          *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
20088        }
20089        *bufpt = 0;
20090
20091        /* The converted number is in buf[] and zero terminated. Output it.
20092        ** Note that the number is in the usual order, not reversed as with
20093        ** integer conversions. */
20094        length = (int)(bufpt-zOut);
20095        bufpt = zOut;
20096
20097        /* Special case:  Add leading zeros if the flag_zeropad flag is
20098        ** set and we are not left justified */
20099        if( flag_zeropad && !flag_leftjustify && length < width){
20100          int i;
20101          int nPad = width - length;
20102          for(i=width; i>=nPad; i--){
20103            bufpt[i] = bufpt[i-nPad];
20104          }
20105          i = prefix!=0;
20106          while( nPad-- ) bufpt[i++] = '0';
20107          length = width;
20108        }
20109#endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
20110        break;
20111      case etSIZE:
20112        *(va_arg(ap,int*)) = pAccum->nChar;
20113        length = width = 0;
20114        break;
20115      case etPERCENT:
20116        buf[0] = '%';
20117        bufpt = buf;
20118        length = 1;
20119        break;
20120      case etCHARX:
20121        c = va_arg(ap,int);
20122        buf[0] = (char)c;
20123        if( precision>=0 ){
20124          for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
20125          length = precision;
20126        }else{
20127          length =1;
20128        }
20129        bufpt = buf;
20130        break;
20131      case etSTRING:
20132      case etDYNSTRING:
20133        bufpt = va_arg(ap,char*);
20134        if( bufpt==0 ){
20135          bufpt = "";
20136        }else if( xtype==etDYNSTRING ){
20137          zExtra = bufpt;
20138        }
20139        if( precision>=0 ){
20140          for(length=0; length<precision && bufpt[length]; length++){}
20141        }else{
20142          length = sqlite3Strlen30(bufpt);
20143        }
20144        break;
20145      case etSQLESCAPE:
20146      case etSQLESCAPE2:
20147      case etSQLESCAPE3: {
20148        int i, j, k, n, isnull;
20149        int needQuote;
20150        char ch;
20151        char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
20152        char *escarg = va_arg(ap,char*);
20153        isnull = escarg==0;
20154        if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
20155        k = precision;
20156        for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
20157          if( ch==q )  n++;
20158        }
20159        needQuote = !isnull && xtype==etSQLESCAPE2;
20160        n += i + 1 + needQuote*2;
20161        if( n>etBUFSIZE ){
20162          bufpt = zExtra = sqlite3Malloc( n );
20163          if( bufpt==0 ){
20164            pAccum->mallocFailed = 1;
20165            return;
20166          }
20167        }else{
20168          bufpt = buf;
20169        }
20170        j = 0;
20171        if( needQuote ) bufpt[j++] = q;
20172        k = i;
20173        for(i=0; i<k; i++){
20174          bufpt[j++] = ch = escarg[i];
20175          if( ch==q ) bufpt[j++] = ch;
20176        }
20177        if( needQuote ) bufpt[j++] = q;
20178        bufpt[j] = 0;
20179        length = j;
20180        /* The precision in %q and %Q means how many input characters to
20181        ** consume, not the length of the output...
20182        ** if( precision>=0 && precision<length ) length = precision; */
20183        break;
20184      }
20185      case etTOKEN: {
20186        Token *pToken = va_arg(ap, Token*);
20187        if( pToken ){
20188          sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
20189        }
20190        length = width = 0;
20191        break;
20192      }
20193      case etSRCLIST: {
20194        SrcList *pSrc = va_arg(ap, SrcList*);
20195        int k = va_arg(ap, int);
20196        struct SrcList_item *pItem = &pSrc->a[k];
20197        assert( k>=0 && k<pSrc->nSrc );
20198        if( pItem->zDatabase ){
20199          sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
20200          sqlite3StrAccumAppend(pAccum, ".", 1);
20201        }
20202        sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
20203        length = width = 0;
20204        break;
20205      }
20206      default: {
20207        assert( xtype==etINVALID );
20208        return;
20209      }
20210    }/* End switch over the format type */
20211    /*
20212    ** The text of the conversion is pointed to by "bufpt" and is
20213    ** "length" characters long.  The field width is "width".  Do
20214    ** the output.
20215    */
20216    if( !flag_leftjustify ){
20217      register int nspace;
20218      nspace = width-length;
20219      if( nspace>0 ){
20220        sqlite3AppendSpace(pAccum, nspace);
20221      }
20222    }
20223    if( length>0 ){
20224      sqlite3StrAccumAppend(pAccum, bufpt, length);
20225    }
20226    if( flag_leftjustify ){
20227      register int nspace;
20228      nspace = width-length;
20229      if( nspace>0 ){
20230        sqlite3AppendSpace(pAccum, nspace);
20231      }
20232    }
20233    sqlite3_free(zExtra);
20234  }/* End for loop over the format string */
20235} /* End of function */
20236
20237/*
20238** Append N bytes of text from z to the StrAccum object.
20239*/
20240SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
20241  assert( z!=0 || N==0 );
20242  if( p->tooBig | p->mallocFailed ){
20243    testcase(p->tooBig);
20244    testcase(p->mallocFailed);
20245    return;
20246  }
20247  assert( p->zText!=0 || p->nChar==0 );
20248  if( N<0 ){
20249    N = sqlite3Strlen30(z);
20250  }
20251  if( N==0 || NEVER(z==0) ){
20252    return;
20253  }
20254  if( p->nChar+N >= p->nAlloc ){
20255    char *zNew;
20256    if( !p->useMalloc ){
20257      p->tooBig = 1;
20258      N = p->nAlloc - p->nChar - 1;
20259      if( N<=0 ){
20260        return;
20261      }
20262    }else{
20263      char *zOld = (p->zText==p->zBase ? 0 : p->zText);
20264      i64 szNew = p->nChar;
20265      szNew += N + 1;
20266      if( szNew > p->mxAlloc ){
20267        sqlite3StrAccumReset(p);
20268        p->tooBig = 1;
20269        return;
20270      }else{
20271        p->nAlloc = (int)szNew;
20272      }
20273      if( p->useMalloc==1 ){
20274        zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
20275      }else{
20276        zNew = sqlite3_realloc(zOld, p->nAlloc);
20277      }
20278      if( zNew ){
20279        if( zOld==0 && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
20280        p->zText = zNew;
20281      }else{
20282        p->mallocFailed = 1;
20283        sqlite3StrAccumReset(p);
20284        return;
20285      }
20286    }
20287  }
20288  assert( p->zText );
20289  memcpy(&p->zText[p->nChar], z, N);
20290  p->nChar += N;
20291}
20292
20293/*
20294** Finish off a string by making sure it is zero-terminated.
20295** Return a pointer to the resulting string.  Return a NULL
20296** pointer if any kind of error was encountered.
20297*/
20298SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
20299  if( p->zText ){
20300    p->zText[p->nChar] = 0;
20301    if( p->useMalloc && p->zText==p->zBase ){
20302      if( p->useMalloc==1 ){
20303        p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
20304      }else{
20305        p->zText = sqlite3_malloc(p->nChar+1);
20306      }
20307      if( p->zText ){
20308        memcpy(p->zText, p->zBase, p->nChar+1);
20309      }else{
20310        p->mallocFailed = 1;
20311      }
20312    }
20313  }
20314  return p->zText;
20315}
20316
20317/*
20318** Reset an StrAccum string.  Reclaim all malloced memory.
20319*/
20320SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
20321  if( p->zText!=p->zBase ){
20322    if( p->useMalloc==1 ){
20323      sqlite3DbFree(p->db, p->zText);
20324    }else{
20325      sqlite3_free(p->zText);
20326    }
20327  }
20328  p->zText = 0;
20329}
20330
20331/*
20332** Initialize a string accumulator
20333*/
20334SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
20335  p->zText = p->zBase = zBase;
20336  p->db = 0;
20337  p->nChar = 0;
20338  p->nAlloc = n;
20339  p->mxAlloc = mx;
20340  p->useMalloc = 1;
20341  p->tooBig = 0;
20342  p->mallocFailed = 0;
20343}
20344
20345/*
20346** Print into memory obtained from sqliteMalloc().  Use the internal
20347** %-conversion extensions.
20348*/
20349SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
20350  char *z;
20351  char zBase[SQLITE_PRINT_BUF_SIZE];
20352  StrAccum acc;
20353  assert( db!=0 );
20354  sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
20355                      db->aLimit[SQLITE_LIMIT_LENGTH]);
20356  acc.db = db;
20357  sqlite3VXPrintf(&acc, 1, zFormat, ap);
20358  z = sqlite3StrAccumFinish(&acc);
20359  if( acc.mallocFailed ){
20360    db->mallocFailed = 1;
20361  }
20362  return z;
20363}
20364
20365/*
20366** Print into memory obtained from sqliteMalloc().  Use the internal
20367** %-conversion extensions.
20368*/
20369SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
20370  va_list ap;
20371  char *z;
20372  va_start(ap, zFormat);
20373  z = sqlite3VMPrintf(db, zFormat, ap);
20374  va_end(ap);
20375  return z;
20376}
20377
20378/*
20379** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
20380** the string and before returnning.  This routine is intended to be used
20381** to modify an existing string.  For example:
20382**
20383**       x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
20384**
20385*/
20386SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
20387  va_list ap;
20388  char *z;
20389  va_start(ap, zFormat);
20390  z = sqlite3VMPrintf(db, zFormat, ap);
20391  va_end(ap);
20392  sqlite3DbFree(db, zStr);
20393  return z;
20394}
20395
20396/*
20397** Print into memory obtained from sqlite3_malloc().  Omit the internal
20398** %-conversion extensions.
20399*/
20400SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
20401  char *z;
20402  char zBase[SQLITE_PRINT_BUF_SIZE];
20403  StrAccum acc;
20404#ifndef SQLITE_OMIT_AUTOINIT
20405  if( sqlite3_initialize() ) return 0;
20406#endif
20407  sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
20408  acc.useMalloc = 2;
20409  sqlite3VXPrintf(&acc, 0, zFormat, ap);
20410  z = sqlite3StrAccumFinish(&acc);
20411  return z;
20412}
20413
20414/*
20415** Print into memory obtained from sqlite3_malloc()().  Omit the internal
20416** %-conversion extensions.
20417*/
20418SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
20419  va_list ap;
20420  char *z;
20421#ifndef SQLITE_OMIT_AUTOINIT
20422  if( sqlite3_initialize() ) return 0;
20423#endif
20424  va_start(ap, zFormat);
20425  z = sqlite3_vmprintf(zFormat, ap);
20426  va_end(ap);
20427  return z;
20428}
20429
20430/*
20431** sqlite3_snprintf() works like snprintf() except that it ignores the
20432** current locale settings.  This is important for SQLite because we
20433** are not able to use a "," as the decimal point in place of "." as
20434** specified by some locales.
20435**
20436** Oops:  The first two arguments of sqlite3_snprintf() are backwards
20437** from the snprintf() standard.  Unfortunately, it is too late to change
20438** this without breaking compatibility, so we just have to live with the
20439** mistake.
20440**
20441** sqlite3_vsnprintf() is the varargs version.
20442*/
20443SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
20444  StrAccum acc;
20445  if( n<=0 ) return zBuf;
20446  sqlite3StrAccumInit(&acc, zBuf, n, 0);
20447  acc.useMalloc = 0;
20448  sqlite3VXPrintf(&acc, 0, zFormat, ap);
20449  return sqlite3StrAccumFinish(&acc);
20450}
20451SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
20452  char *z;
20453  va_list ap;
20454  va_start(ap,zFormat);
20455  z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
20456  va_end(ap);
20457  return z;
20458}
20459
20460/*
20461** This is the routine that actually formats the sqlite3_log() message.
20462** We house it in a separate routine from sqlite3_log() to avoid using
20463** stack space on small-stack systems when logging is disabled.
20464**
20465** sqlite3_log() must render into a static buffer.  It cannot dynamically
20466** allocate memory because it might be called while the memory allocator
20467** mutex is held.
20468*/
20469static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
20470  StrAccum acc;                          /* String accumulator */
20471  char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */
20472
20473  sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
20474  acc.useMalloc = 0;
20475  sqlite3VXPrintf(&acc, 0, zFormat, ap);
20476  sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
20477                           sqlite3StrAccumFinish(&acc));
20478}
20479
20480/*
20481** Format and write a message to the log if logging is enabled.
20482*/
20483SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
20484  va_list ap;                             /* Vararg list */
20485  if( sqlite3GlobalConfig.xLog ){
20486    va_start(ap, zFormat);
20487    renderLogMsg(iErrCode, zFormat, ap);
20488    va_end(ap);
20489  }
20490}
20491
20492#if defined(SQLITE_DEBUG)
20493/*
20494** A version of printf() that understands %lld.  Used for debugging.
20495** The printf() built into some versions of windows does not understand %lld
20496** and segfaults if you give it a long long int.
20497*/
20498SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
20499  va_list ap;
20500  StrAccum acc;
20501  char zBuf[500];
20502  sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
20503  acc.useMalloc = 0;
20504  va_start(ap,zFormat);
20505  sqlite3VXPrintf(&acc, 0, zFormat, ap);
20506  va_end(ap);
20507  sqlite3StrAccumFinish(&acc);
20508  fprintf(stdout,"%s", zBuf);
20509  fflush(stdout);
20510}
20511#endif
20512
20513#ifndef SQLITE_OMIT_TRACE
20514/*
20515** variable-argument wrapper around sqlite3VXPrintf().
20516*/
20517SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
20518  va_list ap;
20519  va_start(ap,zFormat);
20520  sqlite3VXPrintf(p, 1, zFormat, ap);
20521  va_end(ap);
20522}
20523#endif
20524
20525/************** End of printf.c **********************************************/
20526/************** Begin file random.c ******************************************/
20527/*
20528** 2001 September 15
20529**
20530** The author disclaims copyright to this source code.  In place of
20531** a legal notice, here is a blessing:
20532**
20533**    May you do good and not evil.
20534**    May you find forgiveness for yourself and forgive others.
20535**    May you share freely, never taking more than you give.
20536**
20537*************************************************************************
20538** This file contains code to implement a pseudo-random number
20539** generator (PRNG) for SQLite.
20540**
20541** Random numbers are used by some of the database backends in order
20542** to generate random integer keys for tables or random filenames.
20543*/
20544
20545
20546/* All threads share a single random number generator.
20547** This structure is the current state of the generator.
20548*/
20549static SQLITE_WSD struct sqlite3PrngType {
20550  unsigned char isInit;          /* True if initialized */
20551  unsigned char i, j;            /* State variables */
20552  unsigned char s[256];          /* State variables */
20553} sqlite3Prng;
20554
20555/*
20556** Get a single 8-bit random value from the RC4 PRNG.  The Mutex
20557** must be held while executing this routine.
20558**
20559** Why not just use a library random generator like lrand48() for this?
20560** Because the OP_NewRowid opcode in the VDBE depends on having a very
20561** good source of random numbers.  The lrand48() library function may
20562** well be good enough.  But maybe not.  Or maybe lrand48() has some
20563** subtle problems on some systems that could cause problems.  It is hard
20564** to know.  To minimize the risk of problems due to bad lrand48()
20565** implementations, SQLite uses this random number generator based
20566** on RC4, which we know works very well.
20567**
20568** (Later):  Actually, OP_NewRowid does not depend on a good source of
20569** randomness any more.  But we will leave this code in all the same.
20570*/
20571static u8 randomByte(void){
20572  unsigned char t;
20573
20574
20575  /* The "wsdPrng" macro will resolve to the pseudo-random number generator
20576  ** state vector.  If writable static data is unsupported on the target,
20577  ** we have to locate the state vector at run-time.  In the more common
20578  ** case where writable static data is supported, wsdPrng can refer directly
20579  ** to the "sqlite3Prng" state vector declared above.
20580  */
20581#ifdef SQLITE_OMIT_WSD
20582  struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
20583# define wsdPrng p[0]
20584#else
20585# define wsdPrng sqlite3Prng
20586#endif
20587
20588
20589  /* Initialize the state of the random number generator once,
20590  ** the first time this routine is called.  The seed value does
20591  ** not need to contain a lot of randomness since we are not
20592  ** trying to do secure encryption or anything like that...
20593  **
20594  ** Nothing in this file or anywhere else in SQLite does any kind of
20595  ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
20596  ** number generator) not as an encryption device.
20597  */
20598  if( !wsdPrng.isInit ){
20599    int i;
20600    char k[256];
20601    wsdPrng.j = 0;
20602    wsdPrng.i = 0;
20603    sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
20604    for(i=0; i<256; i++){
20605      wsdPrng.s[i] = (u8)i;
20606    }
20607    for(i=0; i<256; i++){
20608      wsdPrng.j += wsdPrng.s[i] + k[i];
20609      t = wsdPrng.s[wsdPrng.j];
20610      wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
20611      wsdPrng.s[i] = t;
20612    }
20613    wsdPrng.isInit = 1;
20614  }
20615
20616  /* Generate and return single random byte
20617  */
20618  wsdPrng.i++;
20619  t = wsdPrng.s[wsdPrng.i];
20620  wsdPrng.j += t;
20621  wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
20622  wsdPrng.s[wsdPrng.j] = t;
20623  t += wsdPrng.s[wsdPrng.i];
20624  return wsdPrng.s[t];
20625}
20626
20627/*
20628** Return N random bytes.
20629*/
20630SQLITE_API void sqlite3_randomness(int N, void *pBuf){
20631  unsigned char *zBuf = pBuf;
20632#if SQLITE_THREADSAFE
20633  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
20634#endif
20635  sqlite3_mutex_enter(mutex);
20636  while( N-- ){
20637    *(zBuf++) = randomByte();
20638  }
20639  sqlite3_mutex_leave(mutex);
20640}
20641
20642#ifndef SQLITE_OMIT_BUILTIN_TEST
20643/*
20644** For testing purposes, we sometimes want to preserve the state of
20645** PRNG and restore the PRNG to its saved state at a later time, or
20646** to reset the PRNG to its initial state.  These routines accomplish
20647** those tasks.
20648**
20649** The sqlite3_test_control() interface calls these routines to
20650** control the PRNG.
20651*/
20652static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
20653SQLITE_PRIVATE void sqlite3PrngSaveState(void){
20654  memcpy(
20655    &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
20656    &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
20657    sizeof(sqlite3Prng)
20658  );
20659}
20660SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
20661  memcpy(
20662    &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
20663    &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
20664    sizeof(sqlite3Prng)
20665  );
20666}
20667SQLITE_PRIVATE void sqlite3PrngResetState(void){
20668  GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
20669}
20670#endif /* SQLITE_OMIT_BUILTIN_TEST */
20671
20672/************** End of random.c **********************************************/
20673/************** Begin file utf.c *********************************************/
20674/*
20675** 2004 April 13
20676**
20677** The author disclaims copyright to this source code.  In place of
20678** a legal notice, here is a blessing:
20679**
20680**    May you do good and not evil.
20681**    May you find forgiveness for yourself and forgive others.
20682**    May you share freely, never taking more than you give.
20683**
20684*************************************************************************
20685** This file contains routines used to translate between UTF-8,
20686** UTF-16, UTF-16BE, and UTF-16LE.
20687**
20688** Notes on UTF-8:
20689**
20690**   Byte-0    Byte-1    Byte-2    Byte-3    Value
20691**  0xxxxxxx                                 00000000 00000000 0xxxxxxx
20692**  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
20693**  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
20694**  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
20695**
20696**
20697** Notes on UTF-16:  (with wwww+1==uuuuu)
20698**
20699**      Word-0               Word-1          Value
20700**  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
20701**  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
20702**
20703**
20704** BOM or Byte Order Mark:
20705**     0xff 0xfe   little-endian utf-16 follows
20706**     0xfe 0xff   big-endian utf-16 follows
20707**
20708*/
20709/* #include <assert.h> */
20710
20711#ifndef SQLITE_AMALGAMATION
20712/*
20713** The following constant value is used by the SQLITE_BIGENDIAN and
20714** SQLITE_LITTLEENDIAN macros.
20715*/
20716SQLITE_PRIVATE const int sqlite3one = 1;
20717#endif /* SQLITE_AMALGAMATION */
20718
20719/*
20720** This lookup table is used to help decode the first byte of
20721** a multi-byte UTF8 character.
20722*/
20723static const unsigned char sqlite3Utf8Trans1[] = {
20724  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
20725  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
20726  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
20727  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
20728  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
20729  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
20730  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
20731  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
20732};
20733
20734
20735#define WRITE_UTF8(zOut, c) {                          \
20736  if( c<0x00080 ){                                     \
20737    *zOut++ = (u8)(c&0xFF);                            \
20738  }                                                    \
20739  else if( c<0x00800 ){                                \
20740    *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
20741    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
20742  }                                                    \
20743  else if( c<0x10000 ){                                \
20744    *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
20745    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
20746    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
20747  }else{                                               \
20748    *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
20749    *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
20750    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
20751    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
20752  }                                                    \
20753}
20754
20755#define WRITE_UTF16LE(zOut, c) {                                    \
20756  if( c<=0xFFFF ){                                                  \
20757    *zOut++ = (u8)(c&0x00FF);                                       \
20758    *zOut++ = (u8)((c>>8)&0x00FF);                                  \
20759  }else{                                                            \
20760    *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
20761    *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
20762    *zOut++ = (u8)(c&0x00FF);                                       \
20763    *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
20764  }                                                                 \
20765}
20766
20767#define WRITE_UTF16BE(zOut, c) {                                    \
20768  if( c<=0xFFFF ){                                                  \
20769    *zOut++ = (u8)((c>>8)&0x00FF);                                  \
20770    *zOut++ = (u8)(c&0x00FF);                                       \
20771  }else{                                                            \
20772    *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
20773    *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
20774    *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
20775    *zOut++ = (u8)(c&0x00FF);                                       \
20776  }                                                                 \
20777}
20778
20779#define READ_UTF16LE(zIn, TERM, c){                                   \
20780  c = (*zIn++);                                                       \
20781  c += ((*zIn++)<<8);                                                 \
20782  if( c>=0xD800 && c<0xE000 && TERM ){                                \
20783    int c2 = (*zIn++);                                                \
20784    c2 += ((*zIn++)<<8);                                              \
20785    c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
20786  }                                                                   \
20787}
20788
20789#define READ_UTF16BE(zIn, TERM, c){                                   \
20790  c = ((*zIn++)<<8);                                                  \
20791  c += (*zIn++);                                                      \
20792  if( c>=0xD800 && c<0xE000 && TERM ){                                \
20793    int c2 = ((*zIn++)<<8);                                           \
20794    c2 += (*zIn++);                                                   \
20795    c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
20796  }                                                                   \
20797}
20798
20799/*
20800** Translate a single UTF-8 character.  Return the unicode value.
20801**
20802** During translation, assume that the byte that zTerm points
20803** is a 0x00.
20804**
20805** Write a pointer to the next unread byte back into *pzNext.
20806**
20807** Notes On Invalid UTF-8:
20808**
20809**  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
20810**     be encoded as a multi-byte character.  Any multi-byte character that
20811**     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
20812**
20813**  *  This routine never allows a UTF16 surrogate value to be encoded.
20814**     If a multi-byte character attempts to encode a value between
20815**     0xd800 and 0xe000 then it is rendered as 0xfffd.
20816**
20817**  *  Bytes in the range of 0x80 through 0xbf which occur as the first
20818**     byte of a character are interpreted as single-byte characters
20819**     and rendered as themselves even though they are technically
20820**     invalid characters.
20821**
20822**  *  This routine accepts an infinite number of different UTF8 encodings
20823**     for unicode values 0x80 and greater.  It do not change over-length
20824**     encodings to 0xfffd as some systems recommend.
20825*/
20826#define READ_UTF8(zIn, zTerm, c)                           \
20827  c = *(zIn++);                                            \
20828  if( c>=0xc0 ){                                           \
20829    c = sqlite3Utf8Trans1[c-0xc0];                         \
20830    while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
20831      c = (c<<6) + (0x3f & *(zIn++));                      \
20832    }                                                      \
20833    if( c<0x80                                             \
20834        || (c&0xFFFFF800)==0xD800                          \
20835        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
20836  }
20837SQLITE_PRIVATE u32 sqlite3Utf8Read(
20838  const unsigned char **pz    /* Pointer to string from which to read char */
20839){
20840  unsigned int c;
20841
20842  /* Same as READ_UTF8() above but without the zTerm parameter.
20843  ** For this routine, we assume the UTF8 string is always zero-terminated.
20844  */
20845  c = *((*pz)++);
20846  if( c>=0xc0 ){
20847    c = sqlite3Utf8Trans1[c-0xc0];
20848    while( (*(*pz) & 0xc0)==0x80 ){
20849      c = (c<<6) + (0x3f & *((*pz)++));
20850    }
20851    if( c<0x80
20852        || (c&0xFFFFF800)==0xD800
20853        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }
20854  }
20855  return c;
20856}
20857
20858
20859
20860
20861/*
20862** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
20863** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
20864*/
20865/* #define TRANSLATE_TRACE 1 */
20866
20867#ifndef SQLITE_OMIT_UTF16
20868/*
20869** This routine transforms the internal text encoding used by pMem to
20870** desiredEnc. It is an error if the string is already of the desired
20871** encoding, or if *pMem does not contain a string value.
20872*/
20873SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
20874  int len;                    /* Maximum length of output string in bytes */
20875  unsigned char *zOut;                  /* Output buffer */
20876  unsigned char *zIn;                   /* Input iterator */
20877  unsigned char *zTerm;                 /* End of input */
20878  unsigned char *z;                     /* Output iterator */
20879  unsigned int c;
20880
20881  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
20882  assert( pMem->flags&MEM_Str );
20883  assert( pMem->enc!=desiredEnc );
20884  assert( pMem->enc!=0 );
20885  assert( pMem->n>=0 );
20886
20887#if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
20888  {
20889    char zBuf[100];
20890    sqlite3VdbeMemPrettyPrint(pMem, zBuf);
20891    fprintf(stderr, "INPUT:  %s\n", zBuf);
20892  }
20893#endif
20894
20895  /* If the translation is between UTF-16 little and big endian, then
20896  ** all that is required is to swap the byte order. This case is handled
20897  ** differently from the others.
20898  */
20899  if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
20900    u8 temp;
20901    int rc;
20902    rc = sqlite3VdbeMemMakeWriteable(pMem);
20903    if( rc!=SQLITE_OK ){
20904      assert( rc==SQLITE_NOMEM );
20905      return SQLITE_NOMEM;
20906    }
20907    zIn = (u8*)pMem->z;
20908    zTerm = &zIn[pMem->n&~1];
20909    while( zIn<zTerm ){
20910      temp = *zIn;
20911      *zIn = *(zIn+1);
20912      zIn++;
20913      *zIn++ = temp;
20914    }
20915    pMem->enc = desiredEnc;
20916    goto translate_out;
20917  }
20918
20919  /* Set len to the maximum number of bytes required in the output buffer. */
20920  if( desiredEnc==SQLITE_UTF8 ){
20921    /* When converting from UTF-16, the maximum growth results from
20922    ** translating a 2-byte character to a 4-byte UTF-8 character.
20923    ** A single byte is required for the output string
20924    ** nul-terminator.
20925    */
20926    pMem->n &= ~1;
20927    len = pMem->n * 2 + 1;
20928  }else{
20929    /* When converting from UTF-8 to UTF-16 the maximum growth is caused
20930    ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
20931    ** character. Two bytes are required in the output buffer for the
20932    ** nul-terminator.
20933    */
20934    len = pMem->n * 2 + 2;
20935  }
20936
20937  /* Set zIn to point at the start of the input buffer and zTerm to point 1
20938  ** byte past the end.
20939  **
20940  ** Variable zOut is set to point at the output buffer, space obtained
20941  ** from sqlite3_malloc().
20942  */
20943  zIn = (u8*)pMem->z;
20944  zTerm = &zIn[pMem->n];
20945  zOut = sqlite3DbMallocRaw(pMem->db, len);
20946  if( !zOut ){
20947    return SQLITE_NOMEM;
20948  }
20949  z = zOut;
20950
20951  if( pMem->enc==SQLITE_UTF8 ){
20952    if( desiredEnc==SQLITE_UTF16LE ){
20953      /* UTF-8 -> UTF-16 Little-endian */
20954      while( zIn<zTerm ){
20955        READ_UTF8(zIn, zTerm, c);
20956        WRITE_UTF16LE(z, c);
20957      }
20958    }else{
20959      assert( desiredEnc==SQLITE_UTF16BE );
20960      /* UTF-8 -> UTF-16 Big-endian */
20961      while( zIn<zTerm ){
20962        READ_UTF8(zIn, zTerm, c);
20963        WRITE_UTF16BE(z, c);
20964      }
20965    }
20966    pMem->n = (int)(z - zOut);
20967    *z++ = 0;
20968  }else{
20969    assert( desiredEnc==SQLITE_UTF8 );
20970    if( pMem->enc==SQLITE_UTF16LE ){
20971      /* UTF-16 Little-endian -> UTF-8 */
20972      while( zIn<zTerm ){
20973        READ_UTF16LE(zIn, zIn<zTerm, c);
20974        WRITE_UTF8(z, c);
20975      }
20976    }else{
20977      /* UTF-16 Big-endian -> UTF-8 */
20978      while( zIn<zTerm ){
20979        READ_UTF16BE(zIn, zIn<zTerm, c);
20980        WRITE_UTF8(z, c);
20981      }
20982    }
20983    pMem->n = (int)(z - zOut);
20984  }
20985  *z = 0;
20986  assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
20987
20988  sqlite3VdbeMemRelease(pMem);
20989  pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
20990  pMem->enc = desiredEnc;
20991  pMem->flags |= (MEM_Term|MEM_Dyn);
20992  pMem->z = (char*)zOut;
20993  pMem->zMalloc = pMem->z;
20994
20995translate_out:
20996#if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
20997  {
20998    char zBuf[100];
20999    sqlite3VdbeMemPrettyPrint(pMem, zBuf);
21000    fprintf(stderr, "OUTPUT: %s\n", zBuf);
21001  }
21002#endif
21003  return SQLITE_OK;
21004}
21005
21006/*
21007** This routine checks for a byte-order mark at the beginning of the
21008** UTF-16 string stored in *pMem. If one is present, it is removed and
21009** the encoding of the Mem adjusted. This routine does not do any
21010** byte-swapping, it just sets Mem.enc appropriately.
21011**
21012** The allocation (static, dynamic etc.) and encoding of the Mem may be
21013** changed by this function.
21014*/
21015SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
21016  int rc = SQLITE_OK;
21017  u8 bom = 0;
21018
21019  assert( pMem->n>=0 );
21020  if( pMem->n>1 ){
21021    u8 b1 = *(u8 *)pMem->z;
21022    u8 b2 = *(((u8 *)pMem->z) + 1);
21023    if( b1==0xFE && b2==0xFF ){
21024      bom = SQLITE_UTF16BE;
21025    }
21026    if( b1==0xFF && b2==0xFE ){
21027      bom = SQLITE_UTF16LE;
21028    }
21029  }
21030
21031  if( bom ){
21032    rc = sqlite3VdbeMemMakeWriteable(pMem);
21033    if( rc==SQLITE_OK ){
21034      pMem->n -= 2;
21035      memmove(pMem->z, &pMem->z[2], pMem->n);
21036      pMem->z[pMem->n] = '\0';
21037      pMem->z[pMem->n+1] = '\0';
21038      pMem->flags |= MEM_Term;
21039      pMem->enc = bom;
21040    }
21041  }
21042  return rc;
21043}
21044#endif /* SQLITE_OMIT_UTF16 */
21045
21046/*
21047** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
21048** return the number of unicode characters in pZ up to (but not including)
21049** the first 0x00 byte. If nByte is not less than zero, return the
21050** number of unicode characters in the first nByte of pZ (or up to
21051** the first 0x00, whichever comes first).
21052*/
21053SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
21054  int r = 0;
21055  const u8 *z = (const u8*)zIn;
21056  const u8 *zTerm;
21057  if( nByte>=0 ){
21058    zTerm = &z[nByte];
21059  }else{
21060    zTerm = (const u8*)(-1);
21061  }
21062  assert( z<=zTerm );
21063  while( *z!=0 && z<zTerm ){
21064    SQLITE_SKIP_UTF8(z);
21065    r++;
21066  }
21067  return r;
21068}
21069
21070/* This test function is not currently used by the automated test-suite.
21071** Hence it is only available in debug builds.
21072*/
21073#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
21074/*
21075** Translate UTF-8 to UTF-8.
21076**
21077** This has the effect of making sure that the string is well-formed
21078** UTF-8.  Miscoded characters are removed.
21079**
21080** The translation is done in-place and aborted if the output
21081** overruns the input.
21082*/
21083SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
21084  unsigned char *zOut = zIn;
21085  unsigned char *zStart = zIn;
21086  u32 c;
21087
21088  while( zIn[0] && zOut<=zIn ){
21089    c = sqlite3Utf8Read((const u8**)&zIn);
21090    if( c!=0xfffd ){
21091      WRITE_UTF8(zOut, c);
21092    }
21093  }
21094  *zOut = 0;
21095  return (int)(zOut - zStart);
21096}
21097#endif
21098
21099#ifndef SQLITE_OMIT_UTF16
21100/*
21101** Convert a UTF-16 string in the native encoding into a UTF-8 string.
21102** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
21103** be freed by the calling function.
21104**
21105** NULL is returned if there is an allocation error.
21106*/
21107SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
21108  Mem m;
21109  memset(&m, 0, sizeof(m));
21110  m.db = db;
21111  sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
21112  sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
21113  if( db->mallocFailed ){
21114    sqlite3VdbeMemRelease(&m);
21115    m.z = 0;
21116  }
21117  assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
21118  assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
21119  assert( (m.flags & MEM_Dyn)!=0 || db->mallocFailed );
21120  assert( m.z || db->mallocFailed );
21121  return m.z;
21122}
21123
21124/*
21125** Convert a UTF-8 string to the UTF-16 encoding specified by parameter
21126** enc. A pointer to the new string is returned, and the value of *pnOut
21127** is set to the length of the returned string in bytes. The call should
21128** arrange to call sqlite3DbFree() on the returned pointer when it is
21129** no longer required.
21130**
21131** If a malloc failure occurs, NULL is returned and the db.mallocFailed
21132** flag set.
21133*/
21134#ifdef SQLITE_ENABLE_STAT3
21135SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *db, u8 enc, char *z, int n, int *pnOut){
21136  Mem m;
21137  memset(&m, 0, sizeof(m));
21138  m.db = db;
21139  sqlite3VdbeMemSetStr(&m, z, n, SQLITE_UTF8, SQLITE_STATIC);
21140  if( sqlite3VdbeMemTranslate(&m, enc) ){
21141    assert( db->mallocFailed );
21142    return 0;
21143  }
21144  assert( m.z==m.zMalloc );
21145  *pnOut = m.n;
21146  return m.z;
21147}
21148#endif
21149
21150/*
21151** zIn is a UTF-16 encoded unicode string at least nChar characters long.
21152** Return the number of bytes in the first nChar unicode characters
21153** in pZ.  nChar must be non-negative.
21154*/
21155SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
21156  int c;
21157  unsigned char const *z = zIn;
21158  int n = 0;
21159
21160  if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
21161    while( n<nChar ){
21162      READ_UTF16BE(z, 1, c);
21163      n++;
21164    }
21165  }else{
21166    while( n<nChar ){
21167      READ_UTF16LE(z, 1, c);
21168      n++;
21169    }
21170  }
21171  return (int)(z-(unsigned char const *)zIn);
21172}
21173
21174#if defined(SQLITE_TEST)
21175/*
21176** This routine is called from the TCL test function "translate_selftest".
21177** It checks that the primitives for serializing and deserializing
21178** characters in each encoding are inverses of each other.
21179*/
21180SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
21181  unsigned int i, t;
21182  unsigned char zBuf[20];
21183  unsigned char *z;
21184  int n;
21185  unsigned int c;
21186
21187  for(i=0; i<0x00110000; i++){
21188    z = zBuf;
21189    WRITE_UTF8(z, i);
21190    n = (int)(z-zBuf);
21191    assert( n>0 && n<=4 );
21192    z[0] = 0;
21193    z = zBuf;
21194    c = sqlite3Utf8Read((const u8**)&z);
21195    t = i;
21196    if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
21197    if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
21198    assert( c==t );
21199    assert( (z-zBuf)==n );
21200  }
21201  for(i=0; i<0x00110000; i++){
21202    if( i>=0xD800 && i<0xE000 ) continue;
21203    z = zBuf;
21204    WRITE_UTF16LE(z, i);
21205    n = (int)(z-zBuf);
21206    assert( n>0 && n<=4 );
21207    z[0] = 0;
21208    z = zBuf;
21209    READ_UTF16LE(z, 1, c);
21210    assert( c==i );
21211    assert( (z-zBuf)==n );
21212  }
21213  for(i=0; i<0x00110000; i++){
21214    if( i>=0xD800 && i<0xE000 ) continue;
21215    z = zBuf;
21216    WRITE_UTF16BE(z, i);
21217    n = (int)(z-zBuf);
21218    assert( n>0 && n<=4 );
21219    z[0] = 0;
21220    z = zBuf;
21221    READ_UTF16BE(z, 1, c);
21222    assert( c==i );
21223    assert( (z-zBuf)==n );
21224  }
21225}
21226#endif /* SQLITE_TEST */
21227#endif /* SQLITE_OMIT_UTF16 */
21228
21229/************** End of utf.c *************************************************/
21230/************** Begin file util.c ********************************************/
21231/*
21232** 2001 September 15
21233**
21234** The author disclaims copyright to this source code.  In place of
21235** a legal notice, here is a blessing:
21236**
21237**    May you do good and not evil.
21238**    May you find forgiveness for yourself and forgive others.
21239**    May you share freely, never taking more than you give.
21240**
21241*************************************************************************
21242** Utility functions used throughout sqlite.
21243**
21244** This file contains functions for allocating memory, comparing
21245** strings, and stuff like that.
21246**
21247*/
21248/* #include <stdarg.h> */
21249#ifdef SQLITE_HAVE_ISNAN
21250# include <math.h>
21251#endif
21252
21253/*
21254** Routine needed to support the testcase() macro.
21255*/
21256#ifdef SQLITE_COVERAGE_TEST
21257SQLITE_PRIVATE void sqlite3Coverage(int x){
21258  static unsigned dummy = 0;
21259  dummy += (unsigned)x;
21260}
21261#endif
21262
21263#ifndef SQLITE_OMIT_FLOATING_POINT
21264/*
21265** Return true if the floating point value is Not a Number (NaN).
21266**
21267** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
21268** Otherwise, we have our own implementation that works on most systems.
21269*/
21270SQLITE_PRIVATE int sqlite3IsNaN(double x){
21271  int rc;   /* The value return */
21272#if !defined(SQLITE_HAVE_ISNAN)
21273  /*
21274  ** Systems that support the isnan() library function should probably
21275  ** make use of it by compiling with -DSQLITE_HAVE_ISNAN.  But we have
21276  ** found that many systems do not have a working isnan() function so
21277  ** this implementation is provided as an alternative.
21278  **
21279  ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
21280  ** On the other hand, the use of -ffast-math comes with the following
21281  ** warning:
21282  **
21283  **      This option [-ffast-math] should never be turned on by any
21284  **      -O option since it can result in incorrect output for programs
21285  **      which depend on an exact implementation of IEEE or ISO
21286  **      rules/specifications for math functions.
21287  **
21288  ** Under MSVC, this NaN test may fail if compiled with a floating-
21289  ** point precision mode other than /fp:precise.  From the MSDN
21290  ** documentation:
21291  **
21292  **      The compiler [with /fp:precise] will properly handle comparisons
21293  **      involving NaN. For example, x != x evaluates to true if x is NaN
21294  **      ...
21295  */
21296#ifdef __FAST_MATH__
21297# error SQLite will not work correctly with the -ffast-math option of GCC.
21298#endif
21299  volatile double y = x;
21300  volatile double z = y;
21301  rc = (y!=z);
21302#else  /* if defined(SQLITE_HAVE_ISNAN) */
21303  rc = isnan(x);
21304#endif /* SQLITE_HAVE_ISNAN */
21305  testcase( rc );
21306  return rc;
21307}
21308#endif /* SQLITE_OMIT_FLOATING_POINT */
21309
21310/*
21311** Compute a string length that is limited to what can be stored in
21312** lower 30 bits of a 32-bit signed integer.
21313**
21314** The value returned will never be negative.  Nor will it ever be greater
21315** than the actual length of the string.  For very long strings (greater
21316** than 1GiB) the value returned might be less than the true string length.
21317*/
21318SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
21319  const char *z2 = z;
21320  if( z==0 ) return 0;
21321  while( *z2 ){ z2++; }
21322  return 0x3fffffff & (int)(z2 - z);
21323}
21324
21325/*
21326** Set the most recent error code and error string for the sqlite
21327** handle "db". The error code is set to "err_code".
21328**
21329** If it is not NULL, string zFormat specifies the format of the
21330** error string in the style of the printf functions: The following
21331** format characters are allowed:
21332**
21333**      %s      Insert a string
21334**      %z      A string that should be freed after use
21335**      %d      Insert an integer
21336**      %T      Insert a token
21337**      %S      Insert the first element of a SrcList
21338**
21339** zFormat and any string tokens that follow it are assumed to be
21340** encoded in UTF-8.
21341**
21342** To clear the most recent error for sqlite handle "db", sqlite3Error
21343** should be called with err_code set to SQLITE_OK and zFormat set
21344** to NULL.
21345*/
21346SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
21347  if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
21348    db->errCode = err_code;
21349    if( zFormat ){
21350      char *z;
21351      va_list ap;
21352      va_start(ap, zFormat);
21353      z = sqlite3VMPrintf(db, zFormat, ap);
21354      va_end(ap);
21355      sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
21356    }else{
21357      sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
21358    }
21359  }
21360}
21361
21362/*
21363** Add an error message to pParse->zErrMsg and increment pParse->nErr.
21364** The following formatting characters are allowed:
21365**
21366**      %s      Insert a string
21367**      %z      A string that should be freed after use
21368**      %d      Insert an integer
21369**      %T      Insert a token
21370**      %S      Insert the first element of a SrcList
21371**
21372** This function should be used to report any error that occurs whilst
21373** compiling an SQL statement (i.e. within sqlite3_prepare()). The
21374** last thing the sqlite3_prepare() function does is copy the error
21375** stored by this function into the database handle using sqlite3Error().
21376** Function sqlite3Error() should be used during statement execution
21377** (sqlite3_step() etc.).
21378*/
21379SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
21380  char *zMsg;
21381  va_list ap;
21382  sqlite3 *db = pParse->db;
21383  va_start(ap, zFormat);
21384  zMsg = sqlite3VMPrintf(db, zFormat, ap);
21385  va_end(ap);
21386  if( db->suppressErr ){
21387    sqlite3DbFree(db, zMsg);
21388  }else{
21389    pParse->nErr++;
21390    sqlite3DbFree(db, pParse->zErrMsg);
21391    pParse->zErrMsg = zMsg;
21392    pParse->rc = SQLITE_ERROR;
21393  }
21394}
21395
21396/*
21397** Convert an SQL-style quoted string into a normal string by removing
21398** the quote characters.  The conversion is done in-place.  If the
21399** input does not begin with a quote character, then this routine
21400** is a no-op.
21401**
21402** The input string must be zero-terminated.  A new zero-terminator
21403** is added to the dequoted string.
21404**
21405** The return value is -1 if no dequoting occurs or the length of the
21406** dequoted string, exclusive of the zero terminator, if dequoting does
21407** occur.
21408**
21409** 2002-Feb-14: This routine is extended to remove MS-Access style
21410** brackets from around identifers.  For example:  "[a-b-c]" becomes
21411** "a-b-c".
21412*/
21413SQLITE_PRIVATE int sqlite3Dequote(char *z){
21414  char quote;
21415  int i, j;
21416  if( z==0 ) return -1;
21417  quote = z[0];
21418  switch( quote ){
21419    case '\'':  break;
21420    case '"':   break;
21421    case '`':   break;                /* For MySQL compatibility */
21422    case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
21423    default:    return -1;
21424  }
21425  for(i=1, j=0; ALWAYS(z[i]); i++){
21426    if( z[i]==quote ){
21427      if( z[i+1]==quote ){
21428        z[j++] = quote;
21429        i++;
21430      }else{
21431        break;
21432      }
21433    }else{
21434      z[j++] = z[i];
21435    }
21436  }
21437  z[j] = 0;
21438  return j;
21439}
21440
21441/* Convenient short-hand */
21442#define UpperToLower sqlite3UpperToLower
21443
21444/*
21445** Some systems have stricmp().  Others have strcasecmp().  Because
21446** there is no consistency, we will define our own.
21447**
21448** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
21449** sqlite3_strnicmp() APIs allow applications and extensions to compare
21450** the contents of two buffers containing UTF-8 strings in a
21451** case-independent fashion, using the same definition of "case
21452** independence" that SQLite uses internally when comparing identifiers.
21453*/
21454SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){
21455  register unsigned char *a, *b;
21456  a = (unsigned char *)zLeft;
21457  b = (unsigned char *)zRight;
21458  while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
21459  return UpperToLower[*a] - UpperToLower[*b];
21460}
21461SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
21462  register unsigned char *a, *b;
21463  a = (unsigned char *)zLeft;
21464  b = (unsigned char *)zRight;
21465  while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
21466  return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
21467}
21468
21469/*
21470** The string z[] is an text representation of a real number.
21471** Convert this string to a double and write it into *pResult.
21472**
21473** The string z[] is length bytes in length (bytes, not characters) and
21474** uses the encoding enc.  The string is not necessarily zero-terminated.
21475**
21476** Return TRUE if the result is a valid real number (or integer) and FALSE
21477** if the string is empty or contains extraneous text.  Valid numbers
21478** are in one of these formats:
21479**
21480**    [+-]digits[E[+-]digits]
21481**    [+-]digits.[digits][E[+-]digits]
21482**    [+-].digits[E[+-]digits]
21483**
21484** Leading and trailing whitespace is ignored for the purpose of determining
21485** validity.
21486**
21487** If some prefix of the input string is a valid number, this routine
21488** returns FALSE but it still converts the prefix and writes the result
21489** into *pResult.
21490*/
21491SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
21492#ifndef SQLITE_OMIT_FLOATING_POINT
21493  int incr;
21494  const char *zEnd = z + length;
21495  /* sign * significand * (10 ^ (esign * exponent)) */
21496  int sign = 1;    /* sign of significand */
21497  i64 s = 0;       /* significand */
21498  int d = 0;       /* adjust exponent for shifting decimal point */
21499  int esign = 1;   /* sign of exponent */
21500  int e = 0;       /* exponent */
21501  int eValid = 1;  /* True exponent is either not used or is well-formed */
21502  double result;
21503  int nDigits = 0;
21504  int nonNum = 0;
21505
21506  assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
21507  *pResult = 0.0;   /* Default return value, in case of an error */
21508
21509  if( enc==SQLITE_UTF8 ){
21510    incr = 1;
21511  }else{
21512    int i;
21513    incr = 2;
21514    assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
21515    for(i=3-enc; i<length && z[i]==0; i+=2){}
21516    nonNum = i<length;
21517    zEnd = z+i+enc-3;
21518    z += (enc&1);
21519  }
21520
21521  /* skip leading spaces */
21522  while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
21523  if( z>=zEnd ) return 0;
21524
21525  /* get sign of significand */
21526  if( *z=='-' ){
21527    sign = -1;
21528    z+=incr;
21529  }else if( *z=='+' ){
21530    z+=incr;
21531  }
21532
21533  /* skip leading zeroes */
21534  while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
21535
21536  /* copy max significant digits to significand */
21537  while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
21538    s = s*10 + (*z - '0');
21539    z+=incr, nDigits++;
21540  }
21541
21542  /* skip non-significant significand digits
21543  ** (increase exponent by d to shift decimal left) */
21544  while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
21545  if( z>=zEnd ) goto do_atof_calc;
21546
21547  /* if decimal point is present */
21548  if( *z=='.' ){
21549    z+=incr;
21550    /* copy digits from after decimal to significand
21551    ** (decrease exponent by d to shift decimal right) */
21552    while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
21553      s = s*10 + (*z - '0');
21554      z+=incr, nDigits++, d--;
21555    }
21556    /* skip non-significant digits */
21557    while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
21558  }
21559  if( z>=zEnd ) goto do_atof_calc;
21560
21561  /* if exponent is present */
21562  if( *z=='e' || *z=='E' ){
21563    z+=incr;
21564    eValid = 0;
21565    if( z>=zEnd ) goto do_atof_calc;
21566    /* get sign of exponent */
21567    if( *z=='-' ){
21568      esign = -1;
21569      z+=incr;
21570    }else if( *z=='+' ){
21571      z+=incr;
21572    }
21573    /* copy digits to exponent */
21574    while( z<zEnd && sqlite3Isdigit(*z) ){
21575      e = e<10000 ? (e*10 + (*z - '0')) : 10000;
21576      z+=incr;
21577      eValid = 1;
21578    }
21579  }
21580
21581  /* skip trailing spaces */
21582  if( nDigits && eValid ){
21583    while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
21584  }
21585
21586do_atof_calc:
21587  /* adjust exponent by d, and update sign */
21588  e = (e*esign) + d;
21589  if( e<0 ) {
21590    esign = -1;
21591    e *= -1;
21592  } else {
21593    esign = 1;
21594  }
21595
21596  /* if 0 significand */
21597  if( !s ) {
21598    /* In the IEEE 754 standard, zero is signed.
21599    ** Add the sign if we've seen at least one digit */
21600    result = (sign<0 && nDigits) ? -(double)0 : (double)0;
21601  } else {
21602    /* attempt to reduce exponent */
21603    if( esign>0 ){
21604      while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
21605    }else{
21606      while( !(s%10) && e>0 ) e--,s/=10;
21607    }
21608
21609    /* adjust the sign of significand */
21610    s = sign<0 ? -s : s;
21611
21612    /* if exponent, scale significand as appropriate
21613    ** and store in result. */
21614    if( e ){
21615      LONGDOUBLE_TYPE scale = 1.0;
21616      /* attempt to handle extremely small/large numbers better */
21617      if( e>307 && e<342 ){
21618        while( e%308 ) { scale *= 1.0e+1; e -= 1; }
21619        if( esign<0 ){
21620          result = s / scale;
21621          result /= 1.0e+308;
21622        }else{
21623          result = s * scale;
21624          result *= 1.0e+308;
21625        }
21626      }else if( e>=342 ){
21627        if( esign<0 ){
21628          result = 0.0*s;
21629        }else{
21630          result = 1e308*1e308*s;  /* Infinity */
21631        }
21632      }else{
21633        /* 1.0e+22 is the largest power of 10 than can be
21634        ** represented exactly. */
21635        while( e%22 ) { scale *= 1.0e+1; e -= 1; }
21636        while( e>0 ) { scale *= 1.0e+22; e -= 22; }
21637        if( esign<0 ){
21638          result = s / scale;
21639        }else{
21640          result = s * scale;
21641        }
21642      }
21643    } else {
21644      result = (double)s;
21645    }
21646  }
21647
21648  /* store the result */
21649  *pResult = result;
21650
21651  /* return true if number and no extra non-whitespace chracters after */
21652  return z>=zEnd && nDigits>0 && eValid && nonNum==0;
21653#else
21654  return !sqlite3Atoi64(z, pResult, length, enc);
21655#endif /* SQLITE_OMIT_FLOATING_POINT */
21656}
21657
21658/*
21659** Compare the 19-character string zNum against the text representation
21660** value 2^63:  9223372036854775808.  Return negative, zero, or positive
21661** if zNum is less than, equal to, or greater than the string.
21662** Note that zNum must contain exactly 19 characters.
21663**
21664** Unlike memcmp() this routine is guaranteed to return the difference
21665** in the values of the last digit if the only difference is in the
21666** last digit.  So, for example,
21667**
21668**      compare2pow63("9223372036854775800", 1)
21669**
21670** will return -8.
21671*/
21672static int compare2pow63(const char *zNum, int incr){
21673  int c = 0;
21674  int i;
21675                    /* 012345678901234567 */
21676  const char *pow63 = "922337203685477580";
21677  for(i=0; c==0 && i<18; i++){
21678    c = (zNum[i*incr]-pow63[i])*10;
21679  }
21680  if( c==0 ){
21681    c = zNum[18*incr] - '8';
21682    testcase( c==(-1) );
21683    testcase( c==0 );
21684    testcase( c==(+1) );
21685  }
21686  return c;
21687}
21688
21689
21690/*
21691** Convert zNum to a 64-bit signed integer.
21692**
21693** If the zNum value is representable as a 64-bit twos-complement
21694** integer, then write that value into *pNum and return 0.
21695**
21696** If zNum is exactly 9223372036854665808, return 2.  This special
21697** case is broken out because while 9223372036854665808 cannot be a
21698** signed 64-bit integer, its negative -9223372036854665808 can be.
21699**
21700** If zNum is too big for a 64-bit integer and is not
21701** 9223372036854665808  or if zNum contains any non-numeric text,
21702** then return 1.
21703**
21704** length is the number of bytes in the string (bytes, not characters).
21705** The string is not necessarily zero-terminated.  The encoding is
21706** given by enc.
21707*/
21708SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
21709  int incr;
21710  u64 u = 0;
21711  int neg = 0; /* assume positive */
21712  int i;
21713  int c = 0;
21714  int nonNum = 0;
21715  const char *zStart;
21716  const char *zEnd = zNum + length;
21717  assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
21718  if( enc==SQLITE_UTF8 ){
21719    incr = 1;
21720  }else{
21721    incr = 2;
21722    assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
21723    for(i=3-enc; i<length && zNum[i]==0; i+=2){}
21724    nonNum = i<length;
21725    zEnd = zNum+i+enc-3;
21726    zNum += (enc&1);
21727  }
21728  while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
21729  if( zNum<zEnd ){
21730    if( *zNum=='-' ){
21731      neg = 1;
21732      zNum+=incr;
21733    }else if( *zNum=='+' ){
21734      zNum+=incr;
21735    }
21736  }
21737  zStart = zNum;
21738  while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
21739  for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
21740    u = u*10 + c - '0';
21741  }
21742  if( u>LARGEST_INT64 ){
21743    *pNum = SMALLEST_INT64;
21744  }else if( neg ){
21745    *pNum = -(i64)u;
21746  }else{
21747    *pNum = (i64)u;
21748  }
21749  testcase( i==18 );
21750  testcase( i==19 );
21751  testcase( i==20 );
21752  if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum) || i>19*incr || nonNum ){
21753    /* zNum is empty or contains non-numeric text or is longer
21754    ** than 19 digits (thus guaranteeing that it is too large) */
21755    return 1;
21756  }else if( i<19*incr ){
21757    /* Less than 19 digits, so we know that it fits in 64 bits */
21758    assert( u<=LARGEST_INT64 );
21759    return 0;
21760  }else{
21761    /* zNum is a 19-digit numbers.  Compare it against 9223372036854775808. */
21762    c = compare2pow63(zNum, incr);
21763    if( c<0 ){
21764      /* zNum is less than 9223372036854775808 so it fits */
21765      assert( u<=LARGEST_INT64 );
21766      return 0;
21767    }else if( c>0 ){
21768      /* zNum is greater than 9223372036854775808 so it overflows */
21769      return 1;
21770    }else{
21771      /* zNum is exactly 9223372036854775808.  Fits if negative.  The
21772      ** special case 2 overflow if positive */
21773      assert( u-1==LARGEST_INT64 );
21774      assert( (*pNum)==SMALLEST_INT64 );
21775      return neg ? 0 : 2;
21776    }
21777  }
21778}
21779
21780/*
21781** If zNum represents an integer that will fit in 32-bits, then set
21782** *pValue to that integer and return true.  Otherwise return false.
21783**
21784** Any non-numeric characters that following zNum are ignored.
21785** This is different from sqlite3Atoi64() which requires the
21786** input number to be zero-terminated.
21787*/
21788SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
21789  sqlite_int64 v = 0;
21790  int i, c;
21791  int neg = 0;
21792  if( zNum[0]=='-' ){
21793    neg = 1;
21794    zNum++;
21795  }else if( zNum[0]=='+' ){
21796    zNum++;
21797  }
21798  while( zNum[0]=='0' ) zNum++;
21799  for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
21800    v = v*10 + c;
21801  }
21802
21803  /* The longest decimal representation of a 32 bit integer is 10 digits:
21804  **
21805  **             1234567890
21806  **     2^31 -> 2147483648
21807  */
21808  testcase( i==10 );
21809  if( i>10 ){
21810    return 0;
21811  }
21812  testcase( v-neg==2147483647 );
21813  if( v-neg>2147483647 ){
21814    return 0;
21815  }
21816  if( neg ){
21817    v = -v;
21818  }
21819  *pValue = (int)v;
21820  return 1;
21821}
21822
21823/*
21824** Return a 32-bit integer value extracted from a string.  If the
21825** string is not an integer, just return 0.
21826*/
21827SQLITE_PRIVATE int sqlite3Atoi(const char *z){
21828  int x = 0;
21829  if( z ) sqlite3GetInt32(z, &x);
21830  return x;
21831}
21832
21833/*
21834** The variable-length integer encoding is as follows:
21835**
21836** KEY:
21837**         A = 0xxxxxxx    7 bits of data and one flag bit
21838**         B = 1xxxxxxx    7 bits of data and one flag bit
21839**         C = xxxxxxxx    8 bits of data
21840**
21841**  7 bits - A
21842** 14 bits - BA
21843** 21 bits - BBA
21844** 28 bits - BBBA
21845** 35 bits - BBBBA
21846** 42 bits - BBBBBA
21847** 49 bits - BBBBBBA
21848** 56 bits - BBBBBBBA
21849** 64 bits - BBBBBBBBC
21850*/
21851
21852/*
21853** Write a 64-bit variable-length integer to memory starting at p[0].
21854** The length of data write will be between 1 and 9 bytes.  The number
21855** of bytes written is returned.
21856**
21857** A variable-length integer consists of the lower 7 bits of each byte
21858** for all bytes that have the 8th bit set and one byte with the 8th
21859** bit clear.  Except, if we get to the 9th byte, it stores the full
21860** 8 bits and is the last byte.
21861*/
21862SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
21863  int i, j, n;
21864  u8 buf[10];
21865  if( v & (((u64)0xff000000)<<32) ){
21866    p[8] = (u8)v;
21867    v >>= 8;
21868    for(i=7; i>=0; i--){
21869      p[i] = (u8)((v & 0x7f) | 0x80);
21870      v >>= 7;
21871    }
21872    return 9;
21873  }
21874  n = 0;
21875  do{
21876    buf[n++] = (u8)((v & 0x7f) | 0x80);
21877    v >>= 7;
21878  }while( v!=0 );
21879  buf[0] &= 0x7f;
21880  assert( n<=9 );
21881  for(i=0, j=n-1; j>=0; j--, i++){
21882    p[i] = buf[j];
21883  }
21884  return n;
21885}
21886
21887/*
21888** This routine is a faster version of sqlite3PutVarint() that only
21889** works for 32-bit positive integers and which is optimized for
21890** the common case of small integers.  A MACRO version, putVarint32,
21891** is provided which inlines the single-byte case.  All code should use
21892** the MACRO version as this function assumes the single-byte case has
21893** already been handled.
21894*/
21895SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
21896#ifndef putVarint32
21897  if( (v & ~0x7f)==0 ){
21898    p[0] = v;
21899    return 1;
21900  }
21901#endif
21902  if( (v & ~0x3fff)==0 ){
21903    p[0] = (u8)((v>>7) | 0x80);
21904    p[1] = (u8)(v & 0x7f);
21905    return 2;
21906  }
21907  return sqlite3PutVarint(p, v);
21908}
21909
21910/*
21911** Bitmasks used by sqlite3GetVarint().  These precomputed constants
21912** are defined here rather than simply putting the constant expressions
21913** inline in order to work around bugs in the RVT compiler.
21914**
21915** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
21916**
21917** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
21918*/
21919#define SLOT_2_0     0x001fc07f
21920#define SLOT_4_2_0   0xf01fc07f
21921
21922
21923/*
21924** Read a 64-bit variable-length integer from memory starting at p[0].
21925** Return the number of bytes read.  The value is stored in *v.
21926*/
21927SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
21928  u32 a,b,s;
21929
21930  a = *p;
21931  /* a: p0 (unmasked) */
21932  if (!(a&0x80))
21933  {
21934    *v = a;
21935    return 1;
21936  }
21937
21938  p++;
21939  b = *p;
21940  /* b: p1 (unmasked) */
21941  if (!(b&0x80))
21942  {
21943    a &= 0x7f;
21944    a = a<<7;
21945    a |= b;
21946    *v = a;
21947    return 2;
21948  }
21949
21950  /* Verify that constants are precomputed correctly */
21951  assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
21952  assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
21953
21954  p++;
21955  a = a<<14;
21956  a |= *p;
21957  /* a: p0<<14 | p2 (unmasked) */
21958  if (!(a&0x80))
21959  {
21960    a &= SLOT_2_0;
21961    b &= 0x7f;
21962    b = b<<7;
21963    a |= b;
21964    *v = a;
21965    return 3;
21966  }
21967
21968  /* CSE1 from below */
21969  a &= SLOT_2_0;
21970  p++;
21971  b = b<<14;
21972  b |= *p;
21973  /* b: p1<<14 | p3 (unmasked) */
21974  if (!(b&0x80))
21975  {
21976    b &= SLOT_2_0;
21977    /* moved CSE1 up */
21978    /* a &= (0x7f<<14)|(0x7f); */
21979    a = a<<7;
21980    a |= b;
21981    *v = a;
21982    return 4;
21983  }
21984
21985  /* a: p0<<14 | p2 (masked) */
21986  /* b: p1<<14 | p3 (unmasked) */
21987  /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
21988  /* moved CSE1 up */
21989  /* a &= (0x7f<<14)|(0x7f); */
21990  b &= SLOT_2_0;
21991  s = a;
21992  /* s: p0<<14 | p2 (masked) */
21993
21994  p++;
21995  a = a<<14;
21996  a |= *p;
21997  /* a: p0<<28 | p2<<14 | p4 (unmasked) */
21998  if (!(a&0x80))
21999  {
22000    /* we can skip these cause they were (effectively) done above in calc'ing s */
22001    /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
22002    /* b &= (0x7f<<14)|(0x7f); */
22003    b = b<<7;
22004    a |= b;
22005    s = s>>18;
22006    *v = ((u64)s)<<32 | a;
22007    return 5;
22008  }
22009
22010  /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
22011  s = s<<7;
22012  s |= b;
22013  /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
22014
22015  p++;
22016  b = b<<14;
22017  b |= *p;
22018  /* b: p1<<28 | p3<<14 | p5 (unmasked) */
22019  if (!(b&0x80))
22020  {
22021    /* we can skip this cause it was (effectively) done above in calc'ing s */
22022    /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
22023    a &= SLOT_2_0;
22024    a = a<<7;
22025    a |= b;
22026    s = s>>18;
22027    *v = ((u64)s)<<32 | a;
22028    return 6;
22029  }
22030
22031  p++;
22032  a = a<<14;
22033  a |= *p;
22034  /* a: p2<<28 | p4<<14 | p6 (unmasked) */
22035  if (!(a&0x80))
22036  {
22037    a &= SLOT_4_2_0;
22038    b &= SLOT_2_0;
22039    b = b<<7;
22040    a |= b;
22041    s = s>>11;
22042    *v = ((u64)s)<<32 | a;
22043    return 7;
22044  }
22045
22046  /* CSE2 from below */
22047  a &= SLOT_2_0;
22048  p++;
22049  b = b<<14;
22050  b |= *p;
22051  /* b: p3<<28 | p5<<14 | p7 (unmasked) */
22052  if (!(b&0x80))
22053  {
22054    b &= SLOT_4_2_0;
22055    /* moved CSE2 up */
22056    /* a &= (0x7f<<14)|(0x7f); */
22057    a = a<<7;
22058    a |= b;
22059    s = s>>4;
22060    *v = ((u64)s)<<32 | a;
22061    return 8;
22062  }
22063
22064  p++;
22065  a = a<<15;
22066  a |= *p;
22067  /* a: p4<<29 | p6<<15 | p8 (unmasked) */
22068
22069  /* moved CSE2 up */
22070  /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
22071  b &= SLOT_2_0;
22072  b = b<<8;
22073  a |= b;
22074
22075  s = s<<4;
22076  b = p[-4];
22077  b &= 0x7f;
22078  b = b>>3;
22079  s |= b;
22080
22081  *v = ((u64)s)<<32 | a;
22082
22083  return 9;
22084}
22085
22086/*
22087** Read a 32-bit variable-length integer from memory starting at p[0].
22088** Return the number of bytes read.  The value is stored in *v.
22089**
22090** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
22091** integer, then set *v to 0xffffffff.
22092**
22093** A MACRO version, getVarint32, is provided which inlines the
22094** single-byte case.  All code should use the MACRO version as
22095** this function assumes the single-byte case has already been handled.
22096*/
22097SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
22098  u32 a,b;
22099
22100  /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
22101  ** by the getVarin32() macro */
22102  a = *p;
22103  /* a: p0 (unmasked) */
22104#ifndef getVarint32
22105  if (!(a&0x80))
22106  {
22107    /* Values between 0 and 127 */
22108    *v = a;
22109    return 1;
22110  }
22111#endif
22112
22113  /* The 2-byte case */
22114  p++;
22115  b = *p;
22116  /* b: p1 (unmasked) */
22117  if (!(b&0x80))
22118  {
22119    /* Values between 128 and 16383 */
22120    a &= 0x7f;
22121    a = a<<7;
22122    *v = a | b;
22123    return 2;
22124  }
22125
22126  /* The 3-byte case */
22127  p++;
22128  a = a<<14;
22129  a |= *p;
22130  /* a: p0<<14 | p2 (unmasked) */
22131  if (!(a&0x80))
22132  {
22133    /* Values between 16384 and 2097151 */
22134    a &= (0x7f<<14)|(0x7f);
22135    b &= 0x7f;
22136    b = b<<7;
22137    *v = a | b;
22138    return 3;
22139  }
22140
22141  /* A 32-bit varint is used to store size information in btrees.
22142  ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
22143  ** A 3-byte varint is sufficient, for example, to record the size
22144  ** of a 1048569-byte BLOB or string.
22145  **
22146  ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
22147  ** rare larger cases can be handled by the slower 64-bit varint
22148  ** routine.
22149  */
22150#if 1
22151  {
22152    u64 v64;
22153    u8 n;
22154
22155    p -= 2;
22156    n = sqlite3GetVarint(p, &v64);
22157    assert( n>3 && n<=9 );
22158    if( (v64 & SQLITE_MAX_U32)!=v64 ){
22159      *v = 0xffffffff;
22160    }else{
22161      *v = (u32)v64;
22162    }
22163    return n;
22164  }
22165
22166#else
22167  /* For following code (kept for historical record only) shows an
22168  ** unrolling for the 3- and 4-byte varint cases.  This code is
22169  ** slightly faster, but it is also larger and much harder to test.
22170  */
22171  p++;
22172  b = b<<14;
22173  b |= *p;
22174  /* b: p1<<14 | p3 (unmasked) */
22175  if (!(b&0x80))
22176  {
22177    /* Values between 2097152 and 268435455 */
22178    b &= (0x7f<<14)|(0x7f);
22179    a &= (0x7f<<14)|(0x7f);
22180    a = a<<7;
22181    *v = a | b;
22182    return 4;
22183  }
22184
22185  p++;
22186  a = a<<14;
22187  a |= *p;
22188  /* a: p0<<28 | p2<<14 | p4 (unmasked) */
22189  if (!(a&0x80))
22190  {
22191    /* Values  between 268435456 and 34359738367 */
22192    a &= SLOT_4_2_0;
22193    b &= SLOT_4_2_0;
22194    b = b<<7;
22195    *v = a | b;
22196    return 5;
22197  }
22198
22199  /* We can only reach this point when reading a corrupt database
22200  ** file.  In that case we are not in any hurry.  Use the (relatively
22201  ** slow) general-purpose sqlite3GetVarint() routine to extract the
22202  ** value. */
22203  {
22204    u64 v64;
22205    u8 n;
22206
22207    p -= 4;
22208    n = sqlite3GetVarint(p, &v64);
22209    assert( n>5 && n<=9 );
22210    *v = (u32)v64;
22211    return n;
22212  }
22213#endif
22214}
22215
22216/*
22217** Return the number of bytes that will be needed to store the given
22218** 64-bit integer.
22219*/
22220SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
22221  int i = 0;
22222  do{
22223    i++;
22224    v >>= 7;
22225  }while( v!=0 && ALWAYS(i<9) );
22226  return i;
22227}
22228
22229
22230/*
22231** Read or write a four-byte big-endian integer value.
22232*/
22233SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
22234  return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
22235}
22236SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
22237  p[0] = (u8)(v>>24);
22238  p[1] = (u8)(v>>16);
22239  p[2] = (u8)(v>>8);
22240  p[3] = (u8)v;
22241}
22242
22243
22244
22245/*
22246** Translate a single byte of Hex into an integer.
22247** This routine only works if h really is a valid hexadecimal
22248** character:  0..9a..fA..F
22249*/
22250SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
22251  assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
22252#ifdef SQLITE_ASCII
22253  h += 9*(1&(h>>6));
22254#endif
22255#ifdef SQLITE_EBCDIC
22256  h += 9*(1&~(h>>4));
22257#endif
22258  return (u8)(h & 0xf);
22259}
22260
22261#if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
22262/*
22263** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
22264** value.  Return a pointer to its binary value.  Space to hold the
22265** binary value has been obtained from malloc and must be freed by
22266** the calling routine.
22267*/
22268SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
22269  char *zBlob;
22270  int i;
22271
22272  zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
22273  n--;
22274  if( zBlob ){
22275    for(i=0; i<n; i+=2){
22276      zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
22277    }
22278    zBlob[i/2] = 0;
22279  }
22280  return zBlob;
22281}
22282#endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
22283
22284/*
22285** Log an error that is an API call on a connection pointer that should
22286** not have been used.  The "type" of connection pointer is given as the
22287** argument.  The zType is a word like "NULL" or "closed" or "invalid".
22288*/
22289static void logBadConnection(const char *zType){
22290  sqlite3_log(SQLITE_MISUSE,
22291     "API call with %s database connection pointer",
22292     zType
22293  );
22294}
22295
22296/*
22297** Check to make sure we have a valid db pointer.  This test is not
22298** foolproof but it does provide some measure of protection against
22299** misuse of the interface such as passing in db pointers that are
22300** NULL or which have been previously closed.  If this routine returns
22301** 1 it means that the db pointer is valid and 0 if it should not be
22302** dereferenced for any reason.  The calling function should invoke
22303** SQLITE_MISUSE immediately.
22304**
22305** sqlite3SafetyCheckOk() requires that the db pointer be valid for
22306** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
22307** open properly and is not fit for general use but which can be
22308** used as an argument to sqlite3_errmsg() or sqlite3_close().
22309*/
22310SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
22311  u32 magic;
22312  if( db==0 ){
22313    logBadConnection("NULL");
22314    return 0;
22315  }
22316  magic = db->magic;
22317  if( magic!=SQLITE_MAGIC_OPEN ){
22318    if( sqlite3SafetyCheckSickOrOk(db) ){
22319      testcase( sqlite3GlobalConfig.xLog!=0 );
22320      logBadConnection("unopened");
22321    }
22322    return 0;
22323  }else{
22324    return 1;
22325  }
22326}
22327SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
22328  u32 magic;
22329  magic = db->magic;
22330  if( magic!=SQLITE_MAGIC_SICK &&
22331      magic!=SQLITE_MAGIC_OPEN &&
22332      magic!=SQLITE_MAGIC_BUSY ){
22333    testcase( sqlite3GlobalConfig.xLog!=0 );
22334    logBadConnection("invalid");
22335    return 0;
22336  }else{
22337    return 1;
22338  }
22339}
22340
22341/*
22342** Attempt to add, substract, or multiply the 64-bit signed value iB against
22343** the other 64-bit signed integer at *pA and store the result in *pA.
22344** Return 0 on success.  Or if the operation would have resulted in an
22345** overflow, leave *pA unchanged and return 1.
22346*/
22347SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
22348  i64 iA = *pA;
22349  testcase( iA==0 ); testcase( iA==1 );
22350  testcase( iB==-1 ); testcase( iB==0 );
22351  if( iB>=0 ){
22352    testcase( iA>0 && LARGEST_INT64 - iA == iB );
22353    testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
22354    if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
22355    *pA += iB;
22356  }else{
22357    testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
22358    testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
22359    if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
22360    *pA += iB;
22361  }
22362  return 0;
22363}
22364SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
22365  testcase( iB==SMALLEST_INT64+1 );
22366  if( iB==SMALLEST_INT64 ){
22367    testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
22368    if( (*pA)>=0 ) return 1;
22369    *pA -= iB;
22370    return 0;
22371  }else{
22372    return sqlite3AddInt64(pA, -iB);
22373  }
22374}
22375#define TWOPOWER32 (((i64)1)<<32)
22376#define TWOPOWER31 (((i64)1)<<31)
22377SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
22378  i64 iA = *pA;
22379  i64 iA1, iA0, iB1, iB0, r;
22380
22381  iA1 = iA/TWOPOWER32;
22382  iA0 = iA % TWOPOWER32;
22383  iB1 = iB/TWOPOWER32;
22384  iB0 = iB % TWOPOWER32;
22385  if( iA1*iB1 != 0 ) return 1;
22386  assert( iA1*iB0==0 || iA0*iB1==0 );
22387  r = iA1*iB0 + iA0*iB1;
22388  testcase( r==(-TWOPOWER31)-1 );
22389  testcase( r==(-TWOPOWER31) );
22390  testcase( r==TWOPOWER31 );
22391  testcase( r==TWOPOWER31-1 );
22392  if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
22393  r *= TWOPOWER32;
22394  if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
22395  *pA = r;
22396  return 0;
22397}
22398
22399/*
22400** Compute the absolute value of a 32-bit signed integer, of possible.  Or
22401** if the integer has a value of -2147483648, return +2147483647
22402*/
22403SQLITE_PRIVATE int sqlite3AbsInt32(int x){
22404  if( x>=0 ) return x;
22405  if( x==(int)0x80000000 ) return 0x7fffffff;
22406  return -x;
22407}
22408
22409#ifdef SQLITE_ENABLE_8_3_NAMES
22410/*
22411** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
22412** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
22413** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
22414** three characters, then shorten the suffix on z[] to be the last three
22415** characters of the original suffix.
22416**
22417** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
22418** do the suffix shortening regardless of URI parameter.
22419**
22420** Examples:
22421**
22422**     test.db-journal    =>   test.nal
22423**     test.db-wal        =>   test.wal
22424**     test.db-shm        =>   test.shm
22425**     test.db-mj7f3319fa =>   test.9fa
22426*/
22427SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
22428#if SQLITE_ENABLE_8_3_NAMES<2
22429  if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
22430#endif
22431  {
22432    int i, sz;
22433    sz = sqlite3Strlen30(z);
22434    for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
22435    if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
22436  }
22437}
22438#endif
22439
22440/************** End of util.c ************************************************/
22441/************** Begin file hash.c ********************************************/
22442/*
22443** 2001 September 22
22444**
22445** The author disclaims copyright to this source code.  In place of
22446** a legal notice, here is a blessing:
22447**
22448**    May you do good and not evil.
22449**    May you find forgiveness for yourself and forgive others.
22450**    May you share freely, never taking more than you give.
22451**
22452*************************************************************************
22453** This is the implementation of generic hash-tables
22454** used in SQLite.
22455*/
22456/* #include <assert.h> */
22457
22458/* Turn bulk memory into a hash table object by initializing the
22459** fields of the Hash structure.
22460**
22461** "pNew" is a pointer to the hash table that is to be initialized.
22462*/
22463SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
22464  assert( pNew!=0 );
22465  pNew->first = 0;
22466  pNew->count = 0;
22467  pNew->htsize = 0;
22468  pNew->ht = 0;
22469}
22470
22471/* Remove all entries from a hash table.  Reclaim all memory.
22472** Call this routine to delete a hash table or to reset a hash table
22473** to the empty state.
22474*/
22475SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
22476  HashElem *elem;         /* For looping over all elements of the table */
22477
22478  assert( pH!=0 );
22479  elem = pH->first;
22480  pH->first = 0;
22481  sqlite3_free(pH->ht);
22482  pH->ht = 0;
22483  pH->htsize = 0;
22484  while( elem ){
22485    HashElem *next_elem = elem->next;
22486    sqlite3_free(elem);
22487    elem = next_elem;
22488  }
22489  pH->count = 0;
22490}
22491
22492/*
22493** The hashing function.
22494*/
22495static unsigned int strHash(const char *z, int nKey){
22496  int h = 0;
22497  assert( nKey>=0 );
22498  while( nKey > 0  ){
22499    h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
22500    nKey--;
22501  }
22502  return h;
22503}
22504
22505
22506/* Link pNew element into the hash table pH.  If pEntry!=0 then also
22507** insert pNew into the pEntry hash bucket.
22508*/
22509static void insertElement(
22510  Hash *pH,              /* The complete hash table */
22511  struct _ht *pEntry,    /* The entry into which pNew is inserted */
22512  HashElem *pNew         /* The element to be inserted */
22513){
22514  HashElem *pHead;       /* First element already in pEntry */
22515  if( pEntry ){
22516    pHead = pEntry->count ? pEntry->chain : 0;
22517    pEntry->count++;
22518    pEntry->chain = pNew;
22519  }else{
22520    pHead = 0;
22521  }
22522  if( pHead ){
22523    pNew->next = pHead;
22524    pNew->prev = pHead->prev;
22525    if( pHead->prev ){ pHead->prev->next = pNew; }
22526    else             { pH->first = pNew; }
22527    pHead->prev = pNew;
22528  }else{
22529    pNew->next = pH->first;
22530    if( pH->first ){ pH->first->prev = pNew; }
22531    pNew->prev = 0;
22532    pH->first = pNew;
22533  }
22534}
22535
22536
22537/* Resize the hash table so that it cantains "new_size" buckets.
22538**
22539** The hash table might fail to resize if sqlite3_malloc() fails or
22540** if the new size is the same as the prior size.
22541** Return TRUE if the resize occurs and false if not.
22542*/
22543static int rehash(Hash *pH, unsigned int new_size){
22544  struct _ht *new_ht;            /* The new hash table */
22545  HashElem *elem, *next_elem;    /* For looping over existing elements */
22546
22547#if SQLITE_MALLOC_SOFT_LIMIT>0
22548  if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
22549    new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
22550  }
22551  if( new_size==pH->htsize ) return 0;
22552#endif
22553
22554  /* The inability to allocates space for a larger hash table is
22555  ** a performance hit but it is not a fatal error.  So mark the
22556  ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of
22557  ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
22558  ** only zeroes the requested number of bytes whereas this module will
22559  ** use the actual amount of space allocated for the hash table (which
22560  ** may be larger than the requested amount).
22561  */
22562  sqlite3BeginBenignMalloc();
22563  new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
22564  sqlite3EndBenignMalloc();
22565
22566  if( new_ht==0 ) return 0;
22567  sqlite3_free(pH->ht);
22568  pH->ht = new_ht;
22569  pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
22570  memset(new_ht, 0, new_size*sizeof(struct _ht));
22571  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
22572    unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
22573    next_elem = elem->next;
22574    insertElement(pH, &new_ht[h], elem);
22575  }
22576  return 1;
22577}
22578
22579/* This function (for internal use only) locates an element in an
22580** hash table that matches the given key.  The hash for this key has
22581** already been computed and is passed as the 4th parameter.
22582*/
22583static HashElem *findElementGivenHash(
22584  const Hash *pH,     /* The pH to be searched */
22585  const char *pKey,   /* The key we are searching for */
22586  int nKey,           /* Bytes in key (not counting zero terminator) */
22587  unsigned int h      /* The hash for this key. */
22588){
22589  HashElem *elem;                /* Used to loop thru the element list */
22590  int count;                     /* Number of elements left to test */
22591
22592  if( pH->ht ){
22593    struct _ht *pEntry = &pH->ht[h];
22594    elem = pEntry->chain;
22595    count = pEntry->count;
22596  }else{
22597    elem = pH->first;
22598    count = pH->count;
22599  }
22600  while( count-- && ALWAYS(elem) ){
22601    if( elem->nKey==nKey && sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){
22602      return elem;
22603    }
22604    elem = elem->next;
22605  }
22606  return 0;
22607}
22608
22609/* Remove a single entry from the hash table given a pointer to that
22610** element and a hash on the element's key.
22611*/
22612static void removeElementGivenHash(
22613  Hash *pH,         /* The pH containing "elem" */
22614  HashElem* elem,   /* The element to be removed from the pH */
22615  unsigned int h    /* Hash value for the element */
22616){
22617  struct _ht *pEntry;
22618  if( elem->prev ){
22619    elem->prev->next = elem->next;
22620  }else{
22621    pH->first = elem->next;
22622  }
22623  if( elem->next ){
22624    elem->next->prev = elem->prev;
22625  }
22626  if( pH->ht ){
22627    pEntry = &pH->ht[h];
22628    if( pEntry->chain==elem ){
22629      pEntry->chain = elem->next;
22630    }
22631    pEntry->count--;
22632    assert( pEntry->count>=0 );
22633  }
22634  sqlite3_free( elem );
22635  pH->count--;
22636  if( pH->count==0 ){
22637    assert( pH->first==0 );
22638    assert( pH->count==0 );
22639    sqlite3HashClear(pH);
22640  }
22641}
22642
22643/* Attempt to locate an element of the hash table pH with a key
22644** that matches pKey,nKey.  Return the data for this element if it is
22645** found, or NULL if there is no match.
22646*/
22647SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey, int nKey){
22648  HashElem *elem;    /* The element that matches key */
22649  unsigned int h;    /* A hash on key */
22650
22651  assert( pH!=0 );
22652  assert( pKey!=0 );
22653  assert( nKey>=0 );
22654  if( pH->ht ){
22655    h = strHash(pKey, nKey) % pH->htsize;
22656  }else{
22657    h = 0;
22658  }
22659  elem = findElementGivenHash(pH, pKey, nKey, h);
22660  return elem ? elem->data : 0;
22661}
22662
22663/* Insert an element into the hash table pH.  The key is pKey,nKey
22664** and the data is "data".
22665**
22666** If no element exists with a matching key, then a new
22667** element is created and NULL is returned.
22668**
22669** If another element already exists with the same key, then the
22670** new data replaces the old data and the old data is returned.
22671** The key is not copied in this instance.  If a malloc fails, then
22672** the new data is returned and the hash table is unchanged.
22673**
22674** If the "data" parameter to this function is NULL, then the
22675** element corresponding to "key" is removed from the hash table.
22676*/
22677SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){
22678  unsigned int h;       /* the hash of the key modulo hash table size */
22679  HashElem *elem;       /* Used to loop thru the element list */
22680  HashElem *new_elem;   /* New element added to the pH */
22681
22682  assert( pH!=0 );
22683  assert( pKey!=0 );
22684  assert( nKey>=0 );
22685  if( pH->htsize ){
22686    h = strHash(pKey, nKey) % pH->htsize;
22687  }else{
22688    h = 0;
22689  }
22690  elem = findElementGivenHash(pH,pKey,nKey,h);
22691  if( elem ){
22692    void *old_data = elem->data;
22693    if( data==0 ){
22694      removeElementGivenHash(pH,elem,h);
22695    }else{
22696      elem->data = data;
22697      elem->pKey = pKey;
22698      assert(nKey==elem->nKey);
22699    }
22700    return old_data;
22701  }
22702  if( data==0 ) return 0;
22703  new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
22704  if( new_elem==0 ) return data;
22705  new_elem->pKey = pKey;
22706  new_elem->nKey = nKey;
22707  new_elem->data = data;
22708  pH->count++;
22709  if( pH->count>=10 && pH->count > 2*pH->htsize ){
22710    if( rehash(pH, pH->count*2) ){
22711      assert( pH->htsize>0 );
22712      h = strHash(pKey, nKey) % pH->htsize;
22713    }
22714  }
22715  if( pH->ht ){
22716    insertElement(pH, &pH->ht[h], new_elem);
22717  }else{
22718    insertElement(pH, 0, new_elem);
22719  }
22720  return 0;
22721}
22722
22723/************** End of hash.c ************************************************/
22724/************** Begin file opcodes.c *****************************************/
22725/* Automatically generated.  Do not edit */
22726/* See the mkopcodec.awk script for details. */
22727#if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
22728SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
22729 static const char *const azName[] = { "?",
22730     /*   1 */ "Goto",
22731     /*   2 */ "Gosub",
22732     /*   3 */ "Return",
22733     /*   4 */ "Yield",
22734     /*   5 */ "HaltIfNull",
22735     /*   6 */ "Halt",
22736     /*   7 */ "Integer",
22737     /*   8 */ "Int64",
22738     /*   9 */ "String",
22739     /*  10 */ "Null",
22740     /*  11 */ "Blob",
22741     /*  12 */ "Variable",
22742     /*  13 */ "Move",
22743     /*  14 */ "Copy",
22744     /*  15 */ "SCopy",
22745     /*  16 */ "ResultRow",
22746     /*  17 */ "CollSeq",
22747     /*  18 */ "Function",
22748     /*  19 */ "Not",
22749     /*  20 */ "AddImm",
22750     /*  21 */ "MustBeInt",
22751     /*  22 */ "RealAffinity",
22752     /*  23 */ "Permutation",
22753     /*  24 */ "Compare",
22754     /*  25 */ "Jump",
22755     /*  26 */ "Once",
22756     /*  27 */ "If",
22757     /*  28 */ "IfNot",
22758     /*  29 */ "Column",
22759     /*  30 */ "Affinity",
22760     /*  31 */ "MakeRecord",
22761     /*  32 */ "Count",
22762     /*  33 */ "Savepoint",
22763     /*  34 */ "AutoCommit",
22764     /*  35 */ "Transaction",
22765     /*  36 */ "ReadCookie",
22766     /*  37 */ "SetCookie",
22767     /*  38 */ "VerifyCookie",
22768     /*  39 */ "OpenRead",
22769     /*  40 */ "OpenWrite",
22770     /*  41 */ "OpenAutoindex",
22771     /*  42 */ "OpenEphemeral",
22772     /*  43 */ "SorterOpen",
22773     /*  44 */ "OpenPseudo",
22774     /*  45 */ "Close",
22775     /*  46 */ "SeekLt",
22776     /*  47 */ "SeekLe",
22777     /*  48 */ "SeekGe",
22778     /*  49 */ "SeekGt",
22779     /*  50 */ "Seek",
22780     /*  51 */ "NotFound",
22781     /*  52 */ "Found",
22782     /*  53 */ "IsUnique",
22783     /*  54 */ "NotExists",
22784     /*  55 */ "Sequence",
22785     /*  56 */ "NewRowid",
22786     /*  57 */ "Insert",
22787     /*  58 */ "InsertInt",
22788     /*  59 */ "Delete",
22789     /*  60 */ "ResetCount",
22790     /*  61 */ "SorterCompare",
22791     /*  62 */ "SorterData",
22792     /*  63 */ "RowKey",
22793     /*  64 */ "RowData",
22794     /*  65 */ "Rowid",
22795     /*  66 */ "NullRow",
22796     /*  67 */ "Last",
22797     /*  68 */ "Or",
22798     /*  69 */ "And",
22799     /*  70 */ "SorterSort",
22800     /*  71 */ "Sort",
22801     /*  72 */ "Rewind",
22802     /*  73 */ "IsNull",
22803     /*  74 */ "NotNull",
22804     /*  75 */ "Ne",
22805     /*  76 */ "Eq",
22806     /*  77 */ "Gt",
22807     /*  78 */ "Le",
22808     /*  79 */ "Lt",
22809     /*  80 */ "Ge",
22810     /*  81 */ "SorterNext",
22811     /*  82 */ "BitAnd",
22812     /*  83 */ "BitOr",
22813     /*  84 */ "ShiftLeft",
22814     /*  85 */ "ShiftRight",
22815     /*  86 */ "Add",
22816     /*  87 */ "Subtract",
22817     /*  88 */ "Multiply",
22818     /*  89 */ "Divide",
22819     /*  90 */ "Remainder",
22820     /*  91 */ "Concat",
22821     /*  92 */ "Prev",
22822     /*  93 */ "BitNot",
22823     /*  94 */ "String8",
22824     /*  95 */ "Next",
22825     /*  96 */ "SorterInsert",
22826     /*  97 */ "IdxInsert",
22827     /*  98 */ "IdxDelete",
22828     /*  99 */ "IdxRowid",
22829     /* 100 */ "IdxLT",
22830     /* 101 */ "IdxGE",
22831     /* 102 */ "Destroy",
22832     /* 103 */ "Clear",
22833     /* 104 */ "CreateIndex",
22834     /* 105 */ "CreateTable",
22835     /* 106 */ "ParseSchema",
22836     /* 107 */ "LoadAnalysis",
22837     /* 108 */ "DropTable",
22838     /* 109 */ "DropIndex",
22839     /* 110 */ "DropTrigger",
22840     /* 111 */ "IntegrityCk",
22841     /* 112 */ "RowSetAdd",
22842     /* 113 */ "RowSetRead",
22843     /* 114 */ "RowSetTest",
22844     /* 115 */ "Program",
22845     /* 116 */ "Param",
22846     /* 117 */ "FkCounter",
22847     /* 118 */ "FkIfZero",
22848     /* 119 */ "MemMax",
22849     /* 120 */ "IfPos",
22850     /* 121 */ "IfNeg",
22851     /* 122 */ "IfZero",
22852     /* 123 */ "AggStep",
22853     /* 124 */ "AggFinal",
22854     /* 125 */ "Checkpoint",
22855     /* 126 */ "JournalMode",
22856     /* 127 */ "Vacuum",
22857     /* 128 */ "IncrVacuum",
22858     /* 129 */ "Expire",
22859     /* 130 */ "Real",
22860     /* 131 */ "TableLock",
22861     /* 132 */ "VBegin",
22862     /* 133 */ "VCreate",
22863     /* 134 */ "VDestroy",
22864     /* 135 */ "VOpen",
22865     /* 136 */ "VFilter",
22866     /* 137 */ "VColumn",
22867     /* 138 */ "VNext",
22868     /* 139 */ "VRename",
22869     /* 140 */ "VUpdate",
22870     /* 141 */ "ToText",
22871     /* 142 */ "ToBlob",
22872     /* 143 */ "ToNumeric",
22873     /* 144 */ "ToInt",
22874     /* 145 */ "ToReal",
22875     /* 146 */ "Pagecount",
22876     /* 147 */ "MaxPgcnt",
22877     /* 148 */ "Trace",
22878     /* 149 */ "Noop",
22879     /* 150 */ "Explain",
22880  };
22881  return azName[i];
22882}
22883#endif
22884
22885/************** End of opcodes.c *********************************************/
22886/************** Begin file os_unix.c *****************************************/
22887/*
22888** 2004 May 22
22889**
22890** The author disclaims copyright to this source code.  In place of
22891** a legal notice, here is a blessing:
22892**
22893**    May you do good and not evil.
22894**    May you find forgiveness for yourself and forgive others.
22895**    May you share freely, never taking more than you give.
22896**
22897******************************************************************************
22898**
22899** This file contains the VFS implementation for unix-like operating systems
22900** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
22901**
22902** There are actually several different VFS implementations in this file.
22903** The differences are in the way that file locking is done.  The default
22904** implementation uses Posix Advisory Locks.  Alternative implementations
22905** use flock(), dot-files, various proprietary locking schemas, or simply
22906** skip locking all together.
22907**
22908** This source file is organized into divisions where the logic for various
22909** subfunctions is contained within the appropriate division.  PLEASE
22910** KEEP THE STRUCTURE OF THIS FILE INTACT.  New code should be placed
22911** in the correct division and should be clearly labeled.
22912**
22913** The layout of divisions is as follows:
22914**
22915**   *  General-purpose declarations and utility functions.
22916**   *  Unique file ID logic used by VxWorks.
22917**   *  Various locking primitive implementations (all except proxy locking):
22918**      + for Posix Advisory Locks
22919**      + for no-op locks
22920**      + for dot-file locks
22921**      + for flock() locking
22922**      + for named semaphore locks (VxWorks only)
22923**      + for AFP filesystem locks (MacOSX only)
22924**   *  sqlite3_file methods not associated with locking.
22925**   *  Definitions of sqlite3_io_methods objects for all locking
22926**      methods plus "finder" functions for each locking method.
22927**   *  sqlite3_vfs method implementations.
22928**   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)
22929**   *  Definitions of sqlite3_vfs objects for all locking methods
22930**      plus implementations of sqlite3_os_init() and sqlite3_os_end().
22931*/
22932#if SQLITE_OS_UNIX              /* This file is used on unix only */
22933
22934/* Use posix_fallocate() if it is available
22935*/
22936#if !defined(HAVE_POSIX_FALLOCATE) \
22937      && (_XOPEN_SOURCE >= 600 || _POSIX_C_SOURCE >= 200112L)
22938# define HAVE_POSIX_FALLOCATE 1
22939#endif
22940
22941/*
22942** There are various methods for file locking used for concurrency
22943** control:
22944**
22945**   1. POSIX locking (the default),
22946**   2. No locking,
22947**   3. Dot-file locking,
22948**   4. flock() locking,
22949**   5. AFP locking (OSX only),
22950**   6. Named POSIX semaphores (VXWorks only),
22951**   7. proxy locking. (OSX only)
22952**
22953** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
22954** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
22955** selection of the appropriate locking style based on the filesystem
22956** where the database is located.
22957*/
22958#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
22959#  if defined(__APPLE__)
22960#    define SQLITE_ENABLE_LOCKING_STYLE 1
22961#  else
22962#    define SQLITE_ENABLE_LOCKING_STYLE 0
22963#  endif
22964#endif
22965
22966/*
22967** Define the OS_VXWORKS pre-processor macro to 1 if building on
22968** vxworks, or 0 otherwise.
22969*/
22970#ifndef OS_VXWORKS
22971#  if defined(__RTP__) || defined(_WRS_KERNEL)
22972#    define OS_VXWORKS 1
22973#  else
22974#    define OS_VXWORKS 0
22975#  endif
22976#endif
22977
22978/*
22979** These #defines should enable >2GB file support on Posix if the
22980** underlying operating system supports it.  If the OS lacks
22981** large file support, these should be no-ops.
22982**
22983** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
22984** on the compiler command line.  This is necessary if you are compiling
22985** on a recent machine (ex: RedHat 7.2) but you want your code to work
22986** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
22987** without this option, LFS is enable.  But LFS does not exist in the kernel
22988** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
22989** portability you should omit LFS.
22990**
22991** The previous paragraph was written in 2005.  (This paragraph is written
22992** on 2008-11-28.) These days, all Linux kernels support large files, so
22993** you should probably leave LFS enabled.  But some embedded platforms might
22994** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
22995*/
22996#ifndef SQLITE_DISABLE_LFS
22997# define _LARGE_FILE       1
22998# ifndef _FILE_OFFSET_BITS
22999#   define _FILE_OFFSET_BITS 64
23000# endif
23001# define _LARGEFILE_SOURCE 1
23002#endif
23003
23004/*
23005** standard include files.
23006*/
23007#include <sys/types.h>
23008#include <sys/stat.h>
23009#include <fcntl.h>
23010#include <unistd.h>
23011/* #include <time.h> */
23012#include <sys/time.h>
23013#include <errno.h>
23014#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
23015#include <sys/mman.h>
23016#endif
23017
23018
23019#if SQLITE_ENABLE_LOCKING_STYLE
23020# include <sys/ioctl.h>
23021# if OS_VXWORKS
23022#  include <semaphore.h>
23023#  include <limits.h>
23024# else
23025#  include <sys/file.h>
23026#  include <sys/param.h>
23027# endif
23028#endif /* SQLITE_ENABLE_LOCKING_STYLE */
23029
23030#if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
23031# include <sys/mount.h>
23032#endif
23033
23034#ifdef HAVE_UTIME
23035# include <utime.h>
23036#endif
23037
23038/*
23039** Allowed values of unixFile.fsFlags
23040*/
23041#define SQLITE_FSFLAGS_IS_MSDOS     0x1
23042
23043/*
23044** If we are to be thread-safe, include the pthreads header and define
23045** the SQLITE_UNIX_THREADS macro.
23046*/
23047#if SQLITE_THREADSAFE
23048/* # include <pthread.h> */
23049# define SQLITE_UNIX_THREADS 1
23050#endif
23051
23052/*
23053** Default permissions when creating a new file
23054*/
23055#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
23056# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
23057#endif
23058
23059/*
23060** Default permissions when creating auto proxy dir
23061*/
23062#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
23063# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
23064#endif
23065
23066/*
23067** Maximum supported path-length.
23068*/
23069#define MAX_PATHNAME 512
23070
23071/*
23072** Only set the lastErrno if the error code is a real error and not
23073** a normal expected return code of SQLITE_BUSY or SQLITE_OK
23074*/
23075#define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
23076
23077/* Forward references */
23078typedef struct unixShm unixShm;               /* Connection shared memory */
23079typedef struct unixShmNode unixShmNode;       /* Shared memory instance */
23080typedef struct unixInodeInfo unixInodeInfo;   /* An i-node */
23081typedef struct UnixUnusedFd UnixUnusedFd;     /* An unused file descriptor */
23082
23083/*
23084** Sometimes, after a file handle is closed by SQLite, the file descriptor
23085** cannot be closed immediately. In these cases, instances of the following
23086** structure are used to store the file descriptor while waiting for an
23087** opportunity to either close or reuse it.
23088*/
23089struct UnixUnusedFd {
23090  int fd;                   /* File descriptor to close */
23091  int flags;                /* Flags this file descriptor was opened with */
23092  UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */
23093};
23094
23095/*
23096** The unixFile structure is subclass of sqlite3_file specific to the unix
23097** VFS implementations.
23098*/
23099typedef struct unixFile unixFile;
23100struct unixFile {
23101  sqlite3_io_methods const *pMethod;  /* Always the first entry */
23102  sqlite3_vfs *pVfs;                  /* The VFS that created this unixFile */
23103  unixInodeInfo *pInode;              /* Info about locks on this inode */
23104  int h;                              /* The file descriptor */
23105  unsigned char eFileLock;            /* The type of lock held on this fd */
23106  unsigned short int ctrlFlags;       /* Behavioral bits.  UNIXFILE_* flags */
23107  int lastErrno;                      /* The unix errno from last I/O error */
23108  void *lockingContext;               /* Locking style specific state */
23109  UnixUnusedFd *pUnused;              /* Pre-allocated UnixUnusedFd */
23110  const char *zPath;                  /* Name of the file */
23111  unixShm *pShm;                      /* Shared memory segment information */
23112  int szChunk;                        /* Configured by FCNTL_CHUNK_SIZE */
23113  int nFetchOut;                      /* Number of outstanding xFetch refs */
23114  sqlite3_int64 mmapSize;             /* Usable size of mapping at pMapRegion */
23115  sqlite3_int64 mmapSizeActual;       /* Actual size of mapping at pMapRegion */
23116  sqlite3_int64 mmapSizeMax;          /* Configured FCNTL_MMAP_SIZE value */
23117  void *pMapRegion;                   /* Memory mapped region */
23118#ifdef __QNXNTO__
23119  int sectorSize;                     /* Device sector size */
23120  int deviceCharacteristics;          /* Precomputed device characteristics */
23121#endif
23122#if SQLITE_ENABLE_LOCKING_STYLE
23123  int openFlags;                      /* The flags specified at open() */
23124#endif
23125#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
23126  unsigned fsFlags;                   /* cached details from statfs() */
23127#endif
23128#if OS_VXWORKS
23129  struct vxworksFileId *pId;          /* Unique file ID */
23130#endif
23131#ifdef SQLITE_DEBUG
23132  /* The next group of variables are used to track whether or not the
23133  ** transaction counter in bytes 24-27 of database files are updated
23134  ** whenever any part of the database changes.  An assertion fault will
23135  ** occur if a file is updated without also updating the transaction
23136  ** counter.  This test is made to avoid new problems similar to the
23137  ** one described by ticket #3584.
23138  */
23139  unsigned char transCntrChng;   /* True if the transaction counter changed */
23140  unsigned char dbUpdate;        /* True if any part of database file changed */
23141  unsigned char inNormalWrite;   /* True if in a normal write operation */
23142
23143#endif
23144
23145#ifdef SQLITE_TEST
23146  /* In test mode, increase the size of this structure a bit so that
23147  ** it is larger than the struct CrashFile defined in test6.c.
23148  */
23149  char aPadding[32];
23150#endif
23151};
23152
23153/*
23154** Allowed values for the unixFile.ctrlFlags bitmask:
23155*/
23156#define UNIXFILE_EXCL        0x01     /* Connections from one process only */
23157#define UNIXFILE_RDONLY      0x02     /* Connection is read only */
23158#define UNIXFILE_PERSIST_WAL 0x04     /* Persistent WAL mode */
23159#ifndef SQLITE_DISABLE_DIRSYNC
23160# define UNIXFILE_DIRSYNC    0x08     /* Directory sync needed */
23161#else
23162# define UNIXFILE_DIRSYNC    0x00
23163#endif
23164#define UNIXFILE_PSOW        0x10     /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
23165#define UNIXFILE_DELETE      0x20     /* Delete on close */
23166#define UNIXFILE_URI         0x40     /* Filename might have query parameters */
23167#define UNIXFILE_NOLOCK      0x80     /* Do no file locking */
23168#define UNIXFILE_WARNED    0x0100     /* verifyDbFile() warnings have been issued */
23169
23170/*
23171** Include code that is common to all os_*.c files
23172*/
23173/************** Include os_common.h in the middle of os_unix.c ***************/
23174/************** Begin file os_common.h ***************************************/
23175/*
23176** 2004 May 22
23177**
23178** The author disclaims copyright to this source code.  In place of
23179** a legal notice, here is a blessing:
23180**
23181**    May you do good and not evil.
23182**    May you find forgiveness for yourself and forgive others.
23183**    May you share freely, never taking more than you give.
23184**
23185******************************************************************************
23186**
23187** This file contains macros and a little bit of code that is common to
23188** all of the platform-specific files (os_*.c) and is #included into those
23189** files.
23190**
23191** This file should be #included by the os_*.c files only.  It is not a
23192** general purpose header file.
23193*/
23194#ifndef _OS_COMMON_H_
23195#define _OS_COMMON_H_
23196
23197/*
23198** At least two bugs have slipped in because we changed the MEMORY_DEBUG
23199** macro to SQLITE_DEBUG and some older makefiles have not yet made the
23200** switch.  The following code should catch this problem at compile-time.
23201*/
23202#ifdef MEMORY_DEBUG
23203# error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
23204#endif
23205
23206#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
23207# ifndef SQLITE_DEBUG_OS_TRACE
23208#   define SQLITE_DEBUG_OS_TRACE 0
23209# endif
23210  int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
23211# define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
23212#else
23213# define OSTRACE(X)
23214#endif
23215
23216/*
23217** Macros for performance tracing.  Normally turned off.  Only works
23218** on i486 hardware.
23219*/
23220#ifdef SQLITE_PERFORMANCE_TRACE
23221
23222/*
23223** hwtime.h contains inline assembler code for implementing
23224** high-performance timing routines.
23225*/
23226/************** Include hwtime.h in the middle of os_common.h ****************/
23227/************** Begin file hwtime.h ******************************************/
23228/*
23229** 2008 May 27
23230**
23231** The author disclaims copyright to this source code.  In place of
23232** a legal notice, here is a blessing:
23233**
23234**    May you do good and not evil.
23235**    May you find forgiveness for yourself and forgive others.
23236**    May you share freely, never taking more than you give.
23237**
23238******************************************************************************
23239**
23240** This file contains inline asm code for retrieving "high-performance"
23241** counters for x86 class CPUs.
23242*/
23243#ifndef _HWTIME_H_
23244#define _HWTIME_H_
23245
23246/*
23247** The following routine only works on pentium-class (or newer) processors.
23248** It uses the RDTSC opcode to read the cycle count value out of the
23249** processor and returns that value.  This can be used for high-res
23250** profiling.
23251*/
23252#if (defined(__GNUC__) || defined(_MSC_VER)) && \
23253      (defined(i386) || defined(__i386__) || defined(_M_IX86))
23254
23255  #if defined(__GNUC__)
23256
23257  __inline__ sqlite_uint64 sqlite3Hwtime(void){
23258     unsigned int lo, hi;
23259     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
23260     return (sqlite_uint64)hi << 32 | lo;
23261  }
23262
23263  #elif defined(_MSC_VER)
23264
23265  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
23266     __asm {
23267        rdtsc
23268        ret       ; return value at EDX:EAX
23269     }
23270  }
23271
23272  #endif
23273
23274#elif (defined(__GNUC__) && defined(__x86_64__))
23275
23276  __inline__ sqlite_uint64 sqlite3Hwtime(void){
23277      unsigned long val;
23278      __asm__ __volatile__ ("rdtsc" : "=A" (val));
23279      return val;
23280  }
23281
23282#elif (defined(__GNUC__) && defined(__ppc__))
23283
23284  __inline__ sqlite_uint64 sqlite3Hwtime(void){
23285      unsigned long long retval;
23286      unsigned long junk;
23287      __asm__ __volatile__ ("\n\
23288          1:      mftbu   %1\n\
23289                  mftb    %L0\n\
23290                  mftbu   %0\n\
23291                  cmpw    %0,%1\n\
23292                  bne     1b"
23293                  : "=r" (retval), "=r" (junk));
23294      return retval;
23295  }
23296
23297#else
23298
23299  #error Need implementation of sqlite3Hwtime() for your platform.
23300
23301  /*
23302  ** To compile without implementing sqlite3Hwtime() for your platform,
23303  ** you can remove the above #error and use the following
23304  ** stub function.  You will lose timing support for many
23305  ** of the debugging and testing utilities, but it should at
23306  ** least compile and run.
23307  */
23308SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
23309
23310#endif
23311
23312#endif /* !defined(_HWTIME_H_) */
23313
23314/************** End of hwtime.h **********************************************/
23315/************** Continuing where we left off in os_common.h ******************/
23316
23317static sqlite_uint64 g_start;
23318static sqlite_uint64 g_elapsed;
23319#define TIMER_START       g_start=sqlite3Hwtime()
23320#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
23321#define TIMER_ELAPSED     g_elapsed
23322#else
23323#define TIMER_START
23324#define TIMER_END
23325#define TIMER_ELAPSED     ((sqlite_uint64)0)
23326#endif
23327
23328/*
23329** If we compile with the SQLITE_TEST macro set, then the following block
23330** of code will give us the ability to simulate a disk I/O error.  This
23331** is used for testing the I/O recovery logic.
23332*/
23333#ifdef SQLITE_TEST
23334SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
23335SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
23336SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
23337SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
23338SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
23339SQLITE_API int sqlite3_diskfull_pending = 0;
23340SQLITE_API int sqlite3_diskfull = 0;
23341#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
23342#define SimulateIOError(CODE)  \
23343  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
23344       || sqlite3_io_error_pending-- == 1 )  \
23345              { local_ioerr(); CODE; }
23346static void local_ioerr(){
23347  IOTRACE(("IOERR\n"));
23348  sqlite3_io_error_hit++;
23349  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
23350}
23351#define SimulateDiskfullError(CODE) \
23352   if( sqlite3_diskfull_pending ){ \
23353     if( sqlite3_diskfull_pending == 1 ){ \
23354       local_ioerr(); \
23355       sqlite3_diskfull = 1; \
23356       sqlite3_io_error_hit = 1; \
23357       CODE; \
23358     }else{ \
23359       sqlite3_diskfull_pending--; \
23360     } \
23361   }
23362#else
23363#define SimulateIOErrorBenign(X)
23364#define SimulateIOError(A)
23365#define SimulateDiskfullError(A)
23366#endif
23367
23368/*
23369** When testing, keep a count of the number of open files.
23370*/
23371#ifdef SQLITE_TEST
23372SQLITE_API int sqlite3_open_file_count = 0;
23373#define OpenCounter(X)  sqlite3_open_file_count+=(X)
23374#else
23375#define OpenCounter(X)
23376#endif
23377
23378#endif /* !defined(_OS_COMMON_H_) */
23379
23380/************** End of os_common.h *******************************************/
23381/************** Continuing where we left off in os_unix.c ********************/
23382
23383/*
23384** Define various macros that are missing from some systems.
23385*/
23386#ifndef O_LARGEFILE
23387# define O_LARGEFILE 0
23388#endif
23389#ifdef SQLITE_DISABLE_LFS
23390# undef O_LARGEFILE
23391# define O_LARGEFILE 0
23392#endif
23393#ifndef O_NOFOLLOW
23394# define O_NOFOLLOW 0
23395#endif
23396#ifndef O_BINARY
23397# define O_BINARY 0
23398#endif
23399
23400/*
23401** The threadid macro resolves to the thread-id or to 0.  Used for
23402** testing and debugging only.
23403*/
23404#if SQLITE_THREADSAFE
23405#define threadid pthread_self()
23406#else
23407#define threadid 0
23408#endif
23409
23410/*
23411** HAVE_MREMAP defaults to true on Linux and false everywhere else.
23412*/
23413#if !defined(HAVE_MREMAP)
23414# if defined(__linux__) && defined(_GNU_SOURCE)
23415#  define HAVE_MREMAP 1
23416# else
23417#  define HAVE_MREMAP 0
23418# endif
23419#endif
23420
23421/*
23422** Different Unix systems declare open() in different ways.  Same use
23423** open(const char*,int,mode_t).  Others use open(const char*,int,...).
23424** The difference is important when using a pointer to the function.
23425**
23426** The safest way to deal with the problem is to always use this wrapper
23427** which always has the same well-defined interface.
23428*/
23429static int posixOpen(const char *zFile, int flags, int mode){
23430  return open(zFile, flags, mode);
23431}
23432
23433/*
23434** On some systems, calls to fchown() will trigger a message in a security
23435** log if they come from non-root processes.  So avoid calling fchown() if
23436** we are not running as root.
23437*/
23438static int posixFchown(int fd, uid_t uid, gid_t gid){
23439  return geteuid() ? 0 : fchown(fd,uid,gid);
23440}
23441
23442/* Forward reference */
23443static int openDirectory(const char*, int*);
23444
23445/*
23446** Many system calls are accessed through pointer-to-functions so that
23447** they may be overridden at runtime to facilitate fault injection during
23448** testing and sandboxing.  The following array holds the names and pointers
23449** to all overrideable system calls.
23450*/
23451static struct unix_syscall {
23452  const char *zName;            /* Name of the system call */
23453  sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
23454  sqlite3_syscall_ptr pDefault; /* Default value */
23455} aSyscall[] = {
23456  { "open",         (sqlite3_syscall_ptr)posixOpen,  0  },
23457#define osOpen      ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
23458
23459  { "close",        (sqlite3_syscall_ptr)close,      0  },
23460#define osClose     ((int(*)(int))aSyscall[1].pCurrent)
23461
23462  { "access",       (sqlite3_syscall_ptr)access,     0  },
23463#define osAccess    ((int(*)(const char*,int))aSyscall[2].pCurrent)
23464
23465  { "getcwd",       (sqlite3_syscall_ptr)getcwd,     0  },
23466#define osGetcwd    ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
23467
23468  { "stat",         (sqlite3_syscall_ptr)stat,       0  },
23469#define osStat      ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
23470
23471/*
23472** The DJGPP compiler environment looks mostly like Unix, but it
23473** lacks the fcntl() system call.  So redefine fcntl() to be something
23474** that always succeeds.  This means that locking does not occur under
23475** DJGPP.  But it is DOS - what did you expect?
23476*/
23477#ifdef __DJGPP__
23478  { "fstat",        0,                 0  },
23479#define osFstat(a,b,c)    0
23480#else
23481  { "fstat",        (sqlite3_syscall_ptr)fstat,      0  },
23482#define osFstat     ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
23483#endif
23484
23485  { "ftruncate",    (sqlite3_syscall_ptr)ftruncate,  0  },
23486#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
23487
23488  { "fcntl",        (sqlite3_syscall_ptr)fcntl,      0  },
23489#define osFcntl     ((int(*)(int,int,...))aSyscall[7].pCurrent)
23490
23491  { "read",         (sqlite3_syscall_ptr)read,       0  },
23492#define osRead      ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
23493
23494#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
23495  { "pread",        (sqlite3_syscall_ptr)pread,      0  },
23496#else
23497  { "pread",        (sqlite3_syscall_ptr)0,          0  },
23498#endif
23499#define osPread     ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
23500
23501#if defined(USE_PREAD64)
23502  { "pread64",      (sqlite3_syscall_ptr)pread64,    0  },
23503#else
23504  { "pread64",      (sqlite3_syscall_ptr)0,          0  },
23505#endif
23506#define osPread64   ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
23507
23508  { "write",        (sqlite3_syscall_ptr)write,      0  },
23509#define osWrite     ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
23510
23511#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
23512  { "pwrite",       (sqlite3_syscall_ptr)pwrite,     0  },
23513#else
23514  { "pwrite",       (sqlite3_syscall_ptr)0,          0  },
23515#endif
23516#define osPwrite    ((ssize_t(*)(int,const void*,size_t,off_t))\
23517                    aSyscall[12].pCurrent)
23518
23519#if defined(USE_PREAD64)
23520  { "pwrite64",     (sqlite3_syscall_ptr)pwrite64,   0  },
23521#else
23522  { "pwrite64",     (sqlite3_syscall_ptr)0,          0  },
23523#endif
23524#define osPwrite64  ((ssize_t(*)(int,const void*,size_t,off_t))\
23525                    aSyscall[13].pCurrent)
23526
23527  { "fchmod",       (sqlite3_syscall_ptr)fchmod,     0  },
23528#define osFchmod    ((int(*)(int,mode_t))aSyscall[14].pCurrent)
23529
23530#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
23531  { "fallocate",    (sqlite3_syscall_ptr)posix_fallocate,  0 },
23532#else
23533  { "fallocate",    (sqlite3_syscall_ptr)0,                0 },
23534#endif
23535#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
23536
23537  { "unlink",       (sqlite3_syscall_ptr)unlink,           0 },
23538#define osUnlink    ((int(*)(const char*))aSyscall[16].pCurrent)
23539
23540  { "openDirectory",    (sqlite3_syscall_ptr)openDirectory,      0 },
23541#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
23542
23543  { "mkdir",        (sqlite3_syscall_ptr)mkdir,           0 },
23544#define osMkdir     ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
23545
23546  { "rmdir",        (sqlite3_syscall_ptr)rmdir,           0 },
23547#define osRmdir     ((int(*)(const char*))aSyscall[19].pCurrent)
23548
23549  { "fchown",       (sqlite3_syscall_ptr)posixFchown,     0 },
23550#define osFchown    ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
23551
23552  { "mmap",       (sqlite3_syscall_ptr)mmap,     0 },
23553#define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[21].pCurrent)
23554
23555  { "munmap",       (sqlite3_syscall_ptr)munmap,          0 },
23556#define osMunmap ((void*(*)(void*,size_t))aSyscall[22].pCurrent)
23557
23558#if HAVE_MREMAP
23559  { "mremap",       (sqlite3_syscall_ptr)mremap,          0 },
23560#else
23561  { "mremap",       (sqlite3_syscall_ptr)0,               0 },
23562#endif
23563#define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[23].pCurrent)
23564
23565}; /* End of the overrideable system calls */
23566
23567/*
23568** This is the xSetSystemCall() method of sqlite3_vfs for all of the
23569** "unix" VFSes.  Return SQLITE_OK opon successfully updating the
23570** system call pointer, or SQLITE_NOTFOUND if there is no configurable
23571** system call named zName.
23572*/
23573static int unixSetSystemCall(
23574  sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
23575  const char *zName,            /* Name of system call to override */
23576  sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
23577){
23578  unsigned int i;
23579  int rc = SQLITE_NOTFOUND;
23580
23581  UNUSED_PARAMETER(pNotUsed);
23582  if( zName==0 ){
23583    /* If no zName is given, restore all system calls to their default
23584    ** settings and return NULL
23585    */
23586    rc = SQLITE_OK;
23587    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
23588      if( aSyscall[i].pDefault ){
23589        aSyscall[i].pCurrent = aSyscall[i].pDefault;
23590      }
23591    }
23592  }else{
23593    /* If zName is specified, operate on only the one system call
23594    ** specified.
23595    */
23596    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
23597      if( strcmp(zName, aSyscall[i].zName)==0 ){
23598        if( aSyscall[i].pDefault==0 ){
23599          aSyscall[i].pDefault = aSyscall[i].pCurrent;
23600        }
23601        rc = SQLITE_OK;
23602        if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
23603        aSyscall[i].pCurrent = pNewFunc;
23604        break;
23605      }
23606    }
23607  }
23608  return rc;
23609}
23610
23611/*
23612** Return the value of a system call.  Return NULL if zName is not a
23613** recognized system call name.  NULL is also returned if the system call
23614** is currently undefined.
23615*/
23616static sqlite3_syscall_ptr unixGetSystemCall(
23617  sqlite3_vfs *pNotUsed,
23618  const char *zName
23619){
23620  unsigned int i;
23621
23622  UNUSED_PARAMETER(pNotUsed);
23623  for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
23624    if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
23625  }
23626  return 0;
23627}
23628
23629/*
23630** Return the name of the first system call after zName.  If zName==NULL
23631** then return the name of the first system call.  Return NULL if zName
23632** is the last system call or if zName is not the name of a valid
23633** system call.
23634*/
23635static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
23636  int i = -1;
23637
23638  UNUSED_PARAMETER(p);
23639  if( zName ){
23640    for(i=0; i<ArraySize(aSyscall)-1; i++){
23641      if( strcmp(zName, aSyscall[i].zName)==0 ) break;
23642    }
23643  }
23644  for(i++; i<ArraySize(aSyscall); i++){
23645    if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
23646  }
23647  return 0;
23648}
23649
23650/*
23651** Invoke open().  Do so multiple times, until it either succeeds or
23652** fails for some reason other than EINTR.
23653**
23654** If the file creation mode "m" is 0 then set it to the default for
23655** SQLite.  The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
23656** 0644) as modified by the system umask.  If m is not 0, then
23657** make the file creation mode be exactly m ignoring the umask.
23658**
23659** The m parameter will be non-zero only when creating -wal, -journal,
23660** and -shm files.  We want those files to have *exactly* the same
23661** permissions as their original database, unadulterated by the umask.
23662** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
23663** transaction crashes and leaves behind hot journals, then any
23664** process that is able to write to the database will also be able to
23665** recover the hot journals.
23666*/
23667static int robust_open(const char *z, int f, mode_t m){
23668  int fd;
23669  mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
23670  do{
23671#if defined(O_CLOEXEC)
23672    fd = osOpen(z,f|O_CLOEXEC,m2);
23673#else
23674    fd = osOpen(z,f,m2);
23675#endif
23676  }while( fd<0 && errno==EINTR );
23677  if( fd>=0 ){
23678    if( m!=0 ){
23679      struct stat statbuf;
23680      if( osFstat(fd, &statbuf)==0
23681       && statbuf.st_size==0
23682       && (statbuf.st_mode&0777)!=m
23683      ){
23684        osFchmod(fd, m);
23685      }
23686    }
23687#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
23688    osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
23689#endif
23690  }
23691  return fd;
23692}
23693
23694/*
23695** Helper functions to obtain and relinquish the global mutex. The
23696** global mutex is used to protect the unixInodeInfo and
23697** vxworksFileId objects used by this file, all of which may be
23698** shared by multiple threads.
23699**
23700** Function unixMutexHeld() is used to assert() that the global mutex
23701** is held when required. This function is only used as part of assert()
23702** statements. e.g.
23703**
23704**   unixEnterMutex()
23705**     assert( unixMutexHeld() );
23706**   unixEnterLeave()
23707*/
23708static void unixEnterMutex(void){
23709  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
23710}
23711static void unixLeaveMutex(void){
23712  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
23713}
23714#ifdef SQLITE_DEBUG
23715static int unixMutexHeld(void) {
23716  return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
23717}
23718#endif
23719
23720
23721#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
23722/*
23723** Helper function for printing out trace information from debugging
23724** binaries. This returns the string represetation of the supplied
23725** integer lock-type.
23726*/
23727static const char *azFileLock(int eFileLock){
23728  switch( eFileLock ){
23729    case NO_LOCK: return "NONE";
23730    case SHARED_LOCK: return "SHARED";
23731    case RESERVED_LOCK: return "RESERVED";
23732    case PENDING_LOCK: return "PENDING";
23733    case EXCLUSIVE_LOCK: return "EXCLUSIVE";
23734  }
23735  return "ERROR";
23736}
23737#endif
23738
23739#ifdef SQLITE_LOCK_TRACE
23740/*
23741** Print out information about all locking operations.
23742**
23743** This routine is used for troubleshooting locks on multithreaded
23744** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
23745** command-line option on the compiler.  This code is normally
23746** turned off.
23747*/
23748static int lockTrace(int fd, int op, struct flock *p){
23749  char *zOpName, *zType;
23750  int s;
23751  int savedErrno;
23752  if( op==F_GETLK ){
23753    zOpName = "GETLK";
23754  }else if( op==F_SETLK ){
23755    zOpName = "SETLK";
23756  }else{
23757    s = osFcntl(fd, op, p);
23758    sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
23759    return s;
23760  }
23761  if( p->l_type==F_RDLCK ){
23762    zType = "RDLCK";
23763  }else if( p->l_type==F_WRLCK ){
23764    zType = "WRLCK";
23765  }else if( p->l_type==F_UNLCK ){
23766    zType = "UNLCK";
23767  }else{
23768    assert( 0 );
23769  }
23770  assert( p->l_whence==SEEK_SET );
23771  s = osFcntl(fd, op, p);
23772  savedErrno = errno;
23773  sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
23774     threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
23775     (int)p->l_pid, s);
23776  if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
23777    struct flock l2;
23778    l2 = *p;
23779    osFcntl(fd, F_GETLK, &l2);
23780    if( l2.l_type==F_RDLCK ){
23781      zType = "RDLCK";
23782    }else if( l2.l_type==F_WRLCK ){
23783      zType = "WRLCK";
23784    }else if( l2.l_type==F_UNLCK ){
23785      zType = "UNLCK";
23786    }else{
23787      assert( 0 );
23788    }
23789    sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
23790       zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
23791  }
23792  errno = savedErrno;
23793  return s;
23794}
23795#undef osFcntl
23796#define osFcntl lockTrace
23797#endif /* SQLITE_LOCK_TRACE */
23798
23799/*
23800** Retry ftruncate() calls that fail due to EINTR
23801*/
23802static int robust_ftruncate(int h, sqlite3_int64 sz){
23803  int rc;
23804  do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
23805  return rc;
23806}
23807
23808/*
23809** This routine translates a standard POSIX errno code into something
23810** useful to the clients of the sqlite3 functions.  Specifically, it is
23811** intended to translate a variety of "try again" errors into SQLITE_BUSY
23812** and a variety of "please close the file descriptor NOW" errors into
23813** SQLITE_IOERR
23814**
23815** Errors during initialization of locks, or file system support for locks,
23816** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
23817*/
23818static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
23819  switch (posixError) {
23820#if 0
23821  /* At one point this code was not commented out. In theory, this branch
23822  ** should never be hit, as this function should only be called after
23823  ** a locking-related function (i.e. fcntl()) has returned non-zero with
23824  ** the value of errno as the first argument. Since a system call has failed,
23825  ** errno should be non-zero.
23826  **
23827  ** Despite this, if errno really is zero, we still don't want to return
23828  ** SQLITE_OK. The system call failed, and *some* SQLite error should be
23829  ** propagated back to the caller. Commenting this branch out means errno==0
23830  ** will be handled by the "default:" case below.
23831  */
23832  case 0:
23833    return SQLITE_OK;
23834#endif
23835
23836  case EAGAIN:
23837  case ETIMEDOUT:
23838  case EBUSY:
23839  case EINTR:
23840  case ENOLCK:
23841    /* random NFS retry error, unless during file system support
23842     * introspection, in which it actually means what it says */
23843    return SQLITE_BUSY;
23844
23845  case EACCES:
23846    /* EACCES is like EAGAIN during locking operations, but not any other time*/
23847    if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
23848        (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
23849        (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
23850        (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
23851      return SQLITE_BUSY;
23852    }
23853    /* else fall through */
23854  case EPERM:
23855    return SQLITE_PERM;
23856
23857  /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
23858  ** this module never makes such a call. And the code in SQLite itself
23859  ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
23860  ** this case is also commented out. If the system does set errno to EDEADLK,
23861  ** the default SQLITE_IOERR_XXX code will be returned. */
23862#if 0
23863  case EDEADLK:
23864    return SQLITE_IOERR_BLOCKED;
23865#endif
23866
23867#if EOPNOTSUPP!=ENOTSUP
23868  case EOPNOTSUPP:
23869    /* something went terribly awry, unless during file system support
23870     * introspection, in which it actually means what it says */
23871#endif
23872#ifdef ENOTSUP
23873  case ENOTSUP:
23874    /* invalid fd, unless during file system support introspection, in which
23875     * it actually means what it says */
23876#endif
23877  case EIO:
23878  case EBADF:
23879  case EINVAL:
23880  case ENOTCONN:
23881  case ENODEV:
23882  case ENXIO:
23883  case ENOENT:
23884#ifdef ESTALE                     /* ESTALE is not defined on Interix systems */
23885  case ESTALE:
23886#endif
23887  case ENOSYS:
23888    /* these should force the client to close the file and reconnect */
23889
23890  default:
23891    return sqliteIOErr;
23892  }
23893}
23894
23895
23896/******************************************************************************
23897****************** Begin Unique File ID Utility Used By VxWorks ***************
23898**
23899** On most versions of unix, we can get a unique ID for a file by concatenating
23900** the device number and the inode number.  But this does not work on VxWorks.
23901** On VxWorks, a unique file id must be based on the canonical filename.
23902**
23903** A pointer to an instance of the following structure can be used as a
23904** unique file ID in VxWorks.  Each instance of this structure contains
23905** a copy of the canonical filename.  There is also a reference count.
23906** The structure is reclaimed when the number of pointers to it drops to
23907** zero.
23908**
23909** There are never very many files open at one time and lookups are not
23910** a performance-critical path, so it is sufficient to put these
23911** structures on a linked list.
23912*/
23913struct vxworksFileId {
23914  struct vxworksFileId *pNext;  /* Next in a list of them all */
23915  int nRef;                     /* Number of references to this one */
23916  int nName;                    /* Length of the zCanonicalName[] string */
23917  char *zCanonicalName;         /* Canonical filename */
23918};
23919
23920#if OS_VXWORKS
23921/*
23922** All unique filenames are held on a linked list headed by this
23923** variable:
23924*/
23925static struct vxworksFileId *vxworksFileList = 0;
23926
23927/*
23928** Simplify a filename into its canonical form
23929** by making the following changes:
23930**
23931**  * removing any trailing and duplicate /
23932**  * convert /./ into just /
23933**  * convert /A/../ where A is any simple name into just /
23934**
23935** Changes are made in-place.  Return the new name length.
23936**
23937** The original filename is in z[0..n-1].  Return the number of
23938** characters in the simplified name.
23939*/
23940static int vxworksSimplifyName(char *z, int n){
23941  int i, j;
23942  while( n>1 && z[n-1]=='/' ){ n--; }
23943  for(i=j=0; i<n; i++){
23944    if( z[i]=='/' ){
23945      if( z[i+1]=='/' ) continue;
23946      if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
23947        i += 1;
23948        continue;
23949      }
23950      if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
23951        while( j>0 && z[j-1]!='/' ){ j--; }
23952        if( j>0 ){ j--; }
23953        i += 2;
23954        continue;
23955      }
23956    }
23957    z[j++] = z[i];
23958  }
23959  z[j] = 0;
23960  return j;
23961}
23962
23963/*
23964** Find a unique file ID for the given absolute pathname.  Return
23965** a pointer to the vxworksFileId object.  This pointer is the unique
23966** file ID.
23967**
23968** The nRef field of the vxworksFileId object is incremented before
23969** the object is returned.  A new vxworksFileId object is created
23970** and added to the global list if necessary.
23971**
23972** If a memory allocation error occurs, return NULL.
23973*/
23974static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
23975  struct vxworksFileId *pNew;         /* search key and new file ID */
23976  struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
23977  int n;                              /* Length of zAbsoluteName string */
23978
23979  assert( zAbsoluteName[0]=='/' );
23980  n = (int)strlen(zAbsoluteName);
23981  pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
23982  if( pNew==0 ) return 0;
23983  pNew->zCanonicalName = (char*)&pNew[1];
23984  memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
23985  n = vxworksSimplifyName(pNew->zCanonicalName, n);
23986
23987  /* Search for an existing entry that matching the canonical name.
23988  ** If found, increment the reference count and return a pointer to
23989  ** the existing file ID.
23990  */
23991  unixEnterMutex();
23992  for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
23993    if( pCandidate->nName==n
23994     && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
23995    ){
23996       sqlite3_free(pNew);
23997       pCandidate->nRef++;
23998       unixLeaveMutex();
23999       return pCandidate;
24000    }
24001  }
24002
24003  /* No match was found.  We will make a new file ID */
24004  pNew->nRef = 1;
24005  pNew->nName = n;
24006  pNew->pNext = vxworksFileList;
24007  vxworksFileList = pNew;
24008  unixLeaveMutex();
24009  return pNew;
24010}
24011
24012/*
24013** Decrement the reference count on a vxworksFileId object.  Free
24014** the object when the reference count reaches zero.
24015*/
24016static void vxworksReleaseFileId(struct vxworksFileId *pId){
24017  unixEnterMutex();
24018  assert( pId->nRef>0 );
24019  pId->nRef--;
24020  if( pId->nRef==0 ){
24021    struct vxworksFileId **pp;
24022    for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
24023    assert( *pp==pId );
24024    *pp = pId->pNext;
24025    sqlite3_free(pId);
24026  }
24027  unixLeaveMutex();
24028}
24029#endif /* OS_VXWORKS */
24030/*************** End of Unique File ID Utility Used By VxWorks ****************
24031******************************************************************************/
24032
24033
24034/******************************************************************************
24035*************************** Posix Advisory Locking ****************************
24036**
24037** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
24038** section 6.5.2.2 lines 483 through 490 specify that when a process
24039** sets or clears a lock, that operation overrides any prior locks set
24040** by the same process.  It does not explicitly say so, but this implies
24041** that it overrides locks set by the same process using a different
24042** file descriptor.  Consider this test case:
24043**
24044**       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
24045**       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
24046**
24047** Suppose ./file1 and ./file2 are really the same file (because
24048** one is a hard or symbolic link to the other) then if you set
24049** an exclusive lock on fd1, then try to get an exclusive lock
24050** on fd2, it works.  I would have expected the second lock to
24051** fail since there was already a lock on the file due to fd1.
24052** But not so.  Since both locks came from the same process, the
24053** second overrides the first, even though they were on different
24054** file descriptors opened on different file names.
24055**
24056** This means that we cannot use POSIX locks to synchronize file access
24057** among competing threads of the same process.  POSIX locks will work fine
24058** to synchronize access for threads in separate processes, but not
24059** threads within the same process.
24060**
24061** To work around the problem, SQLite has to manage file locks internally
24062** on its own.  Whenever a new database is opened, we have to find the
24063** specific inode of the database file (the inode is determined by the
24064** st_dev and st_ino fields of the stat structure that fstat() fills in)
24065** and check for locks already existing on that inode.  When locks are
24066** created or removed, we have to look at our own internal record of the
24067** locks to see if another thread has previously set a lock on that same
24068** inode.
24069**
24070** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
24071** For VxWorks, we have to use the alternative unique ID system based on
24072** canonical filename and implemented in the previous division.)
24073**
24074** The sqlite3_file structure for POSIX is no longer just an integer file
24075** descriptor.  It is now a structure that holds the integer file
24076** descriptor and a pointer to a structure that describes the internal
24077** locks on the corresponding inode.  There is one locking structure
24078** per inode, so if the same inode is opened twice, both unixFile structures
24079** point to the same locking structure.  The locking structure keeps
24080** a reference count (so we will know when to delete it) and a "cnt"
24081** field that tells us its internal lock status.  cnt==0 means the
24082** file is unlocked.  cnt==-1 means the file has an exclusive lock.
24083** cnt>0 means there are cnt shared locks on the file.
24084**
24085** Any attempt to lock or unlock a file first checks the locking
24086** structure.  The fcntl() system call is only invoked to set a
24087** POSIX lock if the internal lock structure transitions between
24088** a locked and an unlocked state.
24089**
24090** But wait:  there are yet more problems with POSIX advisory locks.
24091**
24092** If you close a file descriptor that points to a file that has locks,
24093** all locks on that file that are owned by the current process are
24094** released.  To work around this problem, each unixInodeInfo object
24095** maintains a count of the number of pending locks on tha inode.
24096** When an attempt is made to close an unixFile, if there are
24097** other unixFile open on the same inode that are holding locks, the call
24098** to close() the file descriptor is deferred until all of the locks clear.
24099** The unixInodeInfo structure keeps a list of file descriptors that need to
24100** be closed and that list is walked (and cleared) when the last lock
24101** clears.
24102**
24103** Yet another problem:  LinuxThreads do not play well with posix locks.
24104**
24105** Many older versions of linux use the LinuxThreads library which is
24106** not posix compliant.  Under LinuxThreads, a lock created by thread
24107** A cannot be modified or overridden by a different thread B.
24108** Only thread A can modify the lock.  Locking behavior is correct
24109** if the appliation uses the newer Native Posix Thread Library (NPTL)
24110** on linux - with NPTL a lock created by thread A can override locks
24111** in thread B.  But there is no way to know at compile-time which
24112** threading library is being used.  So there is no way to know at
24113** compile-time whether or not thread A can override locks on thread B.
24114** One has to do a run-time check to discover the behavior of the
24115** current process.
24116**
24117** SQLite used to support LinuxThreads.  But support for LinuxThreads
24118** was dropped beginning with version 3.7.0.  SQLite will still work with
24119** LinuxThreads provided that (1) there is no more than one connection
24120** per database file in the same process and (2) database connections
24121** do not move across threads.
24122*/
24123
24124/*
24125** An instance of the following structure serves as the key used
24126** to locate a particular unixInodeInfo object.
24127*/
24128struct unixFileId {
24129  dev_t dev;                  /* Device number */
24130#if OS_VXWORKS
24131  struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
24132#else
24133  ino_t ino;                  /* Inode number */
24134#endif
24135};
24136
24137/*
24138** An instance of the following structure is allocated for each open
24139** inode.  Or, on LinuxThreads, there is one of these structures for
24140** each inode opened by each thread.
24141**
24142** A single inode can have multiple file descriptors, so each unixFile
24143** structure contains a pointer to an instance of this object and this
24144** object keeps a count of the number of unixFile pointing to it.
24145*/
24146struct unixInodeInfo {
24147  struct unixFileId fileId;       /* The lookup key */
24148  int nShared;                    /* Number of SHARED locks held */
24149  unsigned char eFileLock;        /* One of SHARED_LOCK, RESERVED_LOCK etc. */
24150  unsigned char bProcessLock;     /* An exclusive process lock is held */
24151  int nRef;                       /* Number of pointers to this structure */
24152  unixShmNode *pShmNode;          /* Shared memory associated with this inode */
24153  int nLock;                      /* Number of outstanding file locks */
24154  UnixUnusedFd *pUnused;          /* Unused file descriptors to close */
24155  unixInodeInfo *pNext;           /* List of all unixInodeInfo objects */
24156  unixInodeInfo *pPrev;           /*    .... doubly linked */
24157#if SQLITE_ENABLE_LOCKING_STYLE
24158  unsigned long long sharedByte;  /* for AFP simulated shared lock */
24159#endif
24160#if OS_VXWORKS
24161  sem_t *pSem;                    /* Named POSIX semaphore */
24162  char aSemName[MAX_PATHNAME+2];  /* Name of that semaphore */
24163#endif
24164};
24165
24166/*
24167** A lists of all unixInodeInfo objects.
24168*/
24169static unixInodeInfo *inodeList = 0;
24170
24171/*
24172**
24173** This function - unixLogError_x(), is only ever called via the macro
24174** unixLogError().
24175**
24176** It is invoked after an error occurs in an OS function and errno has been
24177** set. It logs a message using sqlite3_log() containing the current value of
24178** errno and, if possible, the human-readable equivalent from strerror() or
24179** strerror_r().
24180**
24181** The first argument passed to the macro should be the error code that
24182** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
24183** The two subsequent arguments should be the name of the OS function that
24184** failed (e.g. "unlink", "open") and the associated file-system path,
24185** if any.
24186*/
24187#define unixLogError(a,b,c)     unixLogErrorAtLine(a,b,c,__LINE__)
24188static int unixLogErrorAtLine(
24189  int errcode,                    /* SQLite error code */
24190  const char *zFunc,              /* Name of OS function that failed */
24191  const char *zPath,              /* File path associated with error */
24192  int iLine                       /* Source line number where error occurred */
24193){
24194  char *zErr;                     /* Message from strerror() or equivalent */
24195  int iErrno = errno;             /* Saved syscall error number */
24196
24197  /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
24198  ** the strerror() function to obtain the human-readable error message
24199  ** equivalent to errno. Otherwise, use strerror_r().
24200  */
24201#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
24202  char aErr[80];
24203  memset(aErr, 0, sizeof(aErr));
24204  zErr = aErr;
24205
24206  /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
24207  ** assume that the system provides the GNU version of strerror_r() that
24208  ** returns a pointer to a buffer containing the error message. That pointer
24209  ** may point to aErr[], or it may point to some static storage somewhere.
24210  ** Otherwise, assume that the system provides the POSIX version of
24211  ** strerror_r(), which always writes an error message into aErr[].
24212  **
24213  ** If the code incorrectly assumes that it is the POSIX version that is
24214  ** available, the error message will often be an empty string. Not a
24215  ** huge problem. Incorrectly concluding that the GNU version is available
24216  ** could lead to a segfault though.
24217  */
24218#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
24219  zErr =
24220# endif
24221  strerror_r(iErrno, aErr, sizeof(aErr)-1);
24222
24223#elif SQLITE_THREADSAFE
24224  /* This is a threadsafe build, but strerror_r() is not available. */
24225  zErr = "";
24226#else
24227  /* Non-threadsafe build, use strerror(). */
24228  zErr = strerror(iErrno);
24229#endif
24230
24231  if( zPath==0 ) zPath = "";
24232  sqlite3_log(errcode,
24233      "os_unix.c:%d: (%d) %s(%s) - %s",
24234      iLine, iErrno, zFunc, zPath, zErr
24235  );
24236
24237  return errcode;
24238}
24239
24240/*
24241** Close a file descriptor.
24242**
24243** We assume that close() almost always works, since it is only in a
24244** very sick application or on a very sick platform that it might fail.
24245** If it does fail, simply leak the file descriptor, but do log the
24246** error.
24247**
24248** Note that it is not safe to retry close() after EINTR since the
24249** file descriptor might have already been reused by another thread.
24250** So we don't even try to recover from an EINTR.  Just log the error
24251** and move on.
24252*/
24253static void robust_close(unixFile *pFile, int h, int lineno){
24254  if( osClose(h) ){
24255    unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
24256                       pFile ? pFile->zPath : 0, lineno);
24257  }
24258}
24259
24260/*
24261** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
24262*/
24263static void closePendingFds(unixFile *pFile){
24264  unixInodeInfo *pInode = pFile->pInode;
24265  UnixUnusedFd *p;
24266  UnixUnusedFd *pNext;
24267  for(p=pInode->pUnused; p; p=pNext){
24268    pNext = p->pNext;
24269    robust_close(pFile, p->fd, __LINE__);
24270    sqlite3_free(p);
24271  }
24272  pInode->pUnused = 0;
24273}
24274
24275/*
24276** Release a unixInodeInfo structure previously allocated by findInodeInfo().
24277**
24278** The mutex entered using the unixEnterMutex() function must be held
24279** when this function is called.
24280*/
24281static void releaseInodeInfo(unixFile *pFile){
24282  unixInodeInfo *pInode = pFile->pInode;
24283  assert( unixMutexHeld() );
24284  if( ALWAYS(pInode) ){
24285    pInode->nRef--;
24286    if( pInode->nRef==0 ){
24287      assert( pInode->pShmNode==0 );
24288      closePendingFds(pFile);
24289      if( pInode->pPrev ){
24290        assert( pInode->pPrev->pNext==pInode );
24291        pInode->pPrev->pNext = pInode->pNext;
24292      }else{
24293        assert( inodeList==pInode );
24294        inodeList = pInode->pNext;
24295      }
24296      if( pInode->pNext ){
24297        assert( pInode->pNext->pPrev==pInode );
24298        pInode->pNext->pPrev = pInode->pPrev;
24299      }
24300      sqlite3_free(pInode);
24301    }
24302  }
24303}
24304
24305/*
24306** Given a file descriptor, locate the unixInodeInfo object that
24307** describes that file descriptor.  Create a new one if necessary.  The
24308** return value might be uninitialized if an error occurs.
24309**
24310** The mutex entered using the unixEnterMutex() function must be held
24311** when this function is called.
24312**
24313** Return an appropriate error code.
24314*/
24315static int findInodeInfo(
24316  unixFile *pFile,               /* Unix file with file desc used in the key */
24317  unixInodeInfo **ppInode        /* Return the unixInodeInfo object here */
24318){
24319  int rc;                        /* System call return code */
24320  int fd;                        /* The file descriptor for pFile */
24321  struct unixFileId fileId;      /* Lookup key for the unixInodeInfo */
24322  struct stat statbuf;           /* Low-level file information */
24323  unixInodeInfo *pInode = 0;     /* Candidate unixInodeInfo object */
24324
24325  assert( unixMutexHeld() );
24326
24327  /* Get low-level information about the file that we can used to
24328  ** create a unique name for the file.
24329  */
24330  fd = pFile->h;
24331  rc = osFstat(fd, &statbuf);
24332  if( rc!=0 ){
24333    pFile->lastErrno = errno;
24334#ifdef EOVERFLOW
24335    if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
24336#endif
24337    return SQLITE_IOERR;
24338  }
24339
24340#ifdef __APPLE__
24341  /* On OS X on an msdos filesystem, the inode number is reported
24342  ** incorrectly for zero-size files.  See ticket #3260.  To work
24343  ** around this problem (we consider it a bug in OS X, not SQLite)
24344  ** we always increase the file size to 1 by writing a single byte
24345  ** prior to accessing the inode number.  The one byte written is
24346  ** an ASCII 'S' character which also happens to be the first byte
24347  ** in the header of every SQLite database.  In this way, if there
24348  ** is a race condition such that another thread has already populated
24349  ** the first page of the database, no damage is done.
24350  */
24351  if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
24352    do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
24353    if( rc!=1 ){
24354      pFile->lastErrno = errno;
24355      return SQLITE_IOERR;
24356    }
24357    rc = osFstat(fd, &statbuf);
24358    if( rc!=0 ){
24359      pFile->lastErrno = errno;
24360      return SQLITE_IOERR;
24361    }
24362  }
24363#endif
24364
24365  memset(&fileId, 0, sizeof(fileId));
24366  fileId.dev = statbuf.st_dev;
24367#if OS_VXWORKS
24368  fileId.pId = pFile->pId;
24369#else
24370  fileId.ino = statbuf.st_ino;
24371#endif
24372  pInode = inodeList;
24373  while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
24374    pInode = pInode->pNext;
24375  }
24376  if( pInode==0 ){
24377    pInode = sqlite3_malloc( sizeof(*pInode) );
24378    if( pInode==0 ){
24379      return SQLITE_NOMEM;
24380    }
24381    memset(pInode, 0, sizeof(*pInode));
24382    memcpy(&pInode->fileId, &fileId, sizeof(fileId));
24383    pInode->nRef = 1;
24384    pInode->pNext = inodeList;
24385    pInode->pPrev = 0;
24386    if( inodeList ) inodeList->pPrev = pInode;
24387    inodeList = pInode;
24388  }else{
24389    pInode->nRef++;
24390  }
24391  *ppInode = pInode;
24392  return SQLITE_OK;
24393}
24394
24395
24396/*
24397** Check a unixFile that is a database.  Verify the following:
24398**
24399** (1) There is exactly one hard link on the file
24400** (2) The file is not a symbolic link
24401** (3) The file has not been renamed or unlinked
24402**
24403** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
24404*/
24405static void verifyDbFile(unixFile *pFile){
24406  struct stat buf;
24407  int rc;
24408  if( pFile->ctrlFlags & UNIXFILE_WARNED ){
24409    /* One or more of the following warnings have already been issued.  Do not
24410    ** repeat them so as not to clutter the error log */
24411    return;
24412  }
24413  rc = osFstat(pFile->h, &buf);
24414  if( rc!=0 ){
24415    sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
24416    pFile->ctrlFlags |= UNIXFILE_WARNED;
24417    return;
24418  }
24419  if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
24420    sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
24421    pFile->ctrlFlags |= UNIXFILE_WARNED;
24422    return;
24423  }
24424  if( buf.st_nlink>1 ){
24425    sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
24426    pFile->ctrlFlags |= UNIXFILE_WARNED;
24427    return;
24428  }
24429  if( pFile->pInode!=0
24430   && ((rc = osStat(pFile->zPath, &buf))!=0
24431       || buf.st_ino!=pFile->pInode->fileId.ino)
24432  ){
24433    sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
24434    pFile->ctrlFlags |= UNIXFILE_WARNED;
24435    return;
24436  }
24437}
24438
24439
24440/*
24441** This routine checks if there is a RESERVED lock held on the specified
24442** file by this or any other process. If such a lock is held, set *pResOut
24443** to a non-zero value otherwise *pResOut is set to zero.  The return value
24444** is set to SQLITE_OK unless an I/O error occurs during lock checking.
24445*/
24446static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
24447  int rc = SQLITE_OK;
24448  int reserved = 0;
24449  unixFile *pFile = (unixFile*)id;
24450
24451  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
24452
24453  assert( pFile );
24454  unixEnterMutex(); /* Because pFile->pInode is shared across threads */
24455
24456  /* Check if a thread in this process holds such a lock */
24457  if( pFile->pInode->eFileLock>SHARED_LOCK ){
24458    reserved = 1;
24459  }
24460
24461  /* Otherwise see if some other process holds it.
24462  */
24463#ifndef __DJGPP__
24464  if( !reserved && !pFile->pInode->bProcessLock ){
24465    struct flock lock;
24466    lock.l_whence = SEEK_SET;
24467    lock.l_start = RESERVED_BYTE;
24468    lock.l_len = 1;
24469    lock.l_type = F_WRLCK;
24470    if( osFcntl(pFile->h, F_GETLK, &lock) ){
24471      rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
24472      pFile->lastErrno = errno;
24473    } else if( lock.l_type!=F_UNLCK ){
24474      reserved = 1;
24475    }
24476  }
24477#endif
24478
24479  unixLeaveMutex();
24480  OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
24481
24482  *pResOut = reserved;
24483  return rc;
24484}
24485
24486/*
24487** Attempt to set a system-lock on the file pFile.  The lock is
24488** described by pLock.
24489**
24490** If the pFile was opened read/write from unix-excl, then the only lock
24491** ever obtained is an exclusive lock, and it is obtained exactly once
24492** the first time any lock is attempted.  All subsequent system locking
24493** operations become no-ops.  Locking operations still happen internally,
24494** in order to coordinate access between separate database connections
24495** within this process, but all of that is handled in memory and the
24496** operating system does not participate.
24497**
24498** This function is a pass-through to fcntl(F_SETLK) if pFile is using
24499** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
24500** and is read-only.
24501**
24502** Zero is returned if the call completes successfully, or -1 if a call
24503** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
24504*/
24505static int unixFileLock(unixFile *pFile, struct flock *pLock){
24506  int rc;
24507  unixInodeInfo *pInode = pFile->pInode;
24508  assert( unixMutexHeld() );
24509  assert( pInode!=0 );
24510  if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
24511   && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
24512  ){
24513    if( pInode->bProcessLock==0 ){
24514      struct flock lock;
24515      assert( pInode->nLock==0 );
24516      lock.l_whence = SEEK_SET;
24517      lock.l_start = SHARED_FIRST;
24518      lock.l_len = SHARED_SIZE;
24519      lock.l_type = F_WRLCK;
24520      rc = osFcntl(pFile->h, F_SETLK, &lock);
24521      if( rc<0 ) return rc;
24522      pInode->bProcessLock = 1;
24523      pInode->nLock++;
24524    }else{
24525      rc = 0;
24526    }
24527  }else{
24528    rc = osFcntl(pFile->h, F_SETLK, pLock);
24529  }
24530  return rc;
24531}
24532
24533/*
24534** Lock the file with the lock specified by parameter eFileLock - one
24535** of the following:
24536**
24537**     (1) SHARED_LOCK
24538**     (2) RESERVED_LOCK
24539**     (3) PENDING_LOCK
24540**     (4) EXCLUSIVE_LOCK
24541**
24542** Sometimes when requesting one lock state, additional lock states
24543** are inserted in between.  The locking might fail on one of the later
24544** transitions leaving the lock state different from what it started but
24545** still short of its goal.  The following chart shows the allowed
24546** transitions and the inserted intermediate states:
24547**
24548**    UNLOCKED -> SHARED
24549**    SHARED -> RESERVED
24550**    SHARED -> (PENDING) -> EXCLUSIVE
24551**    RESERVED -> (PENDING) -> EXCLUSIVE
24552**    PENDING -> EXCLUSIVE
24553**
24554** This routine will only increase a lock.  Use the sqlite3OsUnlock()
24555** routine to lower a locking level.
24556*/
24557static int unixLock(sqlite3_file *id, int eFileLock){
24558  /* The following describes the implementation of the various locks and
24559  ** lock transitions in terms of the POSIX advisory shared and exclusive
24560  ** lock primitives (called read-locks and write-locks below, to avoid
24561  ** confusion with SQLite lock names). The algorithms are complicated
24562  ** slightly in order to be compatible with windows systems simultaneously
24563  ** accessing the same database file, in case that is ever required.
24564  **
24565  ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
24566  ** byte', each single bytes at well known offsets, and the 'shared byte
24567  ** range', a range of 510 bytes at a well known offset.
24568  **
24569  ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
24570  ** byte'.  If this is successful, a random byte from the 'shared byte
24571  ** range' is read-locked and the lock on the 'pending byte' released.
24572  **
24573  ** A process may only obtain a RESERVED lock after it has a SHARED lock.
24574  ** A RESERVED lock is implemented by grabbing a write-lock on the
24575  ** 'reserved byte'.
24576  **
24577  ** A process may only obtain a PENDING lock after it has obtained a
24578  ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
24579  ** on the 'pending byte'. This ensures that no new SHARED locks can be
24580  ** obtained, but existing SHARED locks are allowed to persist. A process
24581  ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
24582  ** This property is used by the algorithm for rolling back a journal file
24583  ** after a crash.
24584  **
24585  ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
24586  ** implemented by obtaining a write-lock on the entire 'shared byte
24587  ** range'. Since all other locks require a read-lock on one of the bytes
24588  ** within this range, this ensures that no other locks are held on the
24589  ** database.
24590  **
24591  ** The reason a single byte cannot be used instead of the 'shared byte
24592  ** range' is that some versions of windows do not support read-locks. By
24593  ** locking a random byte from a range, concurrent SHARED locks may exist
24594  ** even if the locking primitive used is always a write-lock.
24595  */
24596  int rc = SQLITE_OK;
24597  unixFile *pFile = (unixFile*)id;
24598  unixInodeInfo *pInode;
24599  struct flock lock;
24600  int tErrno = 0;
24601
24602  assert( pFile );
24603  OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
24604      azFileLock(eFileLock), azFileLock(pFile->eFileLock),
24605      azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
24606
24607  /* If there is already a lock of this type or more restrictive on the
24608  ** unixFile, do nothing. Don't use the end_lock: exit path, as
24609  ** unixEnterMutex() hasn't been called yet.
24610  */
24611  if( pFile->eFileLock>=eFileLock ){
24612    OSTRACE(("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
24613            azFileLock(eFileLock)));
24614    return SQLITE_OK;
24615  }
24616
24617  /* Make sure the locking sequence is correct.
24618  **  (1) We never move from unlocked to anything higher than shared lock.
24619  **  (2) SQLite never explicitly requests a pendig lock.
24620  **  (3) A shared lock is always held when a reserve lock is requested.
24621  */
24622  assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
24623  assert( eFileLock!=PENDING_LOCK );
24624  assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
24625
24626  /* This mutex is needed because pFile->pInode is shared across threads
24627  */
24628  unixEnterMutex();
24629  pInode = pFile->pInode;
24630
24631  /* If some thread using this PID has a lock via a different unixFile*
24632  ** handle that precludes the requested lock, return BUSY.
24633  */
24634  if( (pFile->eFileLock!=pInode->eFileLock &&
24635          (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
24636  ){
24637    rc = SQLITE_BUSY;
24638    goto end_lock;
24639  }
24640
24641  /* If a SHARED lock is requested, and some thread using this PID already
24642  ** has a SHARED or RESERVED lock, then increment reference counts and
24643  ** return SQLITE_OK.
24644  */
24645  if( eFileLock==SHARED_LOCK &&
24646      (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
24647    assert( eFileLock==SHARED_LOCK );
24648    assert( pFile->eFileLock==0 );
24649    assert( pInode->nShared>0 );
24650    pFile->eFileLock = SHARED_LOCK;
24651    pInode->nShared++;
24652    pInode->nLock++;
24653    goto end_lock;
24654  }
24655
24656
24657  /* A PENDING lock is needed before acquiring a SHARED lock and before
24658  ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
24659  ** be released.
24660  */
24661  lock.l_len = 1L;
24662  lock.l_whence = SEEK_SET;
24663  if( eFileLock==SHARED_LOCK
24664      || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
24665  ){
24666    lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
24667    lock.l_start = PENDING_BYTE;
24668    if( unixFileLock(pFile, &lock) ){
24669      tErrno = errno;
24670      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
24671      if( rc!=SQLITE_BUSY ){
24672        pFile->lastErrno = tErrno;
24673      }
24674      goto end_lock;
24675    }
24676  }
24677
24678
24679  /* If control gets to this point, then actually go ahead and make
24680  ** operating system calls for the specified lock.
24681  */
24682  if( eFileLock==SHARED_LOCK ){
24683    assert( pInode->nShared==0 );
24684    assert( pInode->eFileLock==0 );
24685    assert( rc==SQLITE_OK );
24686
24687    /* Now get the read-lock */
24688    lock.l_start = SHARED_FIRST;
24689    lock.l_len = SHARED_SIZE;
24690    if( unixFileLock(pFile, &lock) ){
24691      tErrno = errno;
24692      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
24693    }
24694
24695    /* Drop the temporary PENDING lock */
24696    lock.l_start = PENDING_BYTE;
24697    lock.l_len = 1L;
24698    lock.l_type = F_UNLCK;
24699    if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
24700      /* This could happen with a network mount */
24701      tErrno = errno;
24702      rc = SQLITE_IOERR_UNLOCK;
24703    }
24704
24705    if( rc ){
24706      if( rc!=SQLITE_BUSY ){
24707        pFile->lastErrno = tErrno;
24708      }
24709      goto end_lock;
24710    }else{
24711      pFile->eFileLock = SHARED_LOCK;
24712      pInode->nLock++;
24713      pInode->nShared = 1;
24714    }
24715  }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
24716    /* We are trying for an exclusive lock but another thread in this
24717    ** same process is still holding a shared lock. */
24718    rc = SQLITE_BUSY;
24719  }else{
24720    /* The request was for a RESERVED or EXCLUSIVE lock.  It is
24721    ** assumed that there is a SHARED or greater lock on the file
24722    ** already.
24723    */
24724    assert( 0!=pFile->eFileLock );
24725    lock.l_type = F_WRLCK;
24726
24727    assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
24728    if( eFileLock==RESERVED_LOCK ){
24729      lock.l_start = RESERVED_BYTE;
24730      lock.l_len = 1L;
24731    }else{
24732      lock.l_start = SHARED_FIRST;
24733      lock.l_len = SHARED_SIZE;
24734    }
24735
24736    if( unixFileLock(pFile, &lock) ){
24737      tErrno = errno;
24738      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
24739      if( rc!=SQLITE_BUSY ){
24740        pFile->lastErrno = tErrno;
24741      }
24742    }
24743  }
24744
24745
24746#ifdef SQLITE_DEBUG
24747  /* Set up the transaction-counter change checking flags when
24748  ** transitioning from a SHARED to a RESERVED lock.  The change
24749  ** from SHARED to RESERVED marks the beginning of a normal
24750  ** write operation (not a hot journal rollback).
24751  */
24752  if( rc==SQLITE_OK
24753   && pFile->eFileLock<=SHARED_LOCK
24754   && eFileLock==RESERVED_LOCK
24755  ){
24756    pFile->transCntrChng = 0;
24757    pFile->dbUpdate = 0;
24758    pFile->inNormalWrite = 1;
24759  }
24760#endif
24761
24762
24763  if( rc==SQLITE_OK ){
24764    pFile->eFileLock = eFileLock;
24765    pInode->eFileLock = eFileLock;
24766  }else if( eFileLock==EXCLUSIVE_LOCK ){
24767    pFile->eFileLock = PENDING_LOCK;
24768    pInode->eFileLock = PENDING_LOCK;
24769  }
24770
24771end_lock:
24772  unixLeaveMutex();
24773  OSTRACE(("LOCK    %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
24774      rc==SQLITE_OK ? "ok" : "failed"));
24775  return rc;
24776}
24777
24778/*
24779** Add the file descriptor used by file handle pFile to the corresponding
24780** pUnused list.
24781*/
24782static void setPendingFd(unixFile *pFile){
24783  unixInodeInfo *pInode = pFile->pInode;
24784  UnixUnusedFd *p = pFile->pUnused;
24785  p->pNext = pInode->pUnused;
24786  pInode->pUnused = p;
24787  pFile->h = -1;
24788  pFile->pUnused = 0;
24789}
24790
24791/*
24792** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
24793** must be either NO_LOCK or SHARED_LOCK.
24794**
24795** If the locking level of the file descriptor is already at or below
24796** the requested locking level, this routine is a no-op.
24797**
24798** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
24799** the byte range is divided into 2 parts and the first part is unlocked then
24800** set to a read lock, then the other part is simply unlocked.  This works
24801** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
24802** remove the write lock on a region when a read lock is set.
24803*/
24804static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
24805  unixFile *pFile = (unixFile*)id;
24806  unixInodeInfo *pInode;
24807  struct flock lock;
24808  int rc = SQLITE_OK;
24809
24810  assert( pFile );
24811  OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
24812      pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
24813      getpid()));
24814
24815  assert( eFileLock<=SHARED_LOCK );
24816  if( pFile->eFileLock<=eFileLock ){
24817    return SQLITE_OK;
24818  }
24819  unixEnterMutex();
24820  pInode = pFile->pInode;
24821  assert( pInode->nShared!=0 );
24822  if( pFile->eFileLock>SHARED_LOCK ){
24823    assert( pInode->eFileLock==pFile->eFileLock );
24824
24825#ifdef SQLITE_DEBUG
24826    /* When reducing a lock such that other processes can start
24827    ** reading the database file again, make sure that the
24828    ** transaction counter was updated if any part of the database
24829    ** file changed.  If the transaction counter is not updated,
24830    ** other connections to the same file might not realize that
24831    ** the file has changed and hence might not know to flush their
24832    ** cache.  The use of a stale cache can lead to database corruption.
24833    */
24834    pFile->inNormalWrite = 0;
24835#endif
24836
24837    /* downgrading to a shared lock on NFS involves clearing the write lock
24838    ** before establishing the readlock - to avoid a race condition we downgrade
24839    ** the lock in 2 blocks, so that part of the range will be covered by a
24840    ** write lock until the rest is covered by a read lock:
24841    **  1:   [WWWWW]
24842    **  2:   [....W]
24843    **  3:   [RRRRW]
24844    **  4:   [RRRR.]
24845    */
24846    if( eFileLock==SHARED_LOCK ){
24847
24848#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
24849      (void)handleNFSUnlock;
24850      assert( handleNFSUnlock==0 );
24851#endif
24852#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
24853      if( handleNFSUnlock ){
24854        int tErrno;               /* Error code from system call errors */
24855        off_t divSize = SHARED_SIZE - 1;
24856
24857        lock.l_type = F_UNLCK;
24858        lock.l_whence = SEEK_SET;
24859        lock.l_start = SHARED_FIRST;
24860        lock.l_len = divSize;
24861        if( unixFileLock(pFile, &lock)==(-1) ){
24862          tErrno = errno;
24863          rc = SQLITE_IOERR_UNLOCK;
24864          if( IS_LOCK_ERROR(rc) ){
24865            pFile->lastErrno = tErrno;
24866          }
24867          goto end_unlock;
24868        }
24869        lock.l_type = F_RDLCK;
24870        lock.l_whence = SEEK_SET;
24871        lock.l_start = SHARED_FIRST;
24872        lock.l_len = divSize;
24873        if( unixFileLock(pFile, &lock)==(-1) ){
24874          tErrno = errno;
24875          rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
24876          if( IS_LOCK_ERROR(rc) ){
24877            pFile->lastErrno = tErrno;
24878          }
24879          goto end_unlock;
24880        }
24881        lock.l_type = F_UNLCK;
24882        lock.l_whence = SEEK_SET;
24883        lock.l_start = SHARED_FIRST+divSize;
24884        lock.l_len = SHARED_SIZE-divSize;
24885        if( unixFileLock(pFile, &lock)==(-1) ){
24886          tErrno = errno;
24887          rc = SQLITE_IOERR_UNLOCK;
24888          if( IS_LOCK_ERROR(rc) ){
24889            pFile->lastErrno = tErrno;
24890          }
24891          goto end_unlock;
24892        }
24893      }else
24894#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
24895      {
24896        lock.l_type = F_RDLCK;
24897        lock.l_whence = SEEK_SET;
24898        lock.l_start = SHARED_FIRST;
24899        lock.l_len = SHARED_SIZE;
24900        if( unixFileLock(pFile, &lock) ){
24901          /* In theory, the call to unixFileLock() cannot fail because another
24902          ** process is holding an incompatible lock. If it does, this
24903          ** indicates that the other process is not following the locking
24904          ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
24905          ** SQLITE_BUSY would confuse the upper layer (in practice it causes
24906          ** an assert to fail). */
24907          rc = SQLITE_IOERR_RDLOCK;
24908          pFile->lastErrno = errno;
24909          goto end_unlock;
24910        }
24911      }
24912    }
24913    lock.l_type = F_UNLCK;
24914    lock.l_whence = SEEK_SET;
24915    lock.l_start = PENDING_BYTE;
24916    lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
24917    if( unixFileLock(pFile, &lock)==0 ){
24918      pInode->eFileLock = SHARED_LOCK;
24919    }else{
24920      rc = SQLITE_IOERR_UNLOCK;
24921      pFile->lastErrno = errno;
24922      goto end_unlock;
24923    }
24924  }
24925  if( eFileLock==NO_LOCK ){
24926    /* Decrement the shared lock counter.  Release the lock using an
24927    ** OS call only when all threads in this same process have released
24928    ** the lock.
24929    */
24930    pInode->nShared--;
24931    if( pInode->nShared==0 ){
24932      lock.l_type = F_UNLCK;
24933      lock.l_whence = SEEK_SET;
24934      lock.l_start = lock.l_len = 0L;
24935      if( unixFileLock(pFile, &lock)==0 ){
24936        pInode->eFileLock = NO_LOCK;
24937      }else{
24938        rc = SQLITE_IOERR_UNLOCK;
24939        pFile->lastErrno = errno;
24940        pInode->eFileLock = NO_LOCK;
24941        pFile->eFileLock = NO_LOCK;
24942      }
24943    }
24944
24945    /* Decrement the count of locks against this same file.  When the
24946    ** count reaches zero, close any other file descriptors whose close
24947    ** was deferred because of outstanding locks.
24948    */
24949    pInode->nLock--;
24950    assert( pInode->nLock>=0 );
24951    if( pInode->nLock==0 ){
24952      closePendingFds(pFile);
24953    }
24954  }
24955
24956end_unlock:
24957  unixLeaveMutex();
24958  if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
24959  return rc;
24960}
24961
24962/*
24963** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
24964** must be either NO_LOCK or SHARED_LOCK.
24965**
24966** If the locking level of the file descriptor is already at or below
24967** the requested locking level, this routine is a no-op.
24968*/
24969static int unixUnlock(sqlite3_file *id, int eFileLock){
24970  assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
24971  return posixUnlock(id, eFileLock, 0);
24972}
24973
24974static int unixMapfile(unixFile *pFd, i64 nByte);
24975static void unixUnmapfile(unixFile *pFd);
24976
24977/*
24978** This function performs the parts of the "close file" operation
24979** common to all locking schemes. It closes the directory and file
24980** handles, if they are valid, and sets all fields of the unixFile
24981** structure to 0.
24982**
24983** It is *not* necessary to hold the mutex when this routine is called,
24984** even on VxWorks.  A mutex will be acquired on VxWorks by the
24985** vxworksReleaseFileId() routine.
24986*/
24987static int closeUnixFile(sqlite3_file *id){
24988  unixFile *pFile = (unixFile*)id;
24989  unixUnmapfile(pFile);
24990  if( pFile->h>=0 ){
24991    robust_close(pFile, pFile->h, __LINE__);
24992    pFile->h = -1;
24993  }
24994#if OS_VXWORKS
24995  if( pFile->pId ){
24996    if( pFile->ctrlFlags & UNIXFILE_DELETE ){
24997      osUnlink(pFile->pId->zCanonicalName);
24998    }
24999    vxworksReleaseFileId(pFile->pId);
25000    pFile->pId = 0;
25001  }
25002#endif
25003  OSTRACE(("CLOSE   %-3d\n", pFile->h));
25004  OpenCounter(-1);
25005  sqlite3_free(pFile->pUnused);
25006  memset(pFile, 0, sizeof(unixFile));
25007  return SQLITE_OK;
25008}
25009
25010/*
25011** Close a file.
25012*/
25013static int unixClose(sqlite3_file *id){
25014  int rc = SQLITE_OK;
25015  unixFile *pFile = (unixFile *)id;
25016  verifyDbFile(pFile);
25017  unixUnlock(id, NO_LOCK);
25018  unixEnterMutex();
25019
25020  /* unixFile.pInode is always valid here. Otherwise, a different close
25021  ** routine (e.g. nolockClose()) would be called instead.
25022  */
25023  assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
25024  if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
25025    /* If there are outstanding locks, do not actually close the file just
25026    ** yet because that would clear those locks.  Instead, add the file
25027    ** descriptor to pInode->pUnused list.  It will be automatically closed
25028    ** when the last lock is cleared.
25029    */
25030    setPendingFd(pFile);
25031  }
25032  releaseInodeInfo(pFile);
25033  rc = closeUnixFile(id);
25034  unixLeaveMutex();
25035  return rc;
25036}
25037
25038/************** End of the posix advisory lock implementation *****************
25039******************************************************************************/
25040
25041/******************************************************************************
25042****************************** No-op Locking **********************************
25043**
25044** Of the various locking implementations available, this is by far the
25045** simplest:  locking is ignored.  No attempt is made to lock the database
25046** file for reading or writing.
25047**
25048** This locking mode is appropriate for use on read-only databases
25049** (ex: databases that are burned into CD-ROM, for example.)  It can
25050** also be used if the application employs some external mechanism to
25051** prevent simultaneous access of the same database by two or more
25052** database connections.  But there is a serious risk of database
25053** corruption if this locking mode is used in situations where multiple
25054** database connections are accessing the same database file at the same
25055** time and one or more of those connections are writing.
25056*/
25057
25058static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
25059  UNUSED_PARAMETER(NotUsed);
25060  *pResOut = 0;
25061  return SQLITE_OK;
25062}
25063static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
25064  UNUSED_PARAMETER2(NotUsed, NotUsed2);
25065  return SQLITE_OK;
25066}
25067static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
25068  UNUSED_PARAMETER2(NotUsed, NotUsed2);
25069  return SQLITE_OK;
25070}
25071
25072/*
25073** Close the file.
25074*/
25075static int nolockClose(sqlite3_file *id) {
25076  return closeUnixFile(id);
25077}
25078
25079/******************* End of the no-op lock implementation *********************
25080******************************************************************************/
25081
25082/******************************************************************************
25083************************* Begin dot-file Locking ******************************
25084**
25085** The dotfile locking implementation uses the existence of separate lock
25086** files (really a directory) to control access to the database.  This works
25087** on just about every filesystem imaginable.  But there are serious downsides:
25088**
25089**    (1)  There is zero concurrency.  A single reader blocks all other
25090**         connections from reading or writing the database.
25091**
25092**    (2)  An application crash or power loss can leave stale lock files
25093**         sitting around that need to be cleared manually.
25094**
25095** Nevertheless, a dotlock is an appropriate locking mode for use if no
25096** other locking strategy is available.
25097**
25098** Dotfile locking works by creating a subdirectory in the same directory as
25099** the database and with the same name but with a ".lock" extension added.
25100** The existence of a lock directory implies an EXCLUSIVE lock.  All other
25101** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
25102*/
25103
25104/*
25105** The file suffix added to the data base filename in order to create the
25106** lock directory.
25107*/
25108#define DOTLOCK_SUFFIX ".lock"
25109
25110/*
25111** This routine checks if there is a RESERVED lock held on the specified
25112** file by this or any other process. If such a lock is held, set *pResOut
25113** to a non-zero value otherwise *pResOut is set to zero.  The return value
25114** is set to SQLITE_OK unless an I/O error occurs during lock checking.
25115**
25116** In dotfile locking, either a lock exists or it does not.  So in this
25117** variation of CheckReservedLock(), *pResOut is set to true if any lock
25118** is held on the file and false if the file is unlocked.
25119*/
25120static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
25121  int rc = SQLITE_OK;
25122  int reserved = 0;
25123  unixFile *pFile = (unixFile*)id;
25124
25125  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
25126
25127  assert( pFile );
25128
25129  /* Check if a thread in this process holds such a lock */
25130  if( pFile->eFileLock>SHARED_LOCK ){
25131    /* Either this connection or some other connection in the same process
25132    ** holds a lock on the file.  No need to check further. */
25133    reserved = 1;
25134  }else{
25135    /* The lock is held if and only if the lockfile exists */
25136    const char *zLockFile = (const char*)pFile->lockingContext;
25137    reserved = osAccess(zLockFile, 0)==0;
25138  }
25139  OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
25140  *pResOut = reserved;
25141  return rc;
25142}
25143
25144/*
25145** Lock the file with the lock specified by parameter eFileLock - one
25146** of the following:
25147**
25148**     (1) SHARED_LOCK
25149**     (2) RESERVED_LOCK
25150**     (3) PENDING_LOCK
25151**     (4) EXCLUSIVE_LOCK
25152**
25153** Sometimes when requesting one lock state, additional lock states
25154** are inserted in between.  The locking might fail on one of the later
25155** transitions leaving the lock state different from what it started but
25156** still short of its goal.  The following chart shows the allowed
25157** transitions and the inserted intermediate states:
25158**
25159**    UNLOCKED -> SHARED
25160**    SHARED -> RESERVED
25161**    SHARED -> (PENDING) -> EXCLUSIVE
25162**    RESERVED -> (PENDING) -> EXCLUSIVE
25163**    PENDING -> EXCLUSIVE
25164**
25165** This routine will only increase a lock.  Use the sqlite3OsUnlock()
25166** routine to lower a locking level.
25167**
25168** With dotfile locking, we really only support state (4): EXCLUSIVE.
25169** But we track the other locking levels internally.
25170*/
25171static int dotlockLock(sqlite3_file *id, int eFileLock) {
25172  unixFile *pFile = (unixFile*)id;
25173  char *zLockFile = (char *)pFile->lockingContext;
25174  int rc = SQLITE_OK;
25175
25176
25177  /* If we have any lock, then the lock file already exists.  All we have
25178  ** to do is adjust our internal record of the lock level.
25179  */
25180  if( pFile->eFileLock > NO_LOCK ){
25181    pFile->eFileLock = eFileLock;
25182    /* Always update the timestamp on the old file */
25183#ifdef HAVE_UTIME
25184    utime(zLockFile, NULL);
25185#else
25186    utimes(zLockFile, NULL);
25187#endif
25188    return SQLITE_OK;
25189  }
25190
25191  /* grab an exclusive lock */
25192  rc = osMkdir(zLockFile, 0777);
25193  if( rc<0 ){
25194    /* failed to open/create the lock directory */
25195    int tErrno = errno;
25196    if( EEXIST == tErrno ){
25197      rc = SQLITE_BUSY;
25198    } else {
25199      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
25200      if( IS_LOCK_ERROR(rc) ){
25201        pFile->lastErrno = tErrno;
25202      }
25203    }
25204    return rc;
25205  }
25206
25207  /* got it, set the type and return ok */
25208  pFile->eFileLock = eFileLock;
25209  return rc;
25210}
25211
25212/*
25213** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
25214** must be either NO_LOCK or SHARED_LOCK.
25215**
25216** If the locking level of the file descriptor is already at or below
25217** the requested locking level, this routine is a no-op.
25218**
25219** When the locking level reaches NO_LOCK, delete the lock file.
25220*/
25221static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
25222  unixFile *pFile = (unixFile*)id;
25223  char *zLockFile = (char *)pFile->lockingContext;
25224  int rc;
25225
25226  assert( pFile );
25227  OSTRACE(("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
25228           pFile->eFileLock, getpid()));
25229  assert( eFileLock<=SHARED_LOCK );
25230
25231  /* no-op if possible */
25232  if( pFile->eFileLock==eFileLock ){
25233    return SQLITE_OK;
25234  }
25235
25236  /* To downgrade to shared, simply update our internal notion of the
25237  ** lock state.  No need to mess with the file on disk.
25238  */
25239  if( eFileLock==SHARED_LOCK ){
25240    pFile->eFileLock = SHARED_LOCK;
25241    return SQLITE_OK;
25242  }
25243
25244  /* To fully unlock the database, delete the lock file */
25245  assert( eFileLock==NO_LOCK );
25246  rc = osRmdir(zLockFile);
25247  if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
25248  if( rc<0 ){
25249    int tErrno = errno;
25250    rc = 0;
25251    if( ENOENT != tErrno ){
25252      rc = SQLITE_IOERR_UNLOCK;
25253    }
25254    if( IS_LOCK_ERROR(rc) ){
25255      pFile->lastErrno = tErrno;
25256    }
25257    return rc;
25258  }
25259  pFile->eFileLock = NO_LOCK;
25260  return SQLITE_OK;
25261}
25262
25263/*
25264** Close a file.  Make sure the lock has been released before closing.
25265*/
25266static int dotlockClose(sqlite3_file *id) {
25267  int rc = SQLITE_OK;
25268  if( id ){
25269    unixFile *pFile = (unixFile*)id;
25270    dotlockUnlock(id, NO_LOCK);
25271    sqlite3_free(pFile->lockingContext);
25272    rc = closeUnixFile(id);
25273  }
25274  return rc;
25275}
25276/****************** End of the dot-file lock implementation *******************
25277******************************************************************************/
25278
25279/******************************************************************************
25280************************** Begin flock Locking ********************************
25281**
25282** Use the flock() system call to do file locking.
25283**
25284** flock() locking is like dot-file locking in that the various
25285** fine-grain locking levels supported by SQLite are collapsed into
25286** a single exclusive lock.  In other words, SHARED, RESERVED, and
25287** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
25288** still works when you do this, but concurrency is reduced since
25289** only a single process can be reading the database at a time.
25290**
25291** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
25292** compiling for VXWORKS.
25293*/
25294#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
25295
25296/*
25297** Retry flock() calls that fail with EINTR
25298*/
25299#ifdef EINTR
25300static int robust_flock(int fd, int op){
25301  int rc;
25302  do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
25303  return rc;
25304}
25305#else
25306# define robust_flock(a,b) flock(a,b)
25307#endif
25308
25309
25310/*
25311** This routine checks if there is a RESERVED lock held on the specified
25312** file by this or any other process. If such a lock is held, set *pResOut
25313** to a non-zero value otherwise *pResOut is set to zero.  The return value
25314** is set to SQLITE_OK unless an I/O error occurs during lock checking.
25315*/
25316static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
25317  int rc = SQLITE_OK;
25318  int reserved = 0;
25319  unixFile *pFile = (unixFile*)id;
25320
25321  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
25322
25323  assert( pFile );
25324
25325  /* Check if a thread in this process holds such a lock */
25326  if( pFile->eFileLock>SHARED_LOCK ){
25327    reserved = 1;
25328  }
25329
25330  /* Otherwise see if some other process holds it. */
25331  if( !reserved ){
25332    /* attempt to get the lock */
25333    int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
25334    if( !lrc ){
25335      /* got the lock, unlock it */
25336      lrc = robust_flock(pFile->h, LOCK_UN);
25337      if ( lrc ) {
25338        int tErrno = errno;
25339        /* unlock failed with an error */
25340        lrc = SQLITE_IOERR_UNLOCK;
25341        if( IS_LOCK_ERROR(lrc) ){
25342          pFile->lastErrno = tErrno;
25343          rc = lrc;
25344        }
25345      }
25346    } else {
25347      int tErrno = errno;
25348      reserved = 1;
25349      /* someone else might have it reserved */
25350      lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
25351      if( IS_LOCK_ERROR(lrc) ){
25352        pFile->lastErrno = tErrno;
25353        rc = lrc;
25354      }
25355    }
25356  }
25357  OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
25358
25359#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
25360  if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
25361    rc = SQLITE_OK;
25362    reserved=1;
25363  }
25364#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
25365  *pResOut = reserved;
25366  return rc;
25367}
25368
25369/*
25370** Lock the file with the lock specified by parameter eFileLock - one
25371** of the following:
25372**
25373**     (1) SHARED_LOCK
25374**     (2) RESERVED_LOCK
25375**     (3) PENDING_LOCK
25376**     (4) EXCLUSIVE_LOCK
25377**
25378** Sometimes when requesting one lock state, additional lock states
25379** are inserted in between.  The locking might fail on one of the later
25380** transitions leaving the lock state different from what it started but
25381** still short of its goal.  The following chart shows the allowed
25382** transitions and the inserted intermediate states:
25383**
25384**    UNLOCKED -> SHARED
25385**    SHARED -> RESERVED
25386**    SHARED -> (PENDING) -> EXCLUSIVE
25387**    RESERVED -> (PENDING) -> EXCLUSIVE
25388**    PENDING -> EXCLUSIVE
25389**
25390** flock() only really support EXCLUSIVE locks.  We track intermediate
25391** lock states in the sqlite3_file structure, but all locks SHARED or
25392** above are really EXCLUSIVE locks and exclude all other processes from
25393** access the file.
25394**
25395** This routine will only increase a lock.  Use the sqlite3OsUnlock()
25396** routine to lower a locking level.
25397*/
25398static int flockLock(sqlite3_file *id, int eFileLock) {
25399  int rc = SQLITE_OK;
25400  unixFile *pFile = (unixFile*)id;
25401
25402  assert( pFile );
25403
25404  /* if we already have a lock, it is exclusive.
25405  ** Just adjust level and punt on outta here. */
25406  if (pFile->eFileLock > NO_LOCK) {
25407    pFile->eFileLock = eFileLock;
25408    return SQLITE_OK;
25409  }
25410
25411  /* grab an exclusive lock */
25412
25413  if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
25414    int tErrno = errno;
25415    /* didn't get, must be busy */
25416    rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
25417    if( IS_LOCK_ERROR(rc) ){
25418      pFile->lastErrno = tErrno;
25419    }
25420  } else {
25421    /* got it, set the type and return ok */
25422    pFile->eFileLock = eFileLock;
25423  }
25424  OSTRACE(("LOCK    %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
25425           rc==SQLITE_OK ? "ok" : "failed"));
25426#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
25427  if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
25428    rc = SQLITE_BUSY;
25429  }
25430#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
25431  return rc;
25432}
25433
25434
25435/*
25436** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
25437** must be either NO_LOCK or SHARED_LOCK.
25438**
25439** If the locking level of the file descriptor is already at or below
25440** the requested locking level, this routine is a no-op.
25441*/
25442static int flockUnlock(sqlite3_file *id, int eFileLock) {
25443  unixFile *pFile = (unixFile*)id;
25444
25445  assert( pFile );
25446  OSTRACE(("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
25447           pFile->eFileLock, getpid()));
25448  assert( eFileLock<=SHARED_LOCK );
25449
25450  /* no-op if possible */
25451  if( pFile->eFileLock==eFileLock ){
25452    return SQLITE_OK;
25453  }
25454
25455  /* shared can just be set because we always have an exclusive */
25456  if (eFileLock==SHARED_LOCK) {
25457    pFile->eFileLock = eFileLock;
25458    return SQLITE_OK;
25459  }
25460
25461  /* no, really, unlock. */
25462  if( robust_flock(pFile->h, LOCK_UN) ){
25463#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
25464    return SQLITE_OK;
25465#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
25466    return SQLITE_IOERR_UNLOCK;
25467  }else{
25468    pFile->eFileLock = NO_LOCK;
25469    return SQLITE_OK;
25470  }
25471}
25472
25473/*
25474** Close a file.
25475*/
25476static int flockClose(sqlite3_file *id) {
25477  int rc = SQLITE_OK;
25478  if( id ){
25479    flockUnlock(id, NO_LOCK);
25480    rc = closeUnixFile(id);
25481  }
25482  return rc;
25483}
25484
25485#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
25486
25487/******************* End of the flock lock implementation *********************
25488******************************************************************************/
25489
25490/******************************************************************************
25491************************ Begin Named Semaphore Locking ************************
25492**
25493** Named semaphore locking is only supported on VxWorks.
25494**
25495** Semaphore locking is like dot-lock and flock in that it really only
25496** supports EXCLUSIVE locking.  Only a single process can read or write
25497** the database file at a time.  This reduces potential concurrency, but
25498** makes the lock implementation much easier.
25499*/
25500#if OS_VXWORKS
25501
25502/*
25503** This routine checks if there is a RESERVED lock held on the specified
25504** file by this or any other process. If such a lock is held, set *pResOut
25505** to a non-zero value otherwise *pResOut is set to zero.  The return value
25506** is set to SQLITE_OK unless an I/O error occurs during lock checking.
25507*/
25508static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
25509  int rc = SQLITE_OK;
25510  int reserved = 0;
25511  unixFile *pFile = (unixFile*)id;
25512
25513  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
25514
25515  assert( pFile );
25516
25517  /* Check if a thread in this process holds such a lock */
25518  if( pFile->eFileLock>SHARED_LOCK ){
25519    reserved = 1;
25520  }
25521
25522  /* Otherwise see if some other process holds it. */
25523  if( !reserved ){
25524    sem_t *pSem = pFile->pInode->pSem;
25525    struct stat statBuf;
25526
25527    if( sem_trywait(pSem)==-1 ){
25528      int tErrno = errno;
25529      if( EAGAIN != tErrno ){
25530        rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
25531        pFile->lastErrno = tErrno;
25532      } else {
25533        /* someone else has the lock when we are in NO_LOCK */
25534        reserved = (pFile->eFileLock < SHARED_LOCK);
25535      }
25536    }else{
25537      /* we could have it if we want it */
25538      sem_post(pSem);
25539    }
25540  }
25541  OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
25542
25543  *pResOut = reserved;
25544  return rc;
25545}
25546
25547/*
25548** Lock the file with the lock specified by parameter eFileLock - one
25549** of the following:
25550**
25551**     (1) SHARED_LOCK
25552**     (2) RESERVED_LOCK
25553**     (3) PENDING_LOCK
25554**     (4) EXCLUSIVE_LOCK
25555**
25556** Sometimes when requesting one lock state, additional lock states
25557** are inserted in between.  The locking might fail on one of the later
25558** transitions leaving the lock state different from what it started but
25559** still short of its goal.  The following chart shows the allowed
25560** transitions and the inserted intermediate states:
25561**
25562**    UNLOCKED -> SHARED
25563**    SHARED -> RESERVED
25564**    SHARED -> (PENDING) -> EXCLUSIVE
25565**    RESERVED -> (PENDING) -> EXCLUSIVE
25566**    PENDING -> EXCLUSIVE
25567**
25568** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
25569** lock states in the sqlite3_file structure, but all locks SHARED or
25570** above are really EXCLUSIVE locks and exclude all other processes from
25571** access the file.
25572**
25573** This routine will only increase a lock.  Use the sqlite3OsUnlock()
25574** routine to lower a locking level.
25575*/
25576static int semLock(sqlite3_file *id, int eFileLock) {
25577  unixFile *pFile = (unixFile*)id;
25578  int fd;
25579  sem_t *pSem = pFile->pInode->pSem;
25580  int rc = SQLITE_OK;
25581
25582  /* if we already have a lock, it is exclusive.
25583  ** Just adjust level and punt on outta here. */
25584  if (pFile->eFileLock > NO_LOCK) {
25585    pFile->eFileLock = eFileLock;
25586    rc = SQLITE_OK;
25587    goto sem_end_lock;
25588  }
25589
25590  /* lock semaphore now but bail out when already locked. */
25591  if( sem_trywait(pSem)==-1 ){
25592    rc = SQLITE_BUSY;
25593    goto sem_end_lock;
25594  }
25595
25596  /* got it, set the type and return ok */
25597  pFile->eFileLock = eFileLock;
25598
25599 sem_end_lock:
25600  return rc;
25601}
25602
25603/*
25604** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
25605** must be either NO_LOCK or SHARED_LOCK.
25606**
25607** If the locking level of the file descriptor is already at or below
25608** the requested locking level, this routine is a no-op.
25609*/
25610static int semUnlock(sqlite3_file *id, int eFileLock) {
25611  unixFile *pFile = (unixFile*)id;
25612  sem_t *pSem = pFile->pInode->pSem;
25613
25614  assert( pFile );
25615  assert( pSem );
25616  OSTRACE(("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
25617           pFile->eFileLock, getpid()));
25618  assert( eFileLock<=SHARED_LOCK );
25619
25620  /* no-op if possible */
25621  if( pFile->eFileLock==eFileLock ){
25622    return SQLITE_OK;
25623  }
25624
25625  /* shared can just be set because we always have an exclusive */
25626  if (eFileLock==SHARED_LOCK) {
25627    pFile->eFileLock = eFileLock;
25628    return SQLITE_OK;
25629  }
25630
25631  /* no, really unlock. */
25632  if ( sem_post(pSem)==-1 ) {
25633    int rc, tErrno = errno;
25634    rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
25635    if( IS_LOCK_ERROR(rc) ){
25636      pFile->lastErrno = tErrno;
25637    }
25638    return rc;
25639  }
25640  pFile->eFileLock = NO_LOCK;
25641  return SQLITE_OK;
25642}
25643
25644/*
25645 ** Close a file.
25646 */
25647static int semClose(sqlite3_file *id) {
25648  if( id ){
25649    unixFile *pFile = (unixFile*)id;
25650    semUnlock(id, NO_LOCK);
25651    assert( pFile );
25652    unixEnterMutex();
25653    releaseInodeInfo(pFile);
25654    unixLeaveMutex();
25655    closeUnixFile(id);
25656  }
25657  return SQLITE_OK;
25658}
25659
25660#endif /* OS_VXWORKS */
25661/*
25662** Named semaphore locking is only available on VxWorks.
25663**
25664*************** End of the named semaphore lock implementation ****************
25665******************************************************************************/
25666
25667
25668/******************************************************************************
25669*************************** Begin AFP Locking *********************************
25670**
25671** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
25672** on Apple Macintosh computers - both OS9 and OSX.
25673**
25674** Third-party implementations of AFP are available.  But this code here
25675** only works on OSX.
25676*/
25677
25678#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
25679/*
25680** The afpLockingContext structure contains all afp lock specific state
25681*/
25682typedef struct afpLockingContext afpLockingContext;
25683struct afpLockingContext {
25684  int reserved;
25685  const char *dbPath;             /* Name of the open file */
25686};
25687
25688struct ByteRangeLockPB2
25689{
25690  unsigned long long offset;        /* offset to first byte to lock */
25691  unsigned long long length;        /* nbr of bytes to lock */
25692  unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
25693  unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
25694  unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
25695  int fd;                           /* file desc to assoc this lock with */
25696};
25697
25698#define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
25699
25700/*
25701** This is a utility for setting or clearing a bit-range lock on an
25702** AFP filesystem.
25703**
25704** Return SQLITE_OK on success, SQLITE_BUSY on failure.
25705*/
25706static int afpSetLock(
25707  const char *path,              /* Name of the file to be locked or unlocked */
25708  unixFile *pFile,               /* Open file descriptor on path */
25709  unsigned long long offset,     /* First byte to be locked */
25710  unsigned long long length,     /* Number of bytes to lock */
25711  int setLockFlag                /* True to set lock.  False to clear lock */
25712){
25713  struct ByteRangeLockPB2 pb;
25714  int err;
25715
25716  pb.unLockFlag = setLockFlag ? 0 : 1;
25717  pb.startEndFlag = 0;
25718  pb.offset = offset;
25719  pb.length = length;
25720  pb.fd = pFile->h;
25721
25722  OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
25723    (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
25724    offset, length));
25725  err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
25726  if ( err==-1 ) {
25727    int rc;
25728    int tErrno = errno;
25729    OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
25730             path, tErrno, strerror(tErrno)));
25731#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
25732    rc = SQLITE_BUSY;
25733#else
25734    rc = sqliteErrorFromPosixError(tErrno,
25735                    setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
25736#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
25737    if( IS_LOCK_ERROR(rc) ){
25738      pFile->lastErrno = tErrno;
25739    }
25740    return rc;
25741  } else {
25742    return SQLITE_OK;
25743  }
25744}
25745
25746/*
25747** This routine checks if there is a RESERVED lock held on the specified
25748** file by this or any other process. If such a lock is held, set *pResOut
25749** to a non-zero value otherwise *pResOut is set to zero.  The return value
25750** is set to SQLITE_OK unless an I/O error occurs during lock checking.
25751*/
25752static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
25753  int rc = SQLITE_OK;
25754  int reserved = 0;
25755  unixFile *pFile = (unixFile*)id;
25756  afpLockingContext *context;
25757
25758  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
25759
25760  assert( pFile );
25761  context = (afpLockingContext *) pFile->lockingContext;
25762  if( context->reserved ){
25763    *pResOut = 1;
25764    return SQLITE_OK;
25765  }
25766  unixEnterMutex(); /* Because pFile->pInode is shared across threads */
25767
25768  /* Check if a thread in this process holds such a lock */
25769  if( pFile->pInode->eFileLock>SHARED_LOCK ){
25770    reserved = 1;
25771  }
25772
25773  /* Otherwise see if some other process holds it.
25774   */
25775  if( !reserved ){
25776    /* lock the RESERVED byte */
25777    int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
25778    if( SQLITE_OK==lrc ){
25779      /* if we succeeded in taking the reserved lock, unlock it to restore
25780      ** the original state */
25781      lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
25782    } else {
25783      /* if we failed to get the lock then someone else must have it */
25784      reserved = 1;
25785    }
25786    if( IS_LOCK_ERROR(lrc) ){
25787      rc=lrc;
25788    }
25789  }
25790
25791  unixLeaveMutex();
25792  OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
25793
25794  *pResOut = reserved;
25795  return rc;
25796}
25797
25798/*
25799** Lock the file with the lock specified by parameter eFileLock - one
25800** of the following:
25801**
25802**     (1) SHARED_LOCK
25803**     (2) RESERVED_LOCK
25804**     (3) PENDING_LOCK
25805**     (4) EXCLUSIVE_LOCK
25806**
25807** Sometimes when requesting one lock state, additional lock states
25808** are inserted in between.  The locking might fail on one of the later
25809** transitions leaving the lock state different from what it started but
25810** still short of its goal.  The following chart shows the allowed
25811** transitions and the inserted intermediate states:
25812**
25813**    UNLOCKED -> SHARED
25814**    SHARED -> RESERVED
25815**    SHARED -> (PENDING) -> EXCLUSIVE
25816**    RESERVED -> (PENDING) -> EXCLUSIVE
25817**    PENDING -> EXCLUSIVE
25818**
25819** This routine will only increase a lock.  Use the sqlite3OsUnlock()
25820** routine to lower a locking level.
25821*/
25822static int afpLock(sqlite3_file *id, int eFileLock){
25823  int rc = SQLITE_OK;
25824  unixFile *pFile = (unixFile*)id;
25825  unixInodeInfo *pInode = pFile->pInode;
25826  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
25827
25828  assert( pFile );
25829  OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
25830           azFileLock(eFileLock), azFileLock(pFile->eFileLock),
25831           azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
25832
25833  /* If there is already a lock of this type or more restrictive on the
25834  ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
25835  ** unixEnterMutex() hasn't been called yet.
25836  */
25837  if( pFile->eFileLock>=eFileLock ){
25838    OSTRACE(("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
25839           azFileLock(eFileLock)));
25840    return SQLITE_OK;
25841  }
25842
25843  /* Make sure the locking sequence is correct
25844  **  (1) We never move from unlocked to anything higher than shared lock.
25845  **  (2) SQLite never explicitly requests a pendig lock.
25846  **  (3) A shared lock is always held when a reserve lock is requested.
25847  */
25848  assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
25849  assert( eFileLock!=PENDING_LOCK );
25850  assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
25851
25852  /* This mutex is needed because pFile->pInode is shared across threads
25853  */
25854  unixEnterMutex();
25855  pInode = pFile->pInode;
25856
25857  /* If some thread using this PID has a lock via a different unixFile*
25858  ** handle that precludes the requested lock, return BUSY.
25859  */
25860  if( (pFile->eFileLock!=pInode->eFileLock &&
25861       (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
25862     ){
25863    rc = SQLITE_BUSY;
25864    goto afp_end_lock;
25865  }
25866
25867  /* If a SHARED lock is requested, and some thread using this PID already
25868  ** has a SHARED or RESERVED lock, then increment reference counts and
25869  ** return SQLITE_OK.
25870  */
25871  if( eFileLock==SHARED_LOCK &&
25872     (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
25873    assert( eFileLock==SHARED_LOCK );
25874    assert( pFile->eFileLock==0 );
25875    assert( pInode->nShared>0 );
25876    pFile->eFileLock = SHARED_LOCK;
25877    pInode->nShared++;
25878    pInode->nLock++;
25879    goto afp_end_lock;
25880  }
25881
25882  /* A PENDING lock is needed before acquiring a SHARED lock and before
25883  ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
25884  ** be released.
25885  */
25886  if( eFileLock==SHARED_LOCK
25887      || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
25888  ){
25889    int failed;
25890    failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
25891    if (failed) {
25892      rc = failed;
25893      goto afp_end_lock;
25894    }
25895  }
25896
25897  /* If control gets to this point, then actually go ahead and make
25898  ** operating system calls for the specified lock.
25899  */
25900  if( eFileLock==SHARED_LOCK ){
25901    int lrc1, lrc2, lrc1Errno = 0;
25902    long lk, mask;
25903
25904    assert( pInode->nShared==0 );
25905    assert( pInode->eFileLock==0 );
25906
25907    mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
25908    /* Now get the read-lock SHARED_LOCK */
25909    /* note that the quality of the randomness doesn't matter that much */
25910    lk = random();
25911    pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
25912    lrc1 = afpSetLock(context->dbPath, pFile,
25913          SHARED_FIRST+pInode->sharedByte, 1, 1);
25914    if( IS_LOCK_ERROR(lrc1) ){
25915      lrc1Errno = pFile->lastErrno;
25916    }
25917    /* Drop the temporary PENDING lock */
25918    lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
25919
25920    if( IS_LOCK_ERROR(lrc1) ) {
25921      pFile->lastErrno = lrc1Errno;
25922      rc = lrc1;
25923      goto afp_end_lock;
25924    } else if( IS_LOCK_ERROR(lrc2) ){
25925      rc = lrc2;
25926      goto afp_end_lock;
25927    } else if( lrc1 != SQLITE_OK ) {
25928      rc = lrc1;
25929    } else {
25930      pFile->eFileLock = SHARED_LOCK;
25931      pInode->nLock++;
25932      pInode->nShared = 1;
25933    }
25934  }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
25935    /* We are trying for an exclusive lock but another thread in this
25936     ** same process is still holding a shared lock. */
25937    rc = SQLITE_BUSY;
25938  }else{
25939    /* The request was for a RESERVED or EXCLUSIVE lock.  It is
25940    ** assumed that there is a SHARED or greater lock on the file
25941    ** already.
25942    */
25943    int failed = 0;
25944    assert( 0!=pFile->eFileLock );
25945    if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
25946        /* Acquire a RESERVED lock */
25947        failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
25948      if( !failed ){
25949        context->reserved = 1;
25950      }
25951    }
25952    if (!failed && eFileLock == EXCLUSIVE_LOCK) {
25953      /* Acquire an EXCLUSIVE lock */
25954
25955      /* Remove the shared lock before trying the range.  we'll need to
25956      ** reestablish the shared lock if we can't get the  afpUnlock
25957      */
25958      if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
25959                         pInode->sharedByte, 1, 0)) ){
25960        int failed2 = SQLITE_OK;
25961        /* now attemmpt to get the exclusive lock range */
25962        failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
25963                               SHARED_SIZE, 1);
25964        if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
25965                       SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
25966          /* Can't reestablish the shared lock.  Sqlite can't deal, this is
25967          ** a critical I/O error
25968          */
25969          rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
25970               SQLITE_IOERR_LOCK;
25971          goto afp_end_lock;
25972        }
25973      }else{
25974        rc = failed;
25975      }
25976    }
25977    if( failed ){
25978      rc = failed;
25979    }
25980  }
25981
25982  if( rc==SQLITE_OK ){
25983    pFile->eFileLock = eFileLock;
25984    pInode->eFileLock = eFileLock;
25985  }else if( eFileLock==EXCLUSIVE_LOCK ){
25986    pFile->eFileLock = PENDING_LOCK;
25987    pInode->eFileLock = PENDING_LOCK;
25988  }
25989
25990afp_end_lock:
25991  unixLeaveMutex();
25992  OSTRACE(("LOCK    %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
25993         rc==SQLITE_OK ? "ok" : "failed"));
25994  return rc;
25995}
25996
25997/*
25998** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
25999** must be either NO_LOCK or SHARED_LOCK.
26000**
26001** If the locking level of the file descriptor is already at or below
26002** the requested locking level, this routine is a no-op.
26003*/
26004static int afpUnlock(sqlite3_file *id, int eFileLock) {
26005  int rc = SQLITE_OK;
26006  unixFile *pFile = (unixFile*)id;
26007  unixInodeInfo *pInode;
26008  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
26009  int skipShared = 0;
26010#ifdef SQLITE_TEST
26011  int h = pFile->h;
26012#endif
26013
26014  assert( pFile );
26015  OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
26016           pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
26017           getpid()));
26018
26019  assert( eFileLock<=SHARED_LOCK );
26020  if( pFile->eFileLock<=eFileLock ){
26021    return SQLITE_OK;
26022  }
26023  unixEnterMutex();
26024  pInode = pFile->pInode;
26025  assert( pInode->nShared!=0 );
26026  if( pFile->eFileLock>SHARED_LOCK ){
26027    assert( pInode->eFileLock==pFile->eFileLock );
26028    SimulateIOErrorBenign(1);
26029    SimulateIOError( h=(-1) )
26030    SimulateIOErrorBenign(0);
26031
26032#ifdef SQLITE_DEBUG
26033    /* When reducing a lock such that other processes can start
26034    ** reading the database file again, make sure that the
26035    ** transaction counter was updated if any part of the database
26036    ** file changed.  If the transaction counter is not updated,
26037    ** other connections to the same file might not realize that
26038    ** the file has changed and hence might not know to flush their
26039    ** cache.  The use of a stale cache can lead to database corruption.
26040    */
26041    assert( pFile->inNormalWrite==0
26042           || pFile->dbUpdate==0
26043           || pFile->transCntrChng==1 );
26044    pFile->inNormalWrite = 0;
26045#endif
26046
26047    if( pFile->eFileLock==EXCLUSIVE_LOCK ){
26048      rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
26049      if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
26050        /* only re-establish the shared lock if necessary */
26051        int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
26052        rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
26053      } else {
26054        skipShared = 1;
26055      }
26056    }
26057    if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
26058      rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
26059    }
26060    if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
26061      rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
26062      if( !rc ){
26063        context->reserved = 0;
26064      }
26065    }
26066    if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
26067      pInode->eFileLock = SHARED_LOCK;
26068    }
26069  }
26070  if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
26071
26072    /* Decrement the shared lock counter.  Release the lock using an
26073    ** OS call only when all threads in this same process have released
26074    ** the lock.
26075    */
26076    unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
26077    pInode->nShared--;
26078    if( pInode->nShared==0 ){
26079      SimulateIOErrorBenign(1);
26080      SimulateIOError( h=(-1) )
26081      SimulateIOErrorBenign(0);
26082      if( !skipShared ){
26083        rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
26084      }
26085      if( !rc ){
26086        pInode->eFileLock = NO_LOCK;
26087        pFile->eFileLock = NO_LOCK;
26088      }
26089    }
26090    if( rc==SQLITE_OK ){
26091      pInode->nLock--;
26092      assert( pInode->nLock>=0 );
26093      if( pInode->nLock==0 ){
26094        closePendingFds(pFile);
26095      }
26096    }
26097  }
26098
26099  unixLeaveMutex();
26100  if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
26101  return rc;
26102}
26103
26104/*
26105** Close a file & cleanup AFP specific locking context
26106*/
26107static int afpClose(sqlite3_file *id) {
26108  int rc = SQLITE_OK;
26109  if( id ){
26110    unixFile *pFile = (unixFile*)id;
26111    afpUnlock(id, NO_LOCK);
26112    unixEnterMutex();
26113    if( pFile->pInode && pFile->pInode->nLock ){
26114      /* If there are outstanding locks, do not actually close the file just
26115      ** yet because that would clear those locks.  Instead, add the file
26116      ** descriptor to pInode->aPending.  It will be automatically closed when
26117      ** the last lock is cleared.
26118      */
26119      setPendingFd(pFile);
26120    }
26121    releaseInodeInfo(pFile);
26122    sqlite3_free(pFile->lockingContext);
26123    rc = closeUnixFile(id);
26124    unixLeaveMutex();
26125  }
26126  return rc;
26127}
26128
26129#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
26130/*
26131** The code above is the AFP lock implementation.  The code is specific
26132** to MacOSX and does not work on other unix platforms.  No alternative
26133** is available.  If you don't compile for a mac, then the "unix-afp"
26134** VFS is not available.
26135**
26136********************* End of the AFP lock implementation **********************
26137******************************************************************************/
26138
26139/******************************************************************************
26140*************************** Begin NFS Locking ********************************/
26141
26142#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26143/*
26144 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
26145 ** must be either NO_LOCK or SHARED_LOCK.
26146 **
26147 ** If the locking level of the file descriptor is already at or below
26148 ** the requested locking level, this routine is a no-op.
26149 */
26150static int nfsUnlock(sqlite3_file *id, int eFileLock){
26151  return posixUnlock(id, eFileLock, 1);
26152}
26153
26154#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
26155/*
26156** The code above is the NFS lock implementation.  The code is specific
26157** to MacOSX and does not work on other unix platforms.  No alternative
26158** is available.
26159**
26160********************* End of the NFS lock implementation **********************
26161******************************************************************************/
26162
26163/******************************************************************************
26164**************** Non-locking sqlite3_file methods *****************************
26165**
26166** The next division contains implementations for all methods of the
26167** sqlite3_file object other than the locking methods.  The locking
26168** methods were defined in divisions above (one locking method per
26169** division).  Those methods that are common to all locking modes
26170** are gather together into this division.
26171*/
26172
26173/*
26174** Seek to the offset passed as the second argument, then read cnt
26175** bytes into pBuf. Return the number of bytes actually read.
26176**
26177** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
26178** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
26179** one system to another.  Since SQLite does not define USE_PREAD
26180** any any form by default, we will not attempt to define _XOPEN_SOURCE.
26181** See tickets #2741 and #2681.
26182**
26183** To avoid stomping the errno value on a failed read the lastErrno value
26184** is set before returning.
26185*/
26186static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
26187  int got;
26188  int prior = 0;
26189#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
26190  i64 newOffset;
26191#endif
26192  TIMER_START;
26193  assert( cnt==(cnt&0x1ffff) );
26194  cnt &= 0x1ffff;
26195  do{
26196#if defined(USE_PREAD)
26197    got = osPread(id->h, pBuf, cnt, offset);
26198    SimulateIOError( got = -1 );
26199#elif defined(USE_PREAD64)
26200    got = osPread64(id->h, pBuf, cnt, offset);
26201    SimulateIOError( got = -1 );
26202#else
26203    newOffset = lseek(id->h, offset, SEEK_SET);
26204    SimulateIOError( newOffset-- );
26205    if( newOffset!=offset ){
26206      if( newOffset == -1 ){
26207        ((unixFile*)id)->lastErrno = errno;
26208      }else{
26209        ((unixFile*)id)->lastErrno = 0;
26210      }
26211      return -1;
26212    }
26213    got = osRead(id->h, pBuf, cnt);
26214#endif
26215    if( got==cnt ) break;
26216    if( got<0 ){
26217      if( errno==EINTR ){ got = 1; continue; }
26218      prior = 0;
26219      ((unixFile*)id)->lastErrno = errno;
26220      break;
26221    }else if( got>0 ){
26222      cnt -= got;
26223      offset += got;
26224      prior += got;
26225      pBuf = (void*)(got + (char*)pBuf);
26226    }
26227  }while( got>0 );
26228  TIMER_END;
26229  OSTRACE(("READ    %-3d %5d %7lld %llu\n",
26230            id->h, got+prior, offset-prior, TIMER_ELAPSED));
26231  return got+prior;
26232}
26233
26234/*
26235** Read data from a file into a buffer.  Return SQLITE_OK if all
26236** bytes were read successfully and SQLITE_IOERR if anything goes
26237** wrong.
26238*/
26239static int unixRead(
26240  sqlite3_file *id,
26241  void *pBuf,
26242  int amt,
26243  sqlite3_int64 offset
26244){
26245  unixFile *pFile = (unixFile *)id;
26246  int got;
26247  assert( id );
26248  assert( offset>=0 );
26249  assert( amt>0 );
26250
26251  /* If this is a database file (not a journal, master-journal or temp
26252  ** file), the bytes in the locking range should never be read or written. */
26253#if 0
26254  assert( pFile->pUnused==0
26255       || offset>=PENDING_BYTE+512
26256       || offset+amt<=PENDING_BYTE
26257  );
26258#endif
26259
26260#if SQLITE_MAX_MMAP_SIZE>0
26261  /* Deal with as much of this read request as possible by transfering
26262  ** data from the memory mapping using memcpy().  */
26263  if( offset<pFile->mmapSize ){
26264    if( offset+amt <= pFile->mmapSize ){
26265      memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
26266      return SQLITE_OK;
26267    }else{
26268      int nCopy = pFile->mmapSize - offset;
26269      memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
26270      pBuf = &((u8 *)pBuf)[nCopy];
26271      amt -= nCopy;
26272      offset += nCopy;
26273    }
26274  }
26275#endif
26276
26277  got = seekAndRead(pFile, offset, pBuf, amt);
26278  if( got==amt ){
26279    return SQLITE_OK;
26280  }else if( got<0 ){
26281    /* lastErrno set by seekAndRead */
26282    return SQLITE_IOERR_READ;
26283  }else{
26284    pFile->lastErrno = 0; /* not a system error */
26285    /* Unread parts of the buffer must be zero-filled */
26286    memset(&((char*)pBuf)[got], 0, amt-got);
26287    return SQLITE_IOERR_SHORT_READ;
26288  }
26289}
26290
26291/*
26292** Attempt to seek the file-descriptor passed as the first argument to
26293** absolute offset iOff, then attempt to write nBuf bytes of data from
26294** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
26295** return the actual number of bytes written (which may be less than
26296** nBuf).
26297*/
26298static int seekAndWriteFd(
26299  int fd,                         /* File descriptor to write to */
26300  i64 iOff,                       /* File offset to begin writing at */
26301  const void *pBuf,               /* Copy data from this buffer to the file */
26302  int nBuf,                       /* Size of buffer pBuf in bytes */
26303  int *piErrno                    /* OUT: Error number if error occurs */
26304){
26305  int rc = 0;                     /* Value returned by system call */
26306
26307  assert( nBuf==(nBuf&0x1ffff) );
26308  nBuf &= 0x1ffff;
26309  TIMER_START;
26310
26311#if defined(USE_PREAD)
26312  do{ rc = osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
26313#elif defined(USE_PREAD64)
26314  do{ rc = osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
26315#else
26316  do{
26317    i64 iSeek = lseek(fd, iOff, SEEK_SET);
26318    SimulateIOError( iSeek-- );
26319
26320    if( iSeek!=iOff ){
26321      if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0);
26322      return -1;
26323    }
26324    rc = osWrite(fd, pBuf, nBuf);
26325  }while( rc<0 && errno==EINTR );
26326#endif
26327
26328  TIMER_END;
26329  OSTRACE(("WRITE   %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
26330
26331  if( rc<0 && piErrno ) *piErrno = errno;
26332  return rc;
26333}
26334
26335
26336/*
26337** Seek to the offset in id->offset then read cnt bytes into pBuf.
26338** Return the number of bytes actually read.  Update the offset.
26339**
26340** To avoid stomping the errno value on a failed write the lastErrno value
26341** is set before returning.
26342*/
26343static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
26344  return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
26345}
26346
26347
26348/*
26349** Write data from a buffer into a file.  Return SQLITE_OK on success
26350** or some other error code on failure.
26351*/
26352static int unixWrite(
26353  sqlite3_file *id,
26354  const void *pBuf,
26355  int amt,
26356  sqlite3_int64 offset
26357){
26358  unixFile *pFile = (unixFile*)id;
26359  int wrote = 0;
26360  assert( id );
26361  assert( amt>0 );
26362
26363  /* If this is a database file (not a journal, master-journal or temp
26364  ** file), the bytes in the locking range should never be read or written. */
26365#if 0
26366  assert( pFile->pUnused==0
26367       || offset>=PENDING_BYTE+512
26368       || offset+amt<=PENDING_BYTE
26369  );
26370#endif
26371
26372#ifdef SQLITE_DEBUG
26373  /* If we are doing a normal write to a database file (as opposed to
26374  ** doing a hot-journal rollback or a write to some file other than a
26375  ** normal database file) then record the fact that the database
26376  ** has changed.  If the transaction counter is modified, record that
26377  ** fact too.
26378  */
26379  if( pFile->inNormalWrite ){
26380    pFile->dbUpdate = 1;  /* The database has been modified */
26381    if( offset<=24 && offset+amt>=27 ){
26382      int rc;
26383      char oldCntr[4];
26384      SimulateIOErrorBenign(1);
26385      rc = seekAndRead(pFile, 24, oldCntr, 4);
26386      SimulateIOErrorBenign(0);
26387      if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
26388        pFile->transCntrChng = 1;  /* The transaction counter has changed */
26389      }
26390    }
26391  }
26392#endif
26393
26394#if SQLITE_MAX_MMAP_SIZE>0
26395  /* Deal with as much of this write request as possible by transfering
26396  ** data from the memory mapping using memcpy().  */
26397  if( offset<pFile->mmapSize ){
26398    if( offset+amt <= pFile->mmapSize ){
26399      memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
26400      return SQLITE_OK;
26401    }else{
26402      int nCopy = pFile->mmapSize - offset;
26403      memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
26404      pBuf = &((u8 *)pBuf)[nCopy];
26405      amt -= nCopy;
26406      offset += nCopy;
26407    }
26408  }
26409#endif
26410
26411  while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
26412    amt -= wrote;
26413    offset += wrote;
26414    pBuf = &((char*)pBuf)[wrote];
26415  }
26416  SimulateIOError(( wrote=(-1), amt=1 ));
26417  SimulateDiskfullError(( wrote=0, amt=1 ));
26418
26419  if( amt>0 ){
26420    if( wrote<0 && pFile->lastErrno!=ENOSPC ){
26421      /* lastErrno set by seekAndWrite */
26422      return SQLITE_IOERR_WRITE;
26423    }else{
26424      pFile->lastErrno = 0; /* not a system error */
26425      return SQLITE_FULL;
26426    }
26427  }
26428
26429  return SQLITE_OK;
26430}
26431
26432#ifdef SQLITE_TEST
26433/*
26434** Count the number of fullsyncs and normal syncs.  This is used to test
26435** that syncs and fullsyncs are occurring at the right times.
26436*/
26437SQLITE_API int sqlite3_sync_count = 0;
26438SQLITE_API int sqlite3_fullsync_count = 0;
26439#endif
26440
26441/*
26442** We do not trust systems to provide a working fdatasync().  Some do.
26443** Others do no.  To be safe, we will stick with the (slightly slower)
26444** fsync(). If you know that your system does support fdatasync() correctly,
26445** then simply compile with -Dfdatasync=fdatasync
26446*/
26447#if !defined(fdatasync)
26448# define fdatasync fsync
26449#endif
26450
26451/*
26452** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
26453** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
26454** only available on Mac OS X.  But that could change.
26455*/
26456#ifdef F_FULLFSYNC
26457# define HAVE_FULLFSYNC 1
26458#else
26459# define HAVE_FULLFSYNC 0
26460#endif
26461
26462
26463/*
26464** The fsync() system call does not work as advertised on many
26465** unix systems.  The following procedure is an attempt to make
26466** it work better.
26467**
26468** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
26469** for testing when we want to run through the test suite quickly.
26470** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
26471** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
26472** or power failure will likely corrupt the database file.
26473**
26474** SQLite sets the dataOnly flag if the size of the file is unchanged.
26475** The idea behind dataOnly is that it should only write the file content
26476** to disk, not the inode.  We only set dataOnly if the file size is
26477** unchanged since the file size is part of the inode.  However,
26478** Ted Ts'o tells us that fdatasync() will also write the inode if the
26479** file size has changed.  The only real difference between fdatasync()
26480** and fsync(), Ted tells us, is that fdatasync() will not flush the
26481** inode if the mtime or owner or other inode attributes have changed.
26482** We only care about the file size, not the other file attributes, so
26483** as far as SQLite is concerned, an fdatasync() is always adequate.
26484** So, we always use fdatasync() if it is available, regardless of
26485** the value of the dataOnly flag.
26486*/
26487static int full_fsync(int fd, int fullSync, int dataOnly){
26488  int rc;
26489
26490  /* The following "ifdef/elif/else/" block has the same structure as
26491  ** the one below. It is replicated here solely to avoid cluttering
26492  ** up the real code with the UNUSED_PARAMETER() macros.
26493  */
26494#ifdef SQLITE_NO_SYNC
26495  UNUSED_PARAMETER(fd);
26496  UNUSED_PARAMETER(fullSync);
26497  UNUSED_PARAMETER(dataOnly);
26498#elif HAVE_FULLFSYNC
26499  UNUSED_PARAMETER(dataOnly);
26500#else
26501  UNUSED_PARAMETER(fullSync);
26502  UNUSED_PARAMETER(dataOnly);
26503#endif
26504
26505  /* Record the number of times that we do a normal fsync() and
26506  ** FULLSYNC.  This is used during testing to verify that this procedure
26507  ** gets called with the correct arguments.
26508  */
26509#ifdef SQLITE_TEST
26510  if( fullSync ) sqlite3_fullsync_count++;
26511  sqlite3_sync_count++;
26512#endif
26513
26514  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
26515  ** no-op
26516  */
26517#ifdef SQLITE_NO_SYNC
26518  rc = SQLITE_OK;
26519#elif HAVE_FULLFSYNC
26520  if( fullSync ){
26521    rc = osFcntl(fd, F_FULLFSYNC, 0);
26522  }else{
26523    rc = 1;
26524  }
26525  /* If the FULLFSYNC failed, fall back to attempting an fsync().
26526  ** It shouldn't be possible for fullfsync to fail on the local
26527  ** file system (on OSX), so failure indicates that FULLFSYNC
26528  ** isn't supported for this file system. So, attempt an fsync
26529  ** and (for now) ignore the overhead of a superfluous fcntl call.
26530  ** It'd be better to detect fullfsync support once and avoid
26531  ** the fcntl call every time sync is called.
26532  */
26533  if( rc ) rc = fsync(fd);
26534
26535#elif defined(__APPLE__)
26536  /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
26537  ** so currently we default to the macro that redefines fdatasync to fsync
26538  */
26539  rc = fsync(fd);
26540#else
26541  rc = fdatasync(fd);
26542#if OS_VXWORKS
26543  if( rc==-1 && errno==ENOTSUP ){
26544    rc = fsync(fd);
26545  }
26546#endif /* OS_VXWORKS */
26547#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
26548
26549  if( OS_VXWORKS && rc!= -1 ){
26550    rc = 0;
26551  }
26552  return rc;
26553}
26554
26555/*
26556** Open a file descriptor to the directory containing file zFilename.
26557** If successful, *pFd is set to the opened file descriptor and
26558** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
26559** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
26560** value.
26561**
26562** The directory file descriptor is used for only one thing - to
26563** fsync() a directory to make sure file creation and deletion events
26564** are flushed to disk.  Such fsyncs are not needed on newer
26565** journaling filesystems, but are required on older filesystems.
26566**
26567** This routine can be overridden using the xSetSysCall interface.
26568** The ability to override this routine was added in support of the
26569** chromium sandbox.  Opening a directory is a security risk (we are
26570** told) so making it overrideable allows the chromium sandbox to
26571** replace this routine with a harmless no-op.  To make this routine
26572** a no-op, replace it with a stub that returns SQLITE_OK but leaves
26573** *pFd set to a negative number.
26574**
26575** If SQLITE_OK is returned, the caller is responsible for closing
26576** the file descriptor *pFd using close().
26577*/
26578static int openDirectory(const char *zFilename, int *pFd){
26579  int ii;
26580  int fd = -1;
26581  char zDirname[MAX_PATHNAME+1];
26582
26583  sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
26584  for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
26585  if( ii>0 ){
26586    zDirname[ii] = '\0';
26587    fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
26588    if( fd>=0 ){
26589      OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
26590    }
26591  }
26592  *pFd = fd;
26593  return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
26594}
26595
26596/*
26597** Make sure all writes to a particular file are committed to disk.
26598**
26599** If dataOnly==0 then both the file itself and its metadata (file
26600** size, access time, etc) are synced.  If dataOnly!=0 then only the
26601** file data is synced.
26602**
26603** Under Unix, also make sure that the directory entry for the file
26604** has been created by fsync-ing the directory that contains the file.
26605** If we do not do this and we encounter a power failure, the directory
26606** entry for the journal might not exist after we reboot.  The next
26607** SQLite to access the file will not know that the journal exists (because
26608** the directory entry for the journal was never created) and the transaction
26609** will not roll back - possibly leading to database corruption.
26610*/
26611static int unixSync(sqlite3_file *id, int flags){
26612  int rc;
26613  unixFile *pFile = (unixFile*)id;
26614
26615  int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
26616  int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
26617
26618  /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
26619  assert((flags&0x0F)==SQLITE_SYNC_NORMAL
26620      || (flags&0x0F)==SQLITE_SYNC_FULL
26621  );
26622
26623  /* Unix cannot, but some systems may return SQLITE_FULL from here. This
26624  ** line is to test that doing so does not cause any problems.
26625  */
26626  SimulateDiskfullError( return SQLITE_FULL );
26627
26628  assert( pFile );
26629  OSTRACE(("SYNC    %-3d\n", pFile->h));
26630  rc = full_fsync(pFile->h, isFullsync, isDataOnly);
26631  SimulateIOError( rc=1 );
26632  if( rc ){
26633    pFile->lastErrno = errno;
26634    return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
26635  }
26636
26637  /* Also fsync the directory containing the file if the DIRSYNC flag
26638  ** is set.  This is a one-time occurrence.  Many systems (examples: AIX)
26639  ** are unable to fsync a directory, so ignore errors on the fsync.
26640  */
26641  if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
26642    int dirfd;
26643    OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
26644            HAVE_FULLFSYNC, isFullsync));
26645    rc = osOpenDirectory(pFile->zPath, &dirfd);
26646    if( rc==SQLITE_OK && dirfd>=0 ){
26647      full_fsync(dirfd, 0, 0);
26648      robust_close(pFile, dirfd, __LINE__);
26649    }else if( rc==SQLITE_CANTOPEN ){
26650      rc = SQLITE_OK;
26651    }
26652    pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
26653  }
26654  return rc;
26655}
26656
26657/*
26658** Truncate an open file to a specified size
26659*/
26660static int unixTruncate(sqlite3_file *id, i64 nByte){
26661  unixFile *pFile = (unixFile *)id;
26662  int rc;
26663  assert( pFile );
26664  SimulateIOError( return SQLITE_IOERR_TRUNCATE );
26665
26666  /* If the user has configured a chunk-size for this file, truncate the
26667  ** file so that it consists of an integer number of chunks (i.e. the
26668  ** actual file size after the operation may be larger than the requested
26669  ** size).
26670  */
26671  if( pFile->szChunk>0 ){
26672    nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
26673  }
26674
26675  rc = robust_ftruncate(pFile->h, (off_t)nByte);
26676  if( rc ){
26677    pFile->lastErrno = errno;
26678    return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
26679  }else{
26680#ifdef SQLITE_DEBUG
26681    /* If we are doing a normal write to a database file (as opposed to
26682    ** doing a hot-journal rollback or a write to some file other than a
26683    ** normal database file) and we truncate the file to zero length,
26684    ** that effectively updates the change counter.  This might happen
26685    ** when restoring a database using the backup API from a zero-length
26686    ** source.
26687    */
26688    if( pFile->inNormalWrite && nByte==0 ){
26689      pFile->transCntrChng = 1;
26690    }
26691#endif
26692
26693    /* If the file was just truncated to a size smaller than the currently
26694    ** mapped region, reduce the effective mapping size as well. SQLite will
26695    ** use read() and write() to access data beyond this point from now on.
26696    */
26697    if( nByte<pFile->mmapSize ){
26698      pFile->mmapSize = nByte;
26699    }
26700
26701    return SQLITE_OK;
26702  }
26703}
26704
26705/*
26706** Determine the current size of a file in bytes
26707*/
26708static int unixFileSize(sqlite3_file *id, i64 *pSize){
26709  int rc;
26710  struct stat buf;
26711  assert( id );
26712  rc = osFstat(((unixFile*)id)->h, &buf);
26713  SimulateIOError( rc=1 );
26714  if( rc!=0 ){
26715    ((unixFile*)id)->lastErrno = errno;
26716    return SQLITE_IOERR_FSTAT;
26717  }
26718  *pSize = buf.st_size;
26719
26720  /* When opening a zero-size database, the findInodeInfo() procedure
26721  ** writes a single byte into that file in order to work around a bug
26722  ** in the OS-X msdos filesystem.  In order to avoid problems with upper
26723  ** layers, we need to report this file size as zero even though it is
26724  ** really 1.   Ticket #3260.
26725  */
26726  if( *pSize==1 ) *pSize = 0;
26727
26728
26729  return SQLITE_OK;
26730}
26731
26732#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
26733/*
26734** Handler for proxy-locking file-control verbs.  Defined below in the
26735** proxying locking division.
26736*/
26737static int proxyFileControl(sqlite3_file*,int,void*);
26738#endif
26739
26740/*
26741** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
26742** file-control operation.  Enlarge the database to nBytes in size
26743** (rounded up to the next chunk-size).  If the database is already
26744** nBytes or larger, this routine is a no-op.
26745*/
26746static int fcntlSizeHint(unixFile *pFile, i64 nByte){
26747  if( pFile->szChunk>0 ){
26748    i64 nSize;                    /* Required file size */
26749    struct stat buf;              /* Used to hold return values of fstat() */
26750
26751    if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
26752
26753    nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
26754    if( nSize>(i64)buf.st_size ){
26755
26756#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
26757      /* The code below is handling the return value of osFallocate()
26758      ** correctly. posix_fallocate() is defined to "returns zero on success,
26759      ** or an error number on  failure". See the manpage for details. */
26760      int err;
26761      do{
26762        err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
26763      }while( err==EINTR );
26764      if( err ) return SQLITE_IOERR_WRITE;
26765#else
26766      /* If the OS does not have posix_fallocate(), fake it. First use
26767      ** ftruncate() to set the file size, then write a single byte to
26768      ** the last byte in each block within the extended region. This
26769      ** is the same technique used by glibc to implement posix_fallocate()
26770      ** on systems that do not have a real fallocate() system call.
26771      */
26772      int nBlk = buf.st_blksize;  /* File-system block size */
26773      i64 iWrite;                 /* Next offset to write to */
26774
26775      if( robust_ftruncate(pFile->h, nSize) ){
26776        pFile->lastErrno = errno;
26777        return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
26778      }
26779      iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
26780      while( iWrite<nSize ){
26781        int nWrite = seekAndWrite(pFile, iWrite, "", 1);
26782        if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
26783        iWrite += nBlk;
26784      }
26785#endif
26786    }
26787  }
26788
26789  if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
26790    int rc;
26791    if( pFile->szChunk<=0 ){
26792      if( robust_ftruncate(pFile->h, nByte) ){
26793        pFile->lastErrno = errno;
26794        return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
26795      }
26796    }
26797
26798    rc = unixMapfile(pFile, nByte);
26799    return rc;
26800  }
26801
26802  return SQLITE_OK;
26803}
26804
26805/*
26806** If *pArg is inititially negative then this is a query.  Set *pArg to
26807** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
26808**
26809** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
26810*/
26811static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
26812  if( *pArg<0 ){
26813    *pArg = (pFile->ctrlFlags & mask)!=0;
26814  }else if( (*pArg)==0 ){
26815    pFile->ctrlFlags &= ~mask;
26816  }else{
26817    pFile->ctrlFlags |= mask;
26818  }
26819}
26820
26821/* Forward declaration */
26822static int unixGetTempname(int nBuf, char *zBuf);
26823
26824/*
26825** Information and control of an open file handle.
26826*/
26827static int unixFileControl(sqlite3_file *id, int op, void *pArg){
26828  unixFile *pFile = (unixFile*)id;
26829  switch( op ){
26830    case SQLITE_FCNTL_LOCKSTATE: {
26831      *(int*)pArg = pFile->eFileLock;
26832      return SQLITE_OK;
26833    }
26834    case SQLITE_LAST_ERRNO: {
26835      *(int*)pArg = pFile->lastErrno;
26836      return SQLITE_OK;
26837    }
26838    case SQLITE_FCNTL_CHUNK_SIZE: {
26839      pFile->szChunk = *(int *)pArg;
26840      return SQLITE_OK;
26841    }
26842    case SQLITE_FCNTL_SIZE_HINT: {
26843      int rc;
26844      SimulateIOErrorBenign(1);
26845      rc = fcntlSizeHint(pFile, *(i64 *)pArg);
26846      SimulateIOErrorBenign(0);
26847      return rc;
26848    }
26849    case SQLITE_FCNTL_PERSIST_WAL: {
26850      unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
26851      return SQLITE_OK;
26852    }
26853    case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
26854      unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
26855      return SQLITE_OK;
26856    }
26857    case SQLITE_FCNTL_VFSNAME: {
26858      *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
26859      return SQLITE_OK;
26860    }
26861    case SQLITE_FCNTL_TEMPFILENAME: {
26862      char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
26863      if( zTFile ){
26864        unixGetTempname(pFile->pVfs->mxPathname, zTFile);
26865        *(char**)pArg = zTFile;
26866      }
26867      return SQLITE_OK;
26868    }
26869    case SQLITE_FCNTL_MMAP_SIZE: {
26870      i64 newLimit = *(i64*)pArg;
26871      if( newLimit>sqlite3GlobalConfig.mxMmap ){
26872        newLimit = sqlite3GlobalConfig.mxMmap;
26873      }
26874      *(i64*)pArg = pFile->mmapSizeMax;
26875      if( newLimit>=0 ){
26876        pFile->mmapSizeMax = newLimit;
26877        if( newLimit<pFile->mmapSize ) pFile->mmapSize = newLimit;
26878      }
26879      return SQLITE_OK;
26880    }
26881#ifdef SQLITE_DEBUG
26882    /* The pager calls this method to signal that it has done
26883    ** a rollback and that the database is therefore unchanged and
26884    ** it hence it is OK for the transaction change counter to be
26885    ** unchanged.
26886    */
26887    case SQLITE_FCNTL_DB_UNCHANGED: {
26888      ((unixFile*)id)->dbUpdate = 0;
26889      return SQLITE_OK;
26890    }
26891#endif
26892#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
26893    case SQLITE_SET_LOCKPROXYFILE:
26894    case SQLITE_GET_LOCKPROXYFILE: {
26895      return proxyFileControl(id,op,pArg);
26896    }
26897#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
26898  }
26899  return SQLITE_NOTFOUND;
26900}
26901
26902/*
26903** Return the sector size in bytes of the underlying block device for
26904** the specified file. This is almost always 512 bytes, but may be
26905** larger for some devices.
26906**
26907** SQLite code assumes this function cannot fail. It also assumes that
26908** if two files are created in the same file-system directory (i.e.
26909** a database and its journal file) that the sector size will be the
26910** same for both.
26911*/
26912#ifndef __QNXNTO__
26913static int unixSectorSize(sqlite3_file *NotUsed){
26914  UNUSED_PARAMETER(NotUsed);
26915  return SQLITE_DEFAULT_SECTOR_SIZE;
26916}
26917#endif
26918
26919/*
26920** The following version of unixSectorSize() is optimized for QNX.
26921*/
26922#ifdef __QNXNTO__
26923#include <sys/dcmd_blk.h>
26924#include <sys/statvfs.h>
26925static int unixSectorSize(sqlite3_file *id){
26926  unixFile *pFile = (unixFile*)id;
26927  if( pFile->sectorSize == 0 ){
26928    struct statvfs fsInfo;
26929
26930    /* Set defaults for non-supported filesystems */
26931    pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
26932    pFile->deviceCharacteristics = 0;
26933    if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
26934      return pFile->sectorSize;
26935    }
26936
26937    if( !strcmp(fsInfo.f_basetype, "tmp") ) {
26938      pFile->sectorSize = fsInfo.f_bsize;
26939      pFile->deviceCharacteristics =
26940        SQLITE_IOCAP_ATOMIC4K |       /* All ram filesystem writes are atomic */
26941        SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
26942                                      ** the write succeeds */
26943        SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
26944                                      ** so it is ordered */
26945        0;
26946    }else if( strstr(fsInfo.f_basetype, "etfs") ){
26947      pFile->sectorSize = fsInfo.f_bsize;
26948      pFile->deviceCharacteristics =
26949        /* etfs cluster size writes are atomic */
26950        (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
26951        SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
26952                                      ** the write succeeds */
26953        SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
26954                                      ** so it is ordered */
26955        0;
26956    }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
26957      pFile->sectorSize = fsInfo.f_bsize;
26958      pFile->deviceCharacteristics =
26959        SQLITE_IOCAP_ATOMIC |         /* All filesystem writes are atomic */
26960        SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
26961                                      ** the write succeeds */
26962        SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
26963                                      ** so it is ordered */
26964        0;
26965    }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
26966      pFile->sectorSize = fsInfo.f_bsize;
26967      pFile->deviceCharacteristics =
26968        /* full bitset of atomics from max sector size and smaller */
26969        ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
26970        SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
26971                                      ** so it is ordered */
26972        0;
26973    }else if( strstr(fsInfo.f_basetype, "dos") ){
26974      pFile->sectorSize = fsInfo.f_bsize;
26975      pFile->deviceCharacteristics =
26976        /* full bitset of atomics from max sector size and smaller */
26977        ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
26978        SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
26979                                      ** so it is ordered */
26980        0;
26981    }else{
26982      pFile->deviceCharacteristics =
26983        SQLITE_IOCAP_ATOMIC512 |      /* blocks are atomic */
26984        SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
26985                                      ** the write succeeds */
26986        0;
26987    }
26988  }
26989  /* Last chance verification.  If the sector size isn't a multiple of 512
26990  ** then it isn't valid.*/
26991  if( pFile->sectorSize % 512 != 0 ){
26992    pFile->deviceCharacteristics = 0;
26993    pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
26994  }
26995  return pFile->sectorSize;
26996}
26997#endif /* __QNXNTO__ */
26998
26999/*
27000** Return the device characteristics for the file.
27001**
27002** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
27003** However, that choice is contraversial since technically the underlying
27004** file system does not always provide powersafe overwrites.  (In other
27005** words, after a power-loss event, parts of the file that were never
27006** written might end up being altered.)  However, non-PSOW behavior is very,
27007** very rare.  And asserting PSOW makes a large reduction in the amount
27008** of required I/O for journaling, since a lot of padding is eliminated.
27009**  Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
27010** available to turn it off and URI query parameter available to turn it off.
27011*/
27012static int unixDeviceCharacteristics(sqlite3_file *id){
27013  unixFile *p = (unixFile*)id;
27014  int rc = 0;
27015#ifdef __QNXNTO__
27016  if( p->sectorSize==0 ) unixSectorSize(id);
27017  rc = p->deviceCharacteristics;
27018#endif
27019  if( p->ctrlFlags & UNIXFILE_PSOW ){
27020    rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
27021  }
27022  return rc;
27023}
27024
27025#ifndef SQLITE_OMIT_WAL
27026
27027
27028/*
27029** Object used to represent an shared memory buffer.
27030**
27031** When multiple threads all reference the same wal-index, each thread
27032** has its own unixShm object, but they all point to a single instance
27033** of this unixShmNode object.  In other words, each wal-index is opened
27034** only once per process.
27035**
27036** Each unixShmNode object is connected to a single unixInodeInfo object.
27037** We could coalesce this object into unixInodeInfo, but that would mean
27038** every open file that does not use shared memory (in other words, most
27039** open files) would have to carry around this extra information.  So
27040** the unixInodeInfo object contains a pointer to this unixShmNode object
27041** and the unixShmNode object is created only when needed.
27042**
27043** unixMutexHeld() must be true when creating or destroying
27044** this object or while reading or writing the following fields:
27045**
27046**      nRef
27047**
27048** The following fields are read-only after the object is created:
27049**
27050**      fid
27051**      zFilename
27052**
27053** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
27054** unixMutexHeld() is true when reading or writing any other field
27055** in this structure.
27056*/
27057struct unixShmNode {
27058  unixInodeInfo *pInode;     /* unixInodeInfo that owns this SHM node */
27059  sqlite3_mutex *mutex;      /* Mutex to access this object */
27060  char *zFilename;           /* Name of the mmapped file */
27061  int h;                     /* Open file descriptor */
27062  int szRegion;              /* Size of shared-memory regions */
27063  u16 nRegion;               /* Size of array apRegion */
27064  u8 isReadonly;             /* True if read-only */
27065  char **apRegion;           /* Array of mapped shared-memory regions */
27066  int nRef;                  /* Number of unixShm objects pointing to this */
27067  unixShm *pFirst;           /* All unixShm objects pointing to this */
27068#ifdef SQLITE_DEBUG
27069  u8 exclMask;               /* Mask of exclusive locks held */
27070  u8 sharedMask;             /* Mask of shared locks held */
27071  u8 nextShmId;              /* Next available unixShm.id value */
27072#endif
27073};
27074
27075/*
27076** Structure used internally by this VFS to record the state of an
27077** open shared memory connection.
27078**
27079** The following fields are initialized when this object is created and
27080** are read-only thereafter:
27081**
27082**    unixShm.pFile
27083**    unixShm.id
27084**
27085** All other fields are read/write.  The unixShm.pFile->mutex must be held
27086** while accessing any read/write fields.
27087*/
27088struct unixShm {
27089  unixShmNode *pShmNode;     /* The underlying unixShmNode object */
27090  unixShm *pNext;            /* Next unixShm with the same unixShmNode */
27091  u8 hasMutex;               /* True if holding the unixShmNode mutex */
27092  u8 id;                     /* Id of this connection within its unixShmNode */
27093  u16 sharedMask;            /* Mask of shared locks held */
27094  u16 exclMask;              /* Mask of exclusive locks held */
27095};
27096
27097/*
27098** Constants used for locking
27099*/
27100#define UNIX_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)         /* first lock byte */
27101#define UNIX_SHM_DMS    (UNIX_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
27102
27103/*
27104** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
27105**
27106** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
27107** otherwise.
27108*/
27109static int unixShmSystemLock(
27110  unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
27111  int lockType,          /* F_UNLCK, F_RDLCK, or F_WRLCK */
27112  int ofst,              /* First byte of the locking range */
27113  int n                  /* Number of bytes to lock */
27114){
27115  struct flock f;       /* The posix advisory locking structure */
27116  int rc = SQLITE_OK;   /* Result code form fcntl() */
27117
27118  /* Access to the unixShmNode object is serialized by the caller */
27119  assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
27120
27121  /* Shared locks never span more than one byte */
27122  assert( n==1 || lockType!=F_RDLCK );
27123
27124  /* Locks are within range */
27125  assert( n>=1 && n<SQLITE_SHM_NLOCK );
27126
27127  if( pShmNode->h>=0 ){
27128    /* Initialize the locking parameters */
27129    memset(&f, 0, sizeof(f));
27130    f.l_type = lockType;
27131    f.l_whence = SEEK_SET;
27132    f.l_start = ofst;
27133    f.l_len = n;
27134
27135    rc = osFcntl(pShmNode->h, F_SETLK, &f);
27136    rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
27137  }
27138
27139  /* Update the global lock state and do debug tracing */
27140#ifdef SQLITE_DEBUG
27141  { u16 mask;
27142  OSTRACE(("SHM-LOCK "));
27143  mask = (1<<(ofst+n)) - (1<<ofst);
27144  if( rc==SQLITE_OK ){
27145    if( lockType==F_UNLCK ){
27146      OSTRACE(("unlock %d ok", ofst));
27147      pShmNode->exclMask &= ~mask;
27148      pShmNode->sharedMask &= ~mask;
27149    }else if( lockType==F_RDLCK ){
27150      OSTRACE(("read-lock %d ok", ofst));
27151      pShmNode->exclMask &= ~mask;
27152      pShmNode->sharedMask |= mask;
27153    }else{
27154      assert( lockType==F_WRLCK );
27155      OSTRACE(("write-lock %d ok", ofst));
27156      pShmNode->exclMask |= mask;
27157      pShmNode->sharedMask &= ~mask;
27158    }
27159  }else{
27160    if( lockType==F_UNLCK ){
27161      OSTRACE(("unlock %d failed", ofst));
27162    }else if( lockType==F_RDLCK ){
27163      OSTRACE(("read-lock failed"));
27164    }else{
27165      assert( lockType==F_WRLCK );
27166      OSTRACE(("write-lock %d failed", ofst));
27167    }
27168  }
27169  OSTRACE((" - afterwards %03x,%03x\n",
27170           pShmNode->sharedMask, pShmNode->exclMask));
27171  }
27172#endif
27173
27174  return rc;
27175}
27176
27177
27178/*
27179** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
27180**
27181** This is not a VFS shared-memory method; it is a utility function called
27182** by VFS shared-memory methods.
27183*/
27184static void unixShmPurge(unixFile *pFd){
27185  unixShmNode *p = pFd->pInode->pShmNode;
27186  assert( unixMutexHeld() );
27187  if( p && p->nRef==0 ){
27188    int i;
27189    assert( p->pInode==pFd->pInode );
27190    sqlite3_mutex_free(p->mutex);
27191    for(i=0; i<p->nRegion; i++){
27192      if( p->h>=0 ){
27193        osMunmap(p->apRegion[i], p->szRegion);
27194      }else{
27195        sqlite3_free(p->apRegion[i]);
27196      }
27197    }
27198    sqlite3_free(p->apRegion);
27199    if( p->h>=0 ){
27200      robust_close(pFd, p->h, __LINE__);
27201      p->h = -1;
27202    }
27203    p->pInode->pShmNode = 0;
27204    sqlite3_free(p);
27205  }
27206}
27207
27208/*
27209** Open a shared-memory area associated with open database file pDbFd.
27210** This particular implementation uses mmapped files.
27211**
27212** The file used to implement shared-memory is in the same directory
27213** as the open database file and has the same name as the open database
27214** file with the "-shm" suffix added.  For example, if the database file
27215** is "/home/user1/config.db" then the file that is created and mmapped
27216** for shared memory will be called "/home/user1/config.db-shm".
27217**
27218** Another approach to is to use files in /dev/shm or /dev/tmp or an
27219** some other tmpfs mount. But if a file in a different directory
27220** from the database file is used, then differing access permissions
27221** or a chroot() might cause two different processes on the same
27222** database to end up using different files for shared memory -
27223** meaning that their memory would not really be shared - resulting
27224** in database corruption.  Nevertheless, this tmpfs file usage
27225** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
27226** or the equivalent.  The use of the SQLITE_SHM_DIRECTORY compile-time
27227** option results in an incompatible build of SQLite;  builds of SQLite
27228** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
27229** same database file at the same time, database corruption will likely
27230** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
27231** "unsupported" and may go away in a future SQLite release.
27232**
27233** When opening a new shared-memory file, if no other instances of that
27234** file are currently open, in this process or in other processes, then
27235** the file must be truncated to zero length or have its header cleared.
27236**
27237** If the original database file (pDbFd) is using the "unix-excl" VFS
27238** that means that an exclusive lock is held on the database file and
27239** that no other processes are able to read or write the database.  In
27240** that case, we do not really need shared memory.  No shared memory
27241** file is created.  The shared memory will be simulated with heap memory.
27242*/
27243static int unixOpenSharedMemory(unixFile *pDbFd){
27244  struct unixShm *p = 0;          /* The connection to be opened */
27245  struct unixShmNode *pShmNode;   /* The underlying mmapped file */
27246  int rc;                         /* Result code */
27247  unixInodeInfo *pInode;          /* The inode of fd */
27248  char *zShmFilename;             /* Name of the file used for SHM */
27249  int nShmFilename;               /* Size of the SHM filename in bytes */
27250
27251  /* Allocate space for the new unixShm object. */
27252  p = sqlite3_malloc( sizeof(*p) );
27253  if( p==0 ) return SQLITE_NOMEM;
27254  memset(p, 0, sizeof(*p));
27255  assert( pDbFd->pShm==0 );
27256
27257  /* Check to see if a unixShmNode object already exists. Reuse an existing
27258  ** one if present. Create a new one if necessary.
27259  */
27260  unixEnterMutex();
27261  pInode = pDbFd->pInode;
27262  pShmNode = pInode->pShmNode;
27263  if( pShmNode==0 ){
27264    struct stat sStat;                 /* fstat() info for database file */
27265
27266    /* Call fstat() to figure out the permissions on the database file. If
27267    ** a new *-shm file is created, an attempt will be made to create it
27268    ** with the same permissions.
27269    */
27270    if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
27271      rc = SQLITE_IOERR_FSTAT;
27272      goto shm_open_err;
27273    }
27274
27275#ifdef SQLITE_SHM_DIRECTORY
27276    nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
27277#else
27278    nShmFilename = 6 + (int)strlen(pDbFd->zPath);
27279#endif
27280    pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
27281    if( pShmNode==0 ){
27282      rc = SQLITE_NOMEM;
27283      goto shm_open_err;
27284    }
27285    memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
27286    zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
27287#ifdef SQLITE_SHM_DIRECTORY
27288    sqlite3_snprintf(nShmFilename, zShmFilename,
27289                     SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
27290                     (u32)sStat.st_ino, (u32)sStat.st_dev);
27291#else
27292    sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
27293    sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
27294#endif
27295    pShmNode->h = -1;
27296    pDbFd->pInode->pShmNode = pShmNode;
27297    pShmNode->pInode = pDbFd->pInode;
27298    pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
27299    if( pShmNode->mutex==0 ){
27300      rc = SQLITE_NOMEM;
27301      goto shm_open_err;
27302    }
27303
27304    if( pInode->bProcessLock==0 ){
27305      int openFlags = O_RDWR | O_CREAT;
27306      if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
27307        openFlags = O_RDONLY;
27308        pShmNode->isReadonly = 1;
27309      }
27310      pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
27311      if( pShmNode->h<0 ){
27312        rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
27313        goto shm_open_err;
27314      }
27315
27316      /* If this process is running as root, make sure that the SHM file
27317      ** is owned by the same user that owns the original database.  Otherwise,
27318      ** the original owner will not be able to connect.
27319      */
27320      osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
27321
27322      /* Check to see if another process is holding the dead-man switch.
27323      ** If not, truncate the file to zero length.
27324      */
27325      rc = SQLITE_OK;
27326      if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
27327        if( robust_ftruncate(pShmNode->h, 0) ){
27328          rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
27329        }
27330      }
27331      if( rc==SQLITE_OK ){
27332        rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
27333      }
27334      if( rc ) goto shm_open_err;
27335    }
27336  }
27337
27338  /* Make the new connection a child of the unixShmNode */
27339  p->pShmNode = pShmNode;
27340#ifdef SQLITE_DEBUG
27341  p->id = pShmNode->nextShmId++;
27342#endif
27343  pShmNode->nRef++;
27344  pDbFd->pShm = p;
27345  unixLeaveMutex();
27346
27347  /* The reference count on pShmNode has already been incremented under
27348  ** the cover of the unixEnterMutex() mutex and the pointer from the
27349  ** new (struct unixShm) object to the pShmNode has been set. All that is
27350  ** left to do is to link the new object into the linked list starting
27351  ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
27352  ** mutex.
27353  */
27354  sqlite3_mutex_enter(pShmNode->mutex);
27355  p->pNext = pShmNode->pFirst;
27356  pShmNode->pFirst = p;
27357  sqlite3_mutex_leave(pShmNode->mutex);
27358  return SQLITE_OK;
27359
27360  /* Jump here on any error */
27361shm_open_err:
27362  unixShmPurge(pDbFd);       /* This call frees pShmNode if required */
27363  sqlite3_free(p);
27364  unixLeaveMutex();
27365  return rc;
27366}
27367
27368/*
27369** This function is called to obtain a pointer to region iRegion of the
27370** shared-memory associated with the database file fd. Shared-memory regions
27371** are numbered starting from zero. Each shared-memory region is szRegion
27372** bytes in size.
27373**
27374** If an error occurs, an error code is returned and *pp is set to NULL.
27375**
27376** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
27377** region has not been allocated (by any client, including one running in a
27378** separate process), then *pp is set to NULL and SQLITE_OK returned. If
27379** bExtend is non-zero and the requested shared-memory region has not yet
27380** been allocated, it is allocated by this function.
27381**
27382** If the shared-memory region has already been allocated or is allocated by
27383** this call as described above, then it is mapped into this processes
27384** address space (if it is not already), *pp is set to point to the mapped
27385** memory and SQLITE_OK returned.
27386*/
27387static int unixShmMap(
27388  sqlite3_file *fd,               /* Handle open on database file */
27389  int iRegion,                    /* Region to retrieve */
27390  int szRegion,                   /* Size of regions */
27391  int bExtend,                    /* True to extend file if necessary */
27392  void volatile **pp              /* OUT: Mapped memory */
27393){
27394  unixFile *pDbFd = (unixFile*)fd;
27395  unixShm *p;
27396  unixShmNode *pShmNode;
27397  int rc = SQLITE_OK;
27398
27399  /* If the shared-memory file has not yet been opened, open it now. */
27400  if( pDbFd->pShm==0 ){
27401    rc = unixOpenSharedMemory(pDbFd);
27402    if( rc!=SQLITE_OK ) return rc;
27403  }
27404
27405  p = pDbFd->pShm;
27406  pShmNode = p->pShmNode;
27407  sqlite3_mutex_enter(pShmNode->mutex);
27408  assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
27409  assert( pShmNode->pInode==pDbFd->pInode );
27410  assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
27411  assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
27412
27413  if( pShmNode->nRegion<=iRegion ){
27414    char **apNew;                      /* New apRegion[] array */
27415    int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
27416    struct stat sStat;                 /* Used by fstat() */
27417
27418    pShmNode->szRegion = szRegion;
27419
27420    if( pShmNode->h>=0 ){
27421      /* The requested region is not mapped into this processes address space.
27422      ** Check to see if it has been allocated (i.e. if the wal-index file is
27423      ** large enough to contain the requested region).
27424      */
27425      if( osFstat(pShmNode->h, &sStat) ){
27426        rc = SQLITE_IOERR_SHMSIZE;
27427        goto shmpage_out;
27428      }
27429
27430      if( sStat.st_size<nByte ){
27431        /* The requested memory region does not exist. If bExtend is set to
27432        ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
27433        */
27434        if( !bExtend ){
27435          goto shmpage_out;
27436        }
27437
27438        /* Alternatively, if bExtend is true, extend the file. Do this by
27439        ** writing a single byte to the end of each (OS) page being
27440        ** allocated or extended. Technically, we need only write to the
27441        ** last page in order to extend the file. But writing to all new
27442        ** pages forces the OS to allocate them immediately, which reduces
27443        ** the chances of SIGBUS while accessing the mapped region later on.
27444        */
27445        else{
27446          static const int pgsz = 4096;
27447          int iPg;
27448
27449          /* Write to the last byte of each newly allocated or extended page */
27450          assert( (nByte % pgsz)==0 );
27451          for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
27452            if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, 0)!=1 ){
27453              const char *zFile = pShmNode->zFilename;
27454              rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
27455              goto shmpage_out;
27456            }
27457          }
27458        }
27459      }
27460    }
27461
27462    /* Map the requested memory region into this processes address space. */
27463    apNew = (char **)sqlite3_realloc(
27464        pShmNode->apRegion, (iRegion+1)*sizeof(char *)
27465    );
27466    if( !apNew ){
27467      rc = SQLITE_IOERR_NOMEM;
27468      goto shmpage_out;
27469    }
27470    pShmNode->apRegion = apNew;
27471    while(pShmNode->nRegion<=iRegion){
27472      void *pMem;
27473      if( pShmNode->h>=0 ){
27474        pMem = osMmap(0, szRegion,
27475            pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
27476            MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
27477        );
27478        if( pMem==MAP_FAILED ){
27479          rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
27480          goto shmpage_out;
27481        }
27482      }else{
27483        pMem = sqlite3_malloc(szRegion);
27484        if( pMem==0 ){
27485          rc = SQLITE_NOMEM;
27486          goto shmpage_out;
27487        }
27488        memset(pMem, 0, szRegion);
27489      }
27490      pShmNode->apRegion[pShmNode->nRegion] = pMem;
27491      pShmNode->nRegion++;
27492    }
27493  }
27494
27495shmpage_out:
27496  if( pShmNode->nRegion>iRegion ){
27497    *pp = pShmNode->apRegion[iRegion];
27498  }else{
27499    *pp = 0;
27500  }
27501  if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
27502  sqlite3_mutex_leave(pShmNode->mutex);
27503  return rc;
27504}
27505
27506/*
27507** Change the lock state for a shared-memory segment.
27508**
27509** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
27510** different here than in posix.  In xShmLock(), one can go from unlocked
27511** to shared and back or from unlocked to exclusive and back.  But one may
27512** not go from shared to exclusive or from exclusive to shared.
27513*/
27514static int unixShmLock(
27515  sqlite3_file *fd,          /* Database file holding the shared memory */
27516  int ofst,                  /* First lock to acquire or release */
27517  int n,                     /* Number of locks to acquire or release */
27518  int flags                  /* What to do with the lock */
27519){
27520  unixFile *pDbFd = (unixFile*)fd;      /* Connection holding shared memory */
27521  unixShm *p = pDbFd->pShm;             /* The shared memory being locked */
27522  unixShm *pX;                          /* For looping over all siblings */
27523  unixShmNode *pShmNode = p->pShmNode;  /* The underlying file iNode */
27524  int rc = SQLITE_OK;                   /* Result code */
27525  u16 mask;                             /* Mask of locks to take or release */
27526
27527  assert( pShmNode==pDbFd->pInode->pShmNode );
27528  assert( pShmNode->pInode==pDbFd->pInode );
27529  assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
27530  assert( n>=1 );
27531  assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
27532       || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
27533       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
27534       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
27535  assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
27536  assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
27537  assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
27538
27539  mask = (1<<(ofst+n)) - (1<<ofst);
27540  assert( n>1 || mask==(1<<ofst) );
27541  sqlite3_mutex_enter(pShmNode->mutex);
27542  if( flags & SQLITE_SHM_UNLOCK ){
27543    u16 allMask = 0; /* Mask of locks held by siblings */
27544
27545    /* See if any siblings hold this same lock */
27546    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
27547      if( pX==p ) continue;
27548      assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
27549      allMask |= pX->sharedMask;
27550    }
27551
27552    /* Unlock the system-level locks */
27553    if( (mask & allMask)==0 ){
27554      rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
27555    }else{
27556      rc = SQLITE_OK;
27557    }
27558
27559    /* Undo the local locks */
27560    if( rc==SQLITE_OK ){
27561      p->exclMask &= ~mask;
27562      p->sharedMask &= ~mask;
27563    }
27564  }else if( flags & SQLITE_SHM_SHARED ){
27565    u16 allShared = 0;  /* Union of locks held by connections other than "p" */
27566
27567    /* Find out which shared locks are already held by sibling connections.
27568    ** If any sibling already holds an exclusive lock, go ahead and return
27569    ** SQLITE_BUSY.
27570    */
27571    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
27572      if( (pX->exclMask & mask)!=0 ){
27573        rc = SQLITE_BUSY;
27574        break;
27575      }
27576      allShared |= pX->sharedMask;
27577    }
27578
27579    /* Get shared locks at the system level, if necessary */
27580    if( rc==SQLITE_OK ){
27581      if( (allShared & mask)==0 ){
27582        rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
27583      }else{
27584        rc = SQLITE_OK;
27585      }
27586    }
27587
27588    /* Get the local shared locks */
27589    if( rc==SQLITE_OK ){
27590      p->sharedMask |= mask;
27591    }
27592  }else{
27593    /* Make sure no sibling connections hold locks that will block this
27594    ** lock.  If any do, return SQLITE_BUSY right away.
27595    */
27596    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
27597      if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
27598        rc = SQLITE_BUSY;
27599        break;
27600      }
27601    }
27602
27603    /* Get the exclusive locks at the system level.  Then if successful
27604    ** also mark the local connection as being locked.
27605    */
27606    if( rc==SQLITE_OK ){
27607      rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
27608      if( rc==SQLITE_OK ){
27609        assert( (p->sharedMask & mask)==0 );
27610        p->exclMask |= mask;
27611      }
27612    }
27613  }
27614  sqlite3_mutex_leave(pShmNode->mutex);
27615  OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
27616           p->id, getpid(), p->sharedMask, p->exclMask));
27617  return rc;
27618}
27619
27620/*
27621** Implement a memory barrier or memory fence on shared memory.
27622**
27623** All loads and stores begun before the barrier must complete before
27624** any load or store begun after the barrier.
27625*/
27626static void unixShmBarrier(
27627  sqlite3_file *fd                /* Database file holding the shared memory */
27628){
27629  UNUSED_PARAMETER(fd);
27630  unixEnterMutex();
27631  unixLeaveMutex();
27632}
27633
27634/*
27635** Close a connection to shared-memory.  Delete the underlying
27636** storage if deleteFlag is true.
27637**
27638** If there is no shared memory associated with the connection then this
27639** routine is a harmless no-op.
27640*/
27641static int unixShmUnmap(
27642  sqlite3_file *fd,               /* The underlying database file */
27643  int deleteFlag                  /* Delete shared-memory if true */
27644){
27645  unixShm *p;                     /* The connection to be closed */
27646  unixShmNode *pShmNode;          /* The underlying shared-memory file */
27647  unixShm **pp;                   /* For looping over sibling connections */
27648  unixFile *pDbFd;                /* The underlying database file */
27649
27650  pDbFd = (unixFile*)fd;
27651  p = pDbFd->pShm;
27652  if( p==0 ) return SQLITE_OK;
27653  pShmNode = p->pShmNode;
27654
27655  assert( pShmNode==pDbFd->pInode->pShmNode );
27656  assert( pShmNode->pInode==pDbFd->pInode );
27657
27658  /* Remove connection p from the set of connections associated
27659  ** with pShmNode */
27660  sqlite3_mutex_enter(pShmNode->mutex);
27661  for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
27662  *pp = p->pNext;
27663
27664  /* Free the connection p */
27665  sqlite3_free(p);
27666  pDbFd->pShm = 0;
27667  sqlite3_mutex_leave(pShmNode->mutex);
27668
27669  /* If pShmNode->nRef has reached 0, then close the underlying
27670  ** shared-memory file, too */
27671  unixEnterMutex();
27672  assert( pShmNode->nRef>0 );
27673  pShmNode->nRef--;
27674  if( pShmNode->nRef==0 ){
27675    if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
27676    unixShmPurge(pDbFd);
27677  }
27678  unixLeaveMutex();
27679
27680  return SQLITE_OK;
27681}
27682
27683
27684#else
27685# define unixShmMap     0
27686# define unixShmLock    0
27687# define unixShmBarrier 0
27688# define unixShmUnmap   0
27689#endif /* #ifndef SQLITE_OMIT_WAL */
27690
27691/*
27692** If it is currently memory mapped, unmap file pFd.
27693*/
27694static void unixUnmapfile(unixFile *pFd){
27695  assert( pFd->nFetchOut==0 );
27696#if SQLITE_MAX_MMAP_SIZE>0
27697  if( pFd->pMapRegion ){
27698    osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
27699    pFd->pMapRegion = 0;
27700    pFd->mmapSize = 0;
27701    pFd->mmapSizeActual = 0;
27702  }
27703#endif
27704}
27705
27706#if SQLITE_MAX_MMAP_SIZE>0
27707/*
27708** Return the system page size.
27709*/
27710static int unixGetPagesize(void){
27711#if HAVE_MREMAP
27712  return 512;
27713#elif defined(_BSD_SOURCE)
27714  return getpagesize();
27715#else
27716  return (int)sysconf(_SC_PAGESIZE);
27717#endif
27718}
27719#endif /* SQLITE_MAX_MMAP_SIZE>0 */
27720
27721#if SQLITE_MAX_MMAP_SIZE>0
27722/*
27723** Attempt to set the size of the memory mapping maintained by file
27724** descriptor pFd to nNew bytes. Any existing mapping is discarded.
27725**
27726** If successful, this function sets the following variables:
27727**
27728**       unixFile.pMapRegion
27729**       unixFile.mmapSize
27730**       unixFile.mmapSizeActual
27731**
27732** If unsuccessful, an error message is logged via sqlite3_log() and
27733** the three variables above are zeroed. In this case SQLite should
27734** continue accessing the database using the xRead() and xWrite()
27735** methods.
27736*/
27737static void unixRemapfile(
27738  unixFile *pFd,                  /* File descriptor object */
27739  i64 nNew                        /* Required mapping size */
27740){
27741  const char *zErr = "mmap";
27742  int h = pFd->h;                      /* File descriptor open on db file */
27743  u8 *pOrig = (u8 *)pFd->pMapRegion;   /* Pointer to current file mapping */
27744  i64 nOrig = pFd->mmapSizeActual;     /* Size of pOrig region in bytes */
27745  u8 *pNew = 0;                        /* Location of new mapping */
27746  int flags = PROT_READ;               /* Flags to pass to mmap() */
27747
27748  assert( pFd->nFetchOut==0 );
27749  assert( nNew>pFd->mmapSize );
27750  assert( nNew<=pFd->mmapSizeMax );
27751  assert( nNew>0 );
27752  assert( pFd->mmapSizeActual>=pFd->mmapSize );
27753  assert( MAP_FAILED!=0 );
27754
27755  if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
27756
27757  if( pOrig ){
27758    const int szSyspage = unixGetPagesize();
27759    i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
27760    u8 *pReq = &pOrig[nReuse];
27761
27762    /* Unmap any pages of the existing mapping that cannot be reused. */
27763    if( nReuse!=nOrig ){
27764      osMunmap(pReq, nOrig-nReuse);
27765    }
27766
27767#if HAVE_MREMAP
27768    pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
27769    zErr = "mremap";
27770#else
27771    pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
27772    if( pNew!=MAP_FAILED ){
27773      if( pNew!=pReq ){
27774        osMunmap(pNew, nNew - nReuse);
27775        pNew = 0;
27776      }else{
27777        pNew = pOrig;
27778      }
27779    }
27780#endif
27781
27782    /* The attempt to extend the existing mapping failed. Free it. */
27783    if( pNew==MAP_FAILED || pNew==0 ){
27784      osMunmap(pOrig, nReuse);
27785    }
27786  }
27787
27788  /* If pNew is still NULL, try to create an entirely new mapping. */
27789  if( pNew==0 ){
27790    pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
27791  }
27792
27793  if( pNew==MAP_FAILED ){
27794    pNew = 0;
27795    nNew = 0;
27796    unixLogError(SQLITE_OK, zErr, pFd->zPath);
27797
27798    /* If the mmap() above failed, assume that all subsequent mmap() calls
27799    ** will probably fail too. Fall back to using xRead/xWrite exclusively
27800    ** in this case.  */
27801    pFd->mmapSizeMax = 0;
27802  }
27803  pFd->pMapRegion = (void *)pNew;
27804  pFd->mmapSize = pFd->mmapSizeActual = nNew;
27805}
27806#endif
27807
27808/*
27809** Memory map or remap the file opened by file-descriptor pFd (if the file
27810** is already mapped, the existing mapping is replaced by the new). Or, if
27811** there already exists a mapping for this file, and there are still
27812** outstanding xFetch() references to it, this function is a no-op.
27813**
27814** If parameter nByte is non-negative, then it is the requested size of
27815** the mapping to create. Otherwise, if nByte is less than zero, then the
27816** requested size is the size of the file on disk. The actual size of the
27817** created mapping is either the requested size or the value configured
27818** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
27819**
27820** SQLITE_OK is returned if no error occurs (even if the mapping is not
27821** recreated as a result of outstanding references) or an SQLite error
27822** code otherwise.
27823*/
27824static int unixMapfile(unixFile *pFd, i64 nByte){
27825#if SQLITE_MAX_MMAP_SIZE>0
27826  i64 nMap = nByte;
27827  int rc;
27828
27829  assert( nMap>=0 || pFd->nFetchOut==0 );
27830  if( pFd->nFetchOut>0 ) return SQLITE_OK;
27831
27832  if( nMap<0 ){
27833    struct stat statbuf;          /* Low-level file information */
27834    rc = osFstat(pFd->h, &statbuf);
27835    if( rc!=SQLITE_OK ){
27836      return SQLITE_IOERR_FSTAT;
27837    }
27838    nMap = statbuf.st_size;
27839  }
27840  if( nMap>pFd->mmapSizeMax ){
27841    nMap = pFd->mmapSizeMax;
27842  }
27843
27844  if( nMap!=pFd->mmapSize ){
27845    if( nMap>0 ){
27846      unixRemapfile(pFd, nMap);
27847    }else{
27848      unixUnmapfile(pFd);
27849    }
27850  }
27851#endif
27852
27853  return SQLITE_OK;
27854}
27855
27856/*
27857** If possible, return a pointer to a mapping of file fd starting at offset
27858** iOff. The mapping must be valid for at least nAmt bytes.
27859**
27860** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
27861** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
27862** Finally, if an error does occur, return an SQLite error code. The final
27863** value of *pp is undefined in this case.
27864**
27865** If this function does return a pointer, the caller must eventually
27866** release the reference by calling unixUnfetch().
27867*/
27868static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
27869#if SQLITE_MAX_MMAP_SIZE>0
27870  unixFile *pFd = (unixFile *)fd;   /* The underlying database file */
27871#endif
27872  *pp = 0;
27873
27874#if SQLITE_MAX_MMAP_SIZE>0
27875  if( pFd->mmapSizeMax>0 ){
27876    if( pFd->pMapRegion==0 ){
27877      int rc = unixMapfile(pFd, -1);
27878      if( rc!=SQLITE_OK ) return rc;
27879    }
27880    if( pFd->mmapSize >= iOff+nAmt ){
27881      *pp = &((u8 *)pFd->pMapRegion)[iOff];
27882      pFd->nFetchOut++;
27883    }
27884  }
27885#endif
27886  return SQLITE_OK;
27887}
27888
27889/*
27890** If the third argument is non-NULL, then this function releases a
27891** reference obtained by an earlier call to unixFetch(). The second
27892** argument passed to this function must be the same as the corresponding
27893** argument that was passed to the unixFetch() invocation.
27894**
27895** Or, if the third argument is NULL, then this function is being called
27896** to inform the VFS layer that, according to POSIX, any existing mapping
27897** may now be invalid and should be unmapped.
27898*/
27899static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
27900  unixFile *pFd = (unixFile *)fd;   /* The underlying database file */
27901  UNUSED_PARAMETER(iOff);
27902
27903  /* If p==0 (unmap the entire file) then there must be no outstanding
27904  ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
27905  ** then there must be at least one outstanding.  */
27906  assert( (p==0)==(pFd->nFetchOut==0) );
27907
27908  /* If p!=0, it must match the iOff value. */
27909  assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
27910
27911  if( p ){
27912    pFd->nFetchOut--;
27913  }else{
27914    unixUnmapfile(pFd);
27915  }
27916
27917  assert( pFd->nFetchOut>=0 );
27918  return SQLITE_OK;
27919}
27920
27921/*
27922** Here ends the implementation of all sqlite3_file methods.
27923**
27924********************** End sqlite3_file Methods *******************************
27925******************************************************************************/
27926
27927/*
27928** This division contains definitions of sqlite3_io_methods objects that
27929** implement various file locking strategies.  It also contains definitions
27930** of "finder" functions.  A finder-function is used to locate the appropriate
27931** sqlite3_io_methods object for a particular database file.  The pAppData
27932** field of the sqlite3_vfs VFS objects are initialized to be pointers to
27933** the correct finder-function for that VFS.
27934**
27935** Most finder functions return a pointer to a fixed sqlite3_io_methods
27936** object.  The only interesting finder-function is autolockIoFinder, which
27937** looks at the filesystem type and tries to guess the best locking
27938** strategy from that.
27939**
27940** For finder-funtion F, two objects are created:
27941**
27942**    (1) The real finder-function named "FImpt()".
27943**
27944**    (2) A constant pointer to this function named just "F".
27945**
27946**
27947** A pointer to the F pointer is used as the pAppData value for VFS
27948** objects.  We have to do this instead of letting pAppData point
27949** directly at the finder-function since C90 rules prevent a void*
27950** from be cast into a function pointer.
27951**
27952**
27953** Each instance of this macro generates two objects:
27954**
27955**   *  A constant sqlite3_io_methods object call METHOD that has locking
27956**      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
27957**
27958**   *  An I/O method finder function called FINDER that returns a pointer
27959**      to the METHOD object in the previous bullet.
27960*/
27961#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK)      \
27962static const sqlite3_io_methods METHOD = {                                   \
27963   VERSION,                    /* iVersion */                                \
27964   CLOSE,                      /* xClose */                                  \
27965   unixRead,                   /* xRead */                                   \
27966   unixWrite,                  /* xWrite */                                  \
27967   unixTruncate,               /* xTruncate */                               \
27968   unixSync,                   /* xSync */                                   \
27969   unixFileSize,               /* xFileSize */                               \
27970   LOCK,                       /* xLock */                                   \
27971   UNLOCK,                     /* xUnlock */                                 \
27972   CKLOCK,                     /* xCheckReservedLock */                      \
27973   unixFileControl,            /* xFileControl */                            \
27974   unixSectorSize,             /* xSectorSize */                             \
27975   unixDeviceCharacteristics,  /* xDeviceCapabilities */                     \
27976   unixShmMap,                 /* xShmMap */                                 \
27977   unixShmLock,                /* xShmLock */                                \
27978   unixShmBarrier,             /* xShmBarrier */                             \
27979   unixShmUnmap,               /* xShmUnmap */                               \
27980   unixFetch,                  /* xFetch */                                  \
27981   unixUnfetch,                /* xUnfetch */                                \
27982};                                                                           \
27983static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
27984  UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
27985  return &METHOD;                                                            \
27986}                                                                            \
27987static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p)    \
27988    = FINDER##Impl;
27989
27990/*
27991** Here are all of the sqlite3_io_methods objects for each of the
27992** locking strategies.  Functions that return pointers to these methods
27993** are also created.
27994*/
27995IOMETHODS(
27996  posixIoFinder,            /* Finder function name */
27997  posixIoMethods,           /* sqlite3_io_methods object name */
27998  3,                        /* shared memory and mmap are enabled */
27999  unixClose,                /* xClose method */
28000  unixLock,                 /* xLock method */
28001  unixUnlock,               /* xUnlock method */
28002  unixCheckReservedLock     /* xCheckReservedLock method */
28003)
28004IOMETHODS(
28005  nolockIoFinder,           /* Finder function name */
28006  nolockIoMethods,          /* sqlite3_io_methods object name */
28007  1,                        /* shared memory is disabled */
28008  nolockClose,              /* xClose method */
28009  nolockLock,               /* xLock method */
28010  nolockUnlock,             /* xUnlock method */
28011  nolockCheckReservedLock   /* xCheckReservedLock method */
28012)
28013IOMETHODS(
28014  dotlockIoFinder,          /* Finder function name */
28015  dotlockIoMethods,         /* sqlite3_io_methods object name */
28016  1,                        /* shared memory is disabled */
28017  dotlockClose,             /* xClose method */
28018  dotlockLock,              /* xLock method */
28019  dotlockUnlock,            /* xUnlock method */
28020  dotlockCheckReservedLock  /* xCheckReservedLock method */
28021)
28022
28023#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
28024IOMETHODS(
28025  flockIoFinder,            /* Finder function name */
28026  flockIoMethods,           /* sqlite3_io_methods object name */
28027  1,                        /* shared memory is disabled */
28028  flockClose,               /* xClose method */
28029  flockLock,                /* xLock method */
28030  flockUnlock,              /* xUnlock method */
28031  flockCheckReservedLock    /* xCheckReservedLock method */
28032)
28033#endif
28034
28035#if OS_VXWORKS
28036IOMETHODS(
28037  semIoFinder,              /* Finder function name */
28038  semIoMethods,             /* sqlite3_io_methods object name */
28039  1,                        /* shared memory is disabled */
28040  semClose,                 /* xClose method */
28041  semLock,                  /* xLock method */
28042  semUnlock,                /* xUnlock method */
28043  semCheckReservedLock      /* xCheckReservedLock method */
28044)
28045#endif
28046
28047#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28048IOMETHODS(
28049  afpIoFinder,              /* Finder function name */
28050  afpIoMethods,             /* sqlite3_io_methods object name */
28051  1,                        /* shared memory is disabled */
28052  afpClose,                 /* xClose method */
28053  afpLock,                  /* xLock method */
28054  afpUnlock,                /* xUnlock method */
28055  afpCheckReservedLock      /* xCheckReservedLock method */
28056)
28057#endif
28058
28059/*
28060** The proxy locking method is a "super-method" in the sense that it
28061** opens secondary file descriptors for the conch and lock files and
28062** it uses proxy, dot-file, AFP, and flock() locking methods on those
28063** secondary files.  For this reason, the division that implements
28064** proxy locking is located much further down in the file.  But we need
28065** to go ahead and define the sqlite3_io_methods and finder function
28066** for proxy locking here.  So we forward declare the I/O methods.
28067*/
28068#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28069static int proxyClose(sqlite3_file*);
28070static int proxyLock(sqlite3_file*, int);
28071static int proxyUnlock(sqlite3_file*, int);
28072static int proxyCheckReservedLock(sqlite3_file*, int*);
28073IOMETHODS(
28074  proxyIoFinder,            /* Finder function name */
28075  proxyIoMethods,           /* sqlite3_io_methods object name */
28076  1,                        /* shared memory is disabled */
28077  proxyClose,               /* xClose method */
28078  proxyLock,                /* xLock method */
28079  proxyUnlock,              /* xUnlock method */
28080  proxyCheckReservedLock    /* xCheckReservedLock method */
28081)
28082#endif
28083
28084/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
28085#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28086IOMETHODS(
28087  nfsIoFinder,               /* Finder function name */
28088  nfsIoMethods,              /* sqlite3_io_methods object name */
28089  1,                         /* shared memory is disabled */
28090  unixClose,                 /* xClose method */
28091  unixLock,                  /* xLock method */
28092  nfsUnlock,                 /* xUnlock method */
28093  unixCheckReservedLock      /* xCheckReservedLock method */
28094)
28095#endif
28096
28097#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28098/*
28099** This "finder" function attempts to determine the best locking strategy
28100** for the database file "filePath".  It then returns the sqlite3_io_methods
28101** object that implements that strategy.
28102**
28103** This is for MacOSX only.
28104*/
28105static const sqlite3_io_methods *autolockIoFinderImpl(
28106  const char *filePath,    /* name of the database file */
28107  unixFile *pNew           /* open file object for the database file */
28108){
28109  static const struct Mapping {
28110    const char *zFilesystem;              /* Filesystem type name */
28111    const sqlite3_io_methods *pMethods;   /* Appropriate locking method */
28112  } aMap[] = {
28113    { "hfs",    &posixIoMethods },
28114    { "ufs",    &posixIoMethods },
28115    { "afpfs",  &afpIoMethods },
28116    { "smbfs",  &afpIoMethods },
28117    { "webdav", &nolockIoMethods },
28118    { 0, 0 }
28119  };
28120  int i;
28121  struct statfs fsInfo;
28122  struct flock lockInfo;
28123
28124  if( !filePath ){
28125    /* If filePath==NULL that means we are dealing with a transient file
28126    ** that does not need to be locked. */
28127    return &nolockIoMethods;
28128  }
28129  if( statfs(filePath, &fsInfo) != -1 ){
28130    if( fsInfo.f_flags & MNT_RDONLY ){
28131      return &nolockIoMethods;
28132    }
28133    for(i=0; aMap[i].zFilesystem; i++){
28134      if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
28135        return aMap[i].pMethods;
28136      }
28137    }
28138  }
28139
28140  /* Default case. Handles, amongst others, "nfs".
28141  ** Test byte-range lock using fcntl(). If the call succeeds,
28142  ** assume that the file-system supports POSIX style locks.
28143  */
28144  lockInfo.l_len = 1;
28145  lockInfo.l_start = 0;
28146  lockInfo.l_whence = SEEK_SET;
28147  lockInfo.l_type = F_RDLCK;
28148  if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
28149    if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
28150      return &nfsIoMethods;
28151    } else {
28152      return &posixIoMethods;
28153    }
28154  }else{
28155    return &dotlockIoMethods;
28156  }
28157}
28158static const sqlite3_io_methods
28159  *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
28160
28161#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
28162
28163#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
28164/*
28165** This "finder" function attempts to determine the best locking strategy
28166** for the database file "filePath".  It then returns the sqlite3_io_methods
28167** object that implements that strategy.
28168**
28169** This is for VXWorks only.
28170*/
28171static const sqlite3_io_methods *autolockIoFinderImpl(
28172  const char *filePath,    /* name of the database file */
28173  unixFile *pNew           /* the open file object */
28174){
28175  struct flock lockInfo;
28176
28177  if( !filePath ){
28178    /* If filePath==NULL that means we are dealing with a transient file
28179    ** that does not need to be locked. */
28180    return &nolockIoMethods;
28181  }
28182
28183  /* Test if fcntl() is supported and use POSIX style locks.
28184  ** Otherwise fall back to the named semaphore method.
28185  */
28186  lockInfo.l_len = 1;
28187  lockInfo.l_start = 0;
28188  lockInfo.l_whence = SEEK_SET;
28189  lockInfo.l_type = F_RDLCK;
28190  if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
28191    return &posixIoMethods;
28192  }else{
28193    return &semIoMethods;
28194  }
28195}
28196static const sqlite3_io_methods
28197  *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
28198
28199#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
28200
28201/*
28202** An abstract type for a pointer to a IO method finder function:
28203*/
28204typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
28205
28206
28207/****************************************************************************
28208**************************** sqlite3_vfs methods ****************************
28209**
28210** This division contains the implementation of methods on the
28211** sqlite3_vfs object.
28212*/
28213
28214/*
28215** Initialize the contents of the unixFile structure pointed to by pId.
28216*/
28217static int fillInUnixFile(
28218  sqlite3_vfs *pVfs,      /* Pointer to vfs object */
28219  int h,                  /* Open file descriptor of file being opened */
28220  sqlite3_file *pId,      /* Write to the unixFile structure here */
28221  const char *zFilename,  /* Name of the file being opened */
28222  int ctrlFlags           /* Zero or more UNIXFILE_* values */
28223){
28224  const sqlite3_io_methods *pLockingStyle;
28225  unixFile *pNew = (unixFile *)pId;
28226  int rc = SQLITE_OK;
28227
28228  assert( pNew->pInode==NULL );
28229
28230  /* Usually the path zFilename should not be a relative pathname. The
28231  ** exception is when opening the proxy "conch" file in builds that
28232  ** include the special Apple locking styles.
28233  */
28234#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28235  assert( zFilename==0 || zFilename[0]=='/'
28236    || pVfs->pAppData==(void*)&autolockIoFinder );
28237#else
28238  assert( zFilename==0 || zFilename[0]=='/' );
28239#endif
28240
28241  /* No locking occurs in temporary files */
28242  assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
28243
28244  OSTRACE(("OPEN    %-3d %s\n", h, zFilename));
28245  pNew->h = h;
28246  pNew->pVfs = pVfs;
28247  pNew->zPath = zFilename;
28248  pNew->ctrlFlags = (u8)ctrlFlags;
28249  pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
28250  if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
28251                           "psow", SQLITE_POWERSAFE_OVERWRITE) ){
28252    pNew->ctrlFlags |= UNIXFILE_PSOW;
28253  }
28254  if( strcmp(pVfs->zName,"unix-excl")==0 ){
28255    pNew->ctrlFlags |= UNIXFILE_EXCL;
28256  }
28257
28258#if OS_VXWORKS
28259  pNew->pId = vxworksFindFileId(zFilename);
28260  if( pNew->pId==0 ){
28261    ctrlFlags |= UNIXFILE_NOLOCK;
28262    rc = SQLITE_NOMEM;
28263  }
28264#endif
28265
28266  if( ctrlFlags & UNIXFILE_NOLOCK ){
28267    pLockingStyle = &nolockIoMethods;
28268  }else{
28269    pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
28270#if SQLITE_ENABLE_LOCKING_STYLE
28271    /* Cache zFilename in the locking context (AFP and dotlock override) for
28272    ** proxyLock activation is possible (remote proxy is based on db name)
28273    ** zFilename remains valid until file is closed, to support */
28274    pNew->lockingContext = (void*)zFilename;
28275#endif
28276  }
28277
28278  if( pLockingStyle == &posixIoMethods
28279#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28280    || pLockingStyle == &nfsIoMethods
28281#endif
28282  ){
28283    unixEnterMutex();
28284    rc = findInodeInfo(pNew, &pNew->pInode);
28285    if( rc!=SQLITE_OK ){
28286      /* If an error occurred in findInodeInfo(), close the file descriptor
28287      ** immediately, before releasing the mutex. findInodeInfo() may fail
28288      ** in two scenarios:
28289      **
28290      **   (a) A call to fstat() failed.
28291      **   (b) A malloc failed.
28292      **
28293      ** Scenario (b) may only occur if the process is holding no other
28294      ** file descriptors open on the same file. If there were other file
28295      ** descriptors on this file, then no malloc would be required by
28296      ** findInodeInfo(). If this is the case, it is quite safe to close
28297      ** handle h - as it is guaranteed that no posix locks will be released
28298      ** by doing so.
28299      **
28300      ** If scenario (a) caused the error then things are not so safe. The
28301      ** implicit assumption here is that if fstat() fails, things are in
28302      ** such bad shape that dropping a lock or two doesn't matter much.
28303      */
28304      robust_close(pNew, h, __LINE__);
28305      h = -1;
28306    }
28307    unixLeaveMutex();
28308  }
28309
28310#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
28311  else if( pLockingStyle == &afpIoMethods ){
28312    /* AFP locking uses the file path so it needs to be included in
28313    ** the afpLockingContext.
28314    */
28315    afpLockingContext *pCtx;
28316    pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
28317    if( pCtx==0 ){
28318      rc = SQLITE_NOMEM;
28319    }else{
28320      /* NB: zFilename exists and remains valid until the file is closed
28321      ** according to requirement F11141.  So we do not need to make a
28322      ** copy of the filename. */
28323      pCtx->dbPath = zFilename;
28324      pCtx->reserved = 0;
28325      srandomdev();
28326      unixEnterMutex();
28327      rc = findInodeInfo(pNew, &pNew->pInode);
28328      if( rc!=SQLITE_OK ){
28329        sqlite3_free(pNew->lockingContext);
28330        robust_close(pNew, h, __LINE__);
28331        h = -1;
28332      }
28333      unixLeaveMutex();
28334    }
28335  }
28336#endif
28337
28338  else if( pLockingStyle == &dotlockIoMethods ){
28339    /* Dotfile locking uses the file path so it needs to be included in
28340    ** the dotlockLockingContext
28341    */
28342    char *zLockFile;
28343    int nFilename;
28344    assert( zFilename!=0 );
28345    nFilename = (int)strlen(zFilename) + 6;
28346    zLockFile = (char *)sqlite3_malloc(nFilename);
28347    if( zLockFile==0 ){
28348      rc = SQLITE_NOMEM;
28349    }else{
28350      sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
28351    }
28352    pNew->lockingContext = zLockFile;
28353  }
28354
28355#if OS_VXWORKS
28356  else if( pLockingStyle == &semIoMethods ){
28357    /* Named semaphore locking uses the file path so it needs to be
28358    ** included in the semLockingContext
28359    */
28360    unixEnterMutex();
28361    rc = findInodeInfo(pNew, &pNew->pInode);
28362    if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
28363      char *zSemName = pNew->pInode->aSemName;
28364      int n;
28365      sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
28366                       pNew->pId->zCanonicalName);
28367      for( n=1; zSemName[n]; n++ )
28368        if( zSemName[n]=='/' ) zSemName[n] = '_';
28369      pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
28370      if( pNew->pInode->pSem == SEM_FAILED ){
28371        rc = SQLITE_NOMEM;
28372        pNew->pInode->aSemName[0] = '\0';
28373      }
28374    }
28375    unixLeaveMutex();
28376  }
28377#endif
28378
28379  pNew->lastErrno = 0;
28380#if OS_VXWORKS
28381  if( rc!=SQLITE_OK ){
28382    if( h>=0 ) robust_close(pNew, h, __LINE__);
28383    h = -1;
28384    osUnlink(zFilename);
28385    pNew->ctrlFlags |= UNIXFILE_DELETE;
28386  }
28387#endif
28388  if( rc!=SQLITE_OK ){
28389    if( h>=0 ) robust_close(pNew, h, __LINE__);
28390  }else{
28391    pNew->pMethod = pLockingStyle;
28392    OpenCounter(+1);
28393    verifyDbFile(pNew);
28394  }
28395  return rc;
28396}
28397
28398/*
28399** Return the name of a directory in which to put temporary files.
28400** If no suitable temporary file directory can be found, return NULL.
28401*/
28402static const char *unixTempFileDir(void){
28403  static const char *azDirs[] = {
28404     0,
28405     0,
28406     "/var/tmp",
28407     "/usr/tmp",
28408     "/tmp",
28409     0        /* List terminator */
28410  };
28411  unsigned int i;
28412  struct stat buf;
28413  const char *zDir = 0;
28414
28415  azDirs[0] = sqlite3_temp_directory;
28416  if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
28417  for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
28418    if( zDir==0 ) continue;
28419    if( osStat(zDir, &buf) ) continue;
28420    if( !S_ISDIR(buf.st_mode) ) continue;
28421    if( osAccess(zDir, 07) ) continue;
28422    break;
28423  }
28424  return zDir;
28425}
28426
28427/*
28428** Create a temporary file name in zBuf.  zBuf must be allocated
28429** by the calling process and must be big enough to hold at least
28430** pVfs->mxPathname bytes.
28431*/
28432static int unixGetTempname(int nBuf, char *zBuf){
28433  static const unsigned char zChars[] =
28434    "abcdefghijklmnopqrstuvwxyz"
28435    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
28436    "0123456789";
28437  unsigned int i, j;
28438  const char *zDir;
28439
28440  /* It's odd to simulate an io-error here, but really this is just
28441  ** using the io-error infrastructure to test that SQLite handles this
28442  ** function failing.
28443  */
28444  SimulateIOError( return SQLITE_IOERR );
28445
28446  zDir = unixTempFileDir();
28447  if( zDir==0 ) zDir = ".";
28448
28449  /* Check that the output buffer is large enough for the temporary file
28450  ** name. If it is not, return SQLITE_ERROR.
28451  */
28452  if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
28453    return SQLITE_ERROR;
28454  }
28455
28456  do{
28457    sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
28458    j = (int)strlen(zBuf);
28459    sqlite3_randomness(15, &zBuf[j]);
28460    for(i=0; i<15; i++, j++){
28461      zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
28462    }
28463    zBuf[j] = 0;
28464    zBuf[j+1] = 0;
28465  }while( osAccess(zBuf,0)==0 );
28466  return SQLITE_OK;
28467}
28468
28469#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
28470/*
28471** Routine to transform a unixFile into a proxy-locking unixFile.
28472** Implementation in the proxy-lock division, but used by unixOpen()
28473** if SQLITE_PREFER_PROXY_LOCKING is defined.
28474*/
28475static int proxyTransformUnixFile(unixFile*, const char*);
28476#endif
28477
28478/*
28479** Search for an unused file descriptor that was opened on the database
28480** file (not a journal or master-journal file) identified by pathname
28481** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
28482** argument to this function.
28483**
28484** Such a file descriptor may exist if a database connection was closed
28485** but the associated file descriptor could not be closed because some
28486** other file descriptor open on the same file is holding a file-lock.
28487** Refer to comments in the unixClose() function and the lengthy comment
28488** describing "Posix Advisory Locking" at the start of this file for
28489** further details. Also, ticket #4018.
28490**
28491** If a suitable file descriptor is found, then it is returned. If no
28492** such file descriptor is located, -1 is returned.
28493*/
28494static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
28495  UnixUnusedFd *pUnused = 0;
28496
28497  /* Do not search for an unused file descriptor on vxworks. Not because
28498  ** vxworks would not benefit from the change (it might, we're not sure),
28499  ** but because no way to test it is currently available. It is better
28500  ** not to risk breaking vxworks support for the sake of such an obscure
28501  ** feature.  */
28502#if !OS_VXWORKS
28503  struct stat sStat;                   /* Results of stat() call */
28504
28505  /* A stat() call may fail for various reasons. If this happens, it is
28506  ** almost certain that an open() call on the same path will also fail.
28507  ** For this reason, if an error occurs in the stat() call here, it is
28508  ** ignored and -1 is returned. The caller will try to open a new file
28509  ** descriptor on the same path, fail, and return an error to SQLite.
28510  **
28511  ** Even if a subsequent open() call does succeed, the consequences of
28512  ** not searching for a resusable file descriptor are not dire.  */
28513  if( 0==osStat(zPath, &sStat) ){
28514    unixInodeInfo *pInode;
28515
28516    unixEnterMutex();
28517    pInode = inodeList;
28518    while( pInode && (pInode->fileId.dev!=sStat.st_dev
28519                     || pInode->fileId.ino!=sStat.st_ino) ){
28520       pInode = pInode->pNext;
28521    }
28522    if( pInode ){
28523      UnixUnusedFd **pp;
28524      for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
28525      pUnused = *pp;
28526      if( pUnused ){
28527        *pp = pUnused->pNext;
28528      }
28529    }
28530    unixLeaveMutex();
28531  }
28532#endif    /* if !OS_VXWORKS */
28533  return pUnused;
28534}
28535
28536/*
28537** This function is called by unixOpen() to determine the unix permissions
28538** to create new files with. If no error occurs, then SQLITE_OK is returned
28539** and a value suitable for passing as the third argument to open(2) is
28540** written to *pMode. If an IO error occurs, an SQLite error code is
28541** returned and the value of *pMode is not modified.
28542**
28543** In most cases cases, this routine sets *pMode to 0, which will become
28544** an indication to robust_open() to create the file using
28545** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
28546** But if the file being opened is a WAL or regular journal file, then
28547** this function queries the file-system for the permissions on the
28548** corresponding database file and sets *pMode to this value. Whenever
28549** possible, WAL and journal files are created using the same permissions
28550** as the associated database file.
28551**
28552** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
28553** original filename is unavailable.  But 8_3_NAMES is only used for
28554** FAT filesystems and permissions do not matter there, so just use
28555** the default permissions.
28556*/
28557static int findCreateFileMode(
28558  const char *zPath,              /* Path of file (possibly) being created */
28559  int flags,                      /* Flags passed as 4th argument to xOpen() */
28560  mode_t *pMode,                  /* OUT: Permissions to open file with */
28561  uid_t *pUid,                    /* OUT: uid to set on the file */
28562  gid_t *pGid                     /* OUT: gid to set on the file */
28563){
28564  int rc = SQLITE_OK;             /* Return Code */
28565  *pMode = 0;
28566  *pUid = 0;
28567  *pGid = 0;
28568  if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
28569    char zDb[MAX_PATHNAME+1];     /* Database file path */
28570    int nDb;                      /* Number of valid bytes in zDb */
28571    struct stat sStat;            /* Output of stat() on database file */
28572
28573    /* zPath is a path to a WAL or journal file. The following block derives
28574    ** the path to the associated database file from zPath. This block handles
28575    ** the following naming conventions:
28576    **
28577    **   "<path to db>-journal"
28578    **   "<path to db>-wal"
28579    **   "<path to db>-journalNN"
28580    **   "<path to db>-walNN"
28581    **
28582    ** where NN is a decimal number. The NN naming schemes are
28583    ** used by the test_multiplex.c module.
28584    */
28585    nDb = sqlite3Strlen30(zPath) - 1;
28586#ifdef SQLITE_ENABLE_8_3_NAMES
28587    while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
28588    if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
28589#else
28590    while( zPath[nDb]!='-' ){
28591      assert( nDb>0 );
28592      assert( zPath[nDb]!='\n' );
28593      nDb--;
28594    }
28595#endif
28596    memcpy(zDb, zPath, nDb);
28597    zDb[nDb] = '\0';
28598
28599    if( 0==osStat(zDb, &sStat) ){
28600      *pMode = sStat.st_mode & 0777;
28601      *pUid = sStat.st_uid;
28602      *pGid = sStat.st_gid;
28603    }else{
28604      rc = SQLITE_IOERR_FSTAT;
28605    }
28606  }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
28607    *pMode = 0600;
28608  }
28609  return rc;
28610}
28611
28612/*
28613** Open the file zPath.
28614**
28615** Previously, the SQLite OS layer used three functions in place of this
28616** one:
28617**
28618**     sqlite3OsOpenReadWrite();
28619**     sqlite3OsOpenReadOnly();
28620**     sqlite3OsOpenExclusive();
28621**
28622** These calls correspond to the following combinations of flags:
28623**
28624**     ReadWrite() ->     (READWRITE | CREATE)
28625**     ReadOnly()  ->     (READONLY)
28626**     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
28627**
28628** The old OpenExclusive() accepted a boolean argument - "delFlag". If
28629** true, the file was configured to be automatically deleted when the
28630** file handle closed. To achieve the same effect using this new
28631** interface, add the DELETEONCLOSE flag to those specified above for
28632** OpenExclusive().
28633*/
28634static int unixOpen(
28635  sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
28636  const char *zPath,           /* Pathname of file to be opened */
28637  sqlite3_file *pFile,         /* The file descriptor to be filled in */
28638  int flags,                   /* Input flags to control the opening */
28639  int *pOutFlags               /* Output flags returned to SQLite core */
28640){
28641  unixFile *p = (unixFile *)pFile;
28642  int fd = -1;                   /* File descriptor returned by open() */
28643  int openFlags = 0;             /* Flags to pass to open() */
28644  int eType = flags&0xFFFFFF00;  /* Type of file to open */
28645  int noLock;                    /* True to omit locking primitives */
28646  int rc = SQLITE_OK;            /* Function Return Code */
28647  int ctrlFlags = 0;             /* UNIXFILE_* flags */
28648
28649  int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
28650  int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
28651  int isCreate     = (flags & SQLITE_OPEN_CREATE);
28652  int isReadonly   = (flags & SQLITE_OPEN_READONLY);
28653  int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
28654#if SQLITE_ENABLE_LOCKING_STYLE
28655  int isAutoProxy  = (flags & SQLITE_OPEN_AUTOPROXY);
28656#endif
28657#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
28658  struct statfs fsInfo;
28659#endif
28660
28661  /* If creating a master or main-file journal, this function will open
28662  ** a file-descriptor on the directory too. The first time unixSync()
28663  ** is called the directory file descriptor will be fsync()ed and close()d.
28664  */
28665  int syncDir = (isCreate && (
28666        eType==SQLITE_OPEN_MASTER_JOURNAL
28667     || eType==SQLITE_OPEN_MAIN_JOURNAL
28668     || eType==SQLITE_OPEN_WAL
28669  ));
28670
28671  /* If argument zPath is a NULL pointer, this function is required to open
28672  ** a temporary file. Use this buffer to store the file name in.
28673  */
28674  char zTmpname[MAX_PATHNAME+2];
28675  const char *zName = zPath;
28676
28677  /* Check the following statements are true:
28678  **
28679  **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
28680  **   (b) if CREATE is set, then READWRITE must also be set, and
28681  **   (c) if EXCLUSIVE is set, then CREATE must also be set.
28682  **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
28683  */
28684  assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
28685  assert(isCreate==0 || isReadWrite);
28686  assert(isExclusive==0 || isCreate);
28687  assert(isDelete==0 || isCreate);
28688
28689  /* The main DB, main journal, WAL file and master journal are never
28690  ** automatically deleted. Nor are they ever temporary files.  */
28691  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
28692  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
28693  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
28694  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
28695
28696  /* Assert that the upper layer has set one of the "file-type" flags. */
28697  assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
28698       || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
28699       || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
28700       || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
28701  );
28702
28703  memset(p, 0, sizeof(unixFile));
28704
28705  if( eType==SQLITE_OPEN_MAIN_DB ){
28706    UnixUnusedFd *pUnused;
28707    pUnused = findReusableFd(zName, flags);
28708    if( pUnused ){
28709      fd = pUnused->fd;
28710    }else{
28711      pUnused = sqlite3_malloc(sizeof(*pUnused));
28712      if( !pUnused ){
28713        return SQLITE_NOMEM;
28714      }
28715    }
28716    p->pUnused = pUnused;
28717
28718    /* Database filenames are double-zero terminated if they are not
28719    ** URIs with parameters.  Hence, they can always be passed into
28720    ** sqlite3_uri_parameter(). */
28721    assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
28722
28723  }else if( !zName ){
28724    /* If zName is NULL, the upper layer is requesting a temp file. */
28725    assert(isDelete && !syncDir);
28726    rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
28727    if( rc!=SQLITE_OK ){
28728      return rc;
28729    }
28730    zName = zTmpname;
28731
28732    /* Generated temporary filenames are always double-zero terminated
28733    ** for use by sqlite3_uri_parameter(). */
28734    assert( zName[strlen(zName)+1]==0 );
28735  }
28736
28737  /* Determine the value of the flags parameter passed to POSIX function
28738  ** open(). These must be calculated even if open() is not called, as
28739  ** they may be stored as part of the file handle and used by the
28740  ** 'conch file' locking functions later on.  */
28741  if( isReadonly )  openFlags |= O_RDONLY;
28742  if( isReadWrite ) openFlags |= O_RDWR;
28743  if( isCreate )    openFlags |= O_CREAT;
28744  if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
28745  openFlags |= (O_LARGEFILE|O_BINARY);
28746
28747  if( fd<0 ){
28748    mode_t openMode;              /* Permissions to create file with */
28749    uid_t uid;                    /* Userid for the file */
28750    gid_t gid;                    /* Groupid for the file */
28751    rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
28752    if( rc!=SQLITE_OK ){
28753      assert( !p->pUnused );
28754      assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
28755      return rc;
28756    }
28757    fd = robust_open(zName, openFlags, openMode);
28758    OSTRACE(("OPENX   %-3d %s 0%o\n", fd, zName, openFlags));
28759    if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
28760      /* Failed to open the file for read/write access. Try read-only. */
28761      flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
28762      openFlags &= ~(O_RDWR|O_CREAT);
28763      flags |= SQLITE_OPEN_READONLY;
28764      openFlags |= O_RDONLY;
28765      isReadonly = 1;
28766      fd = robust_open(zName, openFlags, openMode);
28767    }
28768    if( fd<0 ){
28769      rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
28770      goto open_finished;
28771    }
28772
28773    /* If this process is running as root and if creating a new rollback
28774    ** journal or WAL file, set the ownership of the journal or WAL to be
28775    ** the same as the original database.
28776    */
28777    if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
28778      osFchown(fd, uid, gid);
28779    }
28780  }
28781  assert( fd>=0 );
28782  if( pOutFlags ){
28783    *pOutFlags = flags;
28784  }
28785
28786  if( p->pUnused ){
28787    p->pUnused->fd = fd;
28788    p->pUnused->flags = flags;
28789  }
28790
28791  if( isDelete ){
28792#if OS_VXWORKS
28793    zPath = zName;
28794#else
28795    osUnlink(zName);
28796#endif
28797  }
28798#if SQLITE_ENABLE_LOCKING_STYLE
28799  else{
28800    p->openFlags = openFlags;
28801  }
28802#endif
28803
28804  noLock = eType!=SQLITE_OPEN_MAIN_DB;
28805
28806
28807#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
28808  if( fstatfs(fd, &fsInfo) == -1 ){
28809    ((unixFile*)pFile)->lastErrno = errno;
28810    robust_close(p, fd, __LINE__);
28811    return SQLITE_IOERR_ACCESS;
28812  }
28813  if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
28814    ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
28815  }
28816#endif
28817
28818  /* Set up appropriate ctrlFlags */
28819  if( isDelete )                ctrlFlags |= UNIXFILE_DELETE;
28820  if( isReadonly )              ctrlFlags |= UNIXFILE_RDONLY;
28821  if( noLock )                  ctrlFlags |= UNIXFILE_NOLOCK;
28822  if( syncDir )                 ctrlFlags |= UNIXFILE_DIRSYNC;
28823  if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
28824
28825#if SQLITE_ENABLE_LOCKING_STYLE
28826#if SQLITE_PREFER_PROXY_LOCKING
28827  isAutoProxy = 1;
28828#endif
28829  if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
28830    char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
28831    int useProxy = 0;
28832
28833    /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
28834    ** never use proxy, NULL means use proxy for non-local files only.  */
28835    if( envforce!=NULL ){
28836      useProxy = atoi(envforce)>0;
28837    }else{
28838      if( statfs(zPath, &fsInfo) == -1 ){
28839        /* In theory, the close(fd) call is sub-optimal. If the file opened
28840        ** with fd is a database file, and there are other connections open
28841        ** on that file that are currently holding advisory locks on it,
28842        ** then the call to close() will cancel those locks. In practice,
28843        ** we're assuming that statfs() doesn't fail very often. At least
28844        ** not while other file descriptors opened by the same process on
28845        ** the same file are working.  */
28846        p->lastErrno = errno;
28847        robust_close(p, fd, __LINE__);
28848        rc = SQLITE_IOERR_ACCESS;
28849        goto open_finished;
28850      }
28851      useProxy = !(fsInfo.f_flags&MNT_LOCAL);
28852    }
28853    if( useProxy ){
28854      rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
28855      if( rc==SQLITE_OK ){
28856        rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
28857        if( rc!=SQLITE_OK ){
28858          /* Use unixClose to clean up the resources added in fillInUnixFile
28859          ** and clear all the structure's references.  Specifically,
28860          ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
28861          */
28862          unixClose(pFile);
28863          return rc;
28864        }
28865      }
28866      goto open_finished;
28867    }
28868  }
28869#endif
28870
28871  rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
28872
28873open_finished:
28874  if( rc!=SQLITE_OK ){
28875    sqlite3_free(p->pUnused);
28876  }
28877  return rc;
28878}
28879
28880
28881/*
28882** Delete the file at zPath. If the dirSync argument is true, fsync()
28883** the directory after deleting the file.
28884*/
28885static int unixDelete(
28886  sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
28887  const char *zPath,        /* Name of file to be deleted */
28888  int dirSync               /* If true, fsync() directory after deleting file */
28889){
28890  int rc = SQLITE_OK;
28891  UNUSED_PARAMETER(NotUsed);
28892  SimulateIOError(return SQLITE_IOERR_DELETE);
28893  if( osUnlink(zPath)==(-1) ){
28894    if( errno==ENOENT ){
28895      rc = SQLITE_IOERR_DELETE_NOENT;
28896    }else{
28897      rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
28898    }
28899    return rc;
28900  }
28901#ifndef SQLITE_DISABLE_DIRSYNC
28902  if( (dirSync & 1)!=0 ){
28903    int fd;
28904    rc = osOpenDirectory(zPath, &fd);
28905    if( rc==SQLITE_OK ){
28906#if OS_VXWORKS
28907      if( fsync(fd)==-1 )
28908#else
28909      if( fsync(fd) )
28910#endif
28911      {
28912        rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
28913      }
28914      robust_close(0, fd, __LINE__);
28915    }else if( rc==SQLITE_CANTOPEN ){
28916      rc = SQLITE_OK;
28917    }
28918  }
28919#endif
28920  return rc;
28921}
28922
28923/*
28924** Test the existence of or access permissions of file zPath. The
28925** test performed depends on the value of flags:
28926**
28927**     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
28928**     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
28929**     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
28930**
28931** Otherwise return 0.
28932*/
28933static int unixAccess(
28934  sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */
28935  const char *zPath,      /* Path of the file to examine */
28936  int flags,              /* What do we want to learn about the zPath file? */
28937  int *pResOut            /* Write result boolean here */
28938){
28939  int amode = 0;
28940  UNUSED_PARAMETER(NotUsed);
28941  SimulateIOError( return SQLITE_IOERR_ACCESS; );
28942  switch( flags ){
28943    case SQLITE_ACCESS_EXISTS:
28944      amode = F_OK;
28945      break;
28946    case SQLITE_ACCESS_READWRITE:
28947      amode = W_OK|R_OK;
28948      break;
28949    case SQLITE_ACCESS_READ:
28950      amode = R_OK;
28951      break;
28952
28953    default:
28954      assert(!"Invalid flags argument");
28955  }
28956  *pResOut = (osAccess(zPath, amode)==0);
28957  if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
28958    struct stat buf;
28959    if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
28960      *pResOut = 0;
28961    }
28962  }
28963  return SQLITE_OK;
28964}
28965
28966
28967/*
28968** Turn a relative pathname into a full pathname. The relative path
28969** is stored as a nul-terminated string in the buffer pointed to by
28970** zPath.
28971**
28972** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
28973** (in this case, MAX_PATHNAME bytes). The full-path is written to
28974** this buffer before returning.
28975*/
28976static int unixFullPathname(
28977  sqlite3_vfs *pVfs,            /* Pointer to vfs object */
28978  const char *zPath,            /* Possibly relative input path */
28979  int nOut,                     /* Size of output buffer in bytes */
28980  char *zOut                    /* Output buffer */
28981){
28982
28983  /* It's odd to simulate an io-error here, but really this is just
28984  ** using the io-error infrastructure to test that SQLite handles this
28985  ** function failing. This function could fail if, for example, the
28986  ** current working directory has been unlinked.
28987  */
28988  SimulateIOError( return SQLITE_ERROR );
28989
28990  assert( pVfs->mxPathname==MAX_PATHNAME );
28991  UNUSED_PARAMETER(pVfs);
28992
28993  zOut[nOut-1] = '\0';
28994  if( zPath[0]=='/' ){
28995    sqlite3_snprintf(nOut, zOut, "%s", zPath);
28996  }else{
28997    int nCwd;
28998    if( osGetcwd(zOut, nOut-1)==0 ){
28999      return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
29000    }
29001    nCwd = (int)strlen(zOut);
29002    sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
29003  }
29004  return SQLITE_OK;
29005}
29006
29007
29008#ifndef SQLITE_OMIT_LOAD_EXTENSION
29009/*
29010** Interfaces for opening a shared library, finding entry points
29011** within the shared library, and closing the shared library.
29012*/
29013#include <dlfcn.h>
29014static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
29015  UNUSED_PARAMETER(NotUsed);
29016  return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
29017}
29018
29019/*
29020** SQLite calls this function immediately after a call to unixDlSym() or
29021** unixDlOpen() fails (returns a null pointer). If a more detailed error
29022** message is available, it is written to zBufOut. If no error message
29023** is available, zBufOut is left unmodified and SQLite uses a default
29024** error message.
29025*/
29026static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
29027  const char *zErr;
29028  UNUSED_PARAMETER(NotUsed);
29029  unixEnterMutex();
29030  zErr = dlerror();
29031  if( zErr ){
29032    sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
29033  }
29034  unixLeaveMutex();
29035}
29036static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
29037  /*
29038  ** GCC with -pedantic-errors says that C90 does not allow a void* to be
29039  ** cast into a pointer to a function.  And yet the library dlsym() routine
29040  ** returns a void* which is really a pointer to a function.  So how do we
29041  ** use dlsym() with -pedantic-errors?
29042  **
29043  ** Variable x below is defined to be a pointer to a function taking
29044  ** parameters void* and const char* and returning a pointer to a function.
29045  ** We initialize x by assigning it a pointer to the dlsym() function.
29046  ** (That assignment requires a cast.)  Then we call the function that
29047  ** x points to.
29048  **
29049  ** This work-around is unlikely to work correctly on any system where
29050  ** you really cannot cast a function pointer into void*.  But then, on the
29051  ** other hand, dlsym() will not work on such a system either, so we have
29052  ** not really lost anything.
29053  */
29054  void (*(*x)(void*,const char*))(void);
29055  UNUSED_PARAMETER(NotUsed);
29056  x = (void(*(*)(void*,const char*))(void))dlsym;
29057  return (*x)(p, zSym);
29058}
29059static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
29060  UNUSED_PARAMETER(NotUsed);
29061  dlclose(pHandle);
29062}
29063#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
29064  #define unixDlOpen  0
29065  #define unixDlError 0
29066  #define unixDlSym   0
29067  #define unixDlClose 0
29068#endif
29069
29070/*
29071** Write nBuf bytes of random data to the supplied buffer zBuf.
29072*/
29073static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
29074  UNUSED_PARAMETER(NotUsed);
29075  assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
29076
29077  /* We have to initialize zBuf to prevent valgrind from reporting
29078  ** errors.  The reports issued by valgrind are incorrect - we would
29079  ** prefer that the randomness be increased by making use of the
29080  ** uninitialized space in zBuf - but valgrind errors tend to worry
29081  ** some users.  Rather than argue, it seems easier just to initialize
29082  ** the whole array and silence valgrind, even if that means less randomness
29083  ** in the random seed.
29084  **
29085  ** When testing, initializing zBuf[] to zero is all we do.  That means
29086  ** that we always use the same random number sequence.  This makes the
29087  ** tests repeatable.
29088  */
29089  memset(zBuf, 0, nBuf);
29090#if !defined(SQLITE_TEST)
29091  {
29092    int pid, fd, got;
29093    fd = robust_open("/dev/urandom", O_RDONLY, 0);
29094    if( fd<0 ){
29095      time_t t;
29096      time(&t);
29097      memcpy(zBuf, &t, sizeof(t));
29098      pid = getpid();
29099      memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
29100      assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
29101      nBuf = sizeof(t) + sizeof(pid);
29102    }else{
29103      do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
29104      robust_close(0, fd, __LINE__);
29105    }
29106  }
29107#endif
29108  return nBuf;
29109}
29110
29111
29112/*
29113** Sleep for a little while.  Return the amount of time slept.
29114** The argument is the number of microseconds we want to sleep.
29115** The return value is the number of microseconds of sleep actually
29116** requested from the underlying operating system, a number which
29117** might be greater than or equal to the argument, but not less
29118** than the argument.
29119*/
29120static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
29121#if OS_VXWORKS
29122  struct timespec sp;
29123
29124  sp.tv_sec = microseconds / 1000000;
29125  sp.tv_nsec = (microseconds % 1000000) * 1000;
29126  nanosleep(&sp, NULL);
29127  UNUSED_PARAMETER(NotUsed);
29128  return microseconds;
29129#elif defined(HAVE_USLEEP) && HAVE_USLEEP
29130  usleep(microseconds);
29131  UNUSED_PARAMETER(NotUsed);
29132  return microseconds;
29133#else
29134  int seconds = (microseconds+999999)/1000000;
29135  sleep(seconds);
29136  UNUSED_PARAMETER(NotUsed);
29137  return seconds*1000000;
29138#endif
29139}
29140
29141/*
29142** The following variable, if set to a non-zero value, is interpreted as
29143** the number of seconds since 1970 and is used to set the result of
29144** sqlite3OsCurrentTime() during testing.
29145*/
29146#ifdef SQLITE_TEST
29147SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
29148#endif
29149
29150/*
29151** Find the current time (in Universal Coordinated Time).  Write into *piNow
29152** the current time and date as a Julian Day number times 86_400_000.  In
29153** other words, write into *piNow the number of milliseconds since the Julian
29154** epoch of noon in Greenwich on November 24, 4714 B.C according to the
29155** proleptic Gregorian calendar.
29156**
29157** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date
29158** cannot be found.
29159*/
29160static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
29161  static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
29162  int rc = SQLITE_OK;
29163#if defined(NO_GETTOD)
29164  time_t t;
29165  time(&t);
29166  *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
29167#elif OS_VXWORKS
29168  struct timespec sNow;
29169  clock_gettime(CLOCK_REALTIME, &sNow);
29170  *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
29171#else
29172  struct timeval sNow;
29173  if( gettimeofday(&sNow, 0)==0 ){
29174    *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
29175  }else{
29176    rc = SQLITE_ERROR;
29177  }
29178#endif
29179
29180#ifdef SQLITE_TEST
29181  if( sqlite3_current_time ){
29182    *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
29183  }
29184#endif
29185  UNUSED_PARAMETER(NotUsed);
29186  return rc;
29187}
29188
29189/*
29190** Find the current time (in Universal Coordinated Time).  Write the
29191** current time and date as a Julian Day number into *prNow and
29192** return 0.  Return 1 if the time and date cannot be found.
29193*/
29194static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
29195  sqlite3_int64 i = 0;
29196  int rc;
29197  UNUSED_PARAMETER(NotUsed);
29198  rc = unixCurrentTimeInt64(0, &i);
29199  *prNow = i/86400000.0;
29200  return rc;
29201}
29202
29203/*
29204** We added the xGetLastError() method with the intention of providing
29205** better low-level error messages when operating-system problems come up
29206** during SQLite operation.  But so far, none of that has been implemented
29207** in the core.  So this routine is never called.  For now, it is merely
29208** a place-holder.
29209*/
29210static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
29211  UNUSED_PARAMETER(NotUsed);
29212  UNUSED_PARAMETER(NotUsed2);
29213  UNUSED_PARAMETER(NotUsed3);
29214  return 0;
29215}
29216
29217
29218/*
29219************************ End of sqlite3_vfs methods ***************************
29220******************************************************************************/
29221
29222/******************************************************************************
29223************************** Begin Proxy Locking ********************************
29224**
29225** Proxy locking is a "uber-locking-method" in this sense:  It uses the
29226** other locking methods on secondary lock files.  Proxy locking is a
29227** meta-layer over top of the primitive locking implemented above.  For
29228** this reason, the division that implements of proxy locking is deferred
29229** until late in the file (here) after all of the other I/O methods have
29230** been defined - so that the primitive locking methods are available
29231** as services to help with the implementation of proxy locking.
29232**
29233****
29234**
29235** The default locking schemes in SQLite use byte-range locks on the
29236** database file to coordinate safe, concurrent access by multiple readers
29237** and writers [http://sqlite.org/lockingv3.html].  The five file locking
29238** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
29239** as POSIX read & write locks over fixed set of locations (via fsctl),
29240** on AFP and SMB only exclusive byte-range locks are available via fsctl
29241** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
29242** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
29243** address in the shared range is taken for a SHARED lock, the entire
29244** shared range is taken for an EXCLUSIVE lock):
29245**
29246**      PENDING_BYTE        0x40000000
29247**      RESERVED_BYTE       0x40000001
29248**      SHARED_RANGE        0x40000002 -> 0x40000200
29249**
29250** This works well on the local file system, but shows a nearly 100x
29251** slowdown in read performance on AFP because the AFP client disables
29252** the read cache when byte-range locks are present.  Enabling the read
29253** cache exposes a cache coherency problem that is present on all OS X
29254** supported network file systems.  NFS and AFP both observe the
29255** close-to-open semantics for ensuring cache coherency
29256** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
29257** address the requirements for concurrent database access by multiple
29258** readers and writers
29259** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
29260**
29261** To address the performance and cache coherency issues, proxy file locking
29262** changes the way database access is controlled by limiting access to a
29263** single host at a time and moving file locks off of the database file
29264** and onto a proxy file on the local file system.
29265**
29266**
29267** Using proxy locks
29268** -----------------
29269**
29270** C APIs
29271**
29272**  sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
29273**                       <proxy_path> | ":auto:");
29274**  sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
29275**
29276**
29277** SQL pragmas
29278**
29279**  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
29280**  PRAGMA [database.]lock_proxy_file
29281**
29282** Specifying ":auto:" means that if there is a conch file with a matching
29283** host ID in it, the proxy path in the conch file will be used, otherwise
29284** a proxy path based on the user's temp dir
29285** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
29286** actual proxy file name is generated from the name and path of the
29287** database file.  For example:
29288**
29289**       For database path "/Users/me/foo.db"
29290**       The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
29291**
29292** Once a lock proxy is configured for a database connection, it can not
29293** be removed, however it may be switched to a different proxy path via
29294** the above APIs (assuming the conch file is not being held by another
29295** connection or process).
29296**
29297**
29298** How proxy locking works
29299** -----------------------
29300**
29301** Proxy file locking relies primarily on two new supporting files:
29302**
29303**   *  conch file to limit access to the database file to a single host
29304**      at a time
29305**
29306**   *  proxy file to act as a proxy for the advisory locks normally
29307**      taken on the database
29308**
29309** The conch file - to use a proxy file, sqlite must first "hold the conch"
29310** by taking an sqlite-style shared lock on the conch file, reading the
29311** contents and comparing the host's unique host ID (see below) and lock
29312** proxy path against the values stored in the conch.  The conch file is
29313** stored in the same directory as the database file and the file name
29314** is patterned after the database file name as ".<databasename>-conch".
29315** If the conch file does not exist, or it's contents do not match the
29316** host ID and/or proxy path, then the lock is escalated to an exclusive
29317** lock and the conch file contents is updated with the host ID and proxy
29318** path and the lock is downgraded to a shared lock again.  If the conch
29319** is held by another process (with a shared lock), the exclusive lock
29320** will fail and SQLITE_BUSY is returned.
29321**
29322** The proxy file - a single-byte file used for all advisory file locks
29323** normally taken on the database file.   This allows for safe sharing
29324** of the database file for multiple readers and writers on the same
29325** host (the conch ensures that they all use the same local lock file).
29326**
29327** Requesting the lock proxy does not immediately take the conch, it is
29328** only taken when the first request to lock database file is made.
29329** This matches the semantics of the traditional locking behavior, where
29330** opening a connection to a database file does not take a lock on it.
29331** The shared lock and an open file descriptor are maintained until
29332** the connection to the database is closed.
29333**
29334** The proxy file and the lock file are never deleted so they only need
29335** to be created the first time they are used.
29336**
29337** Configuration options
29338** ---------------------
29339**
29340**  SQLITE_PREFER_PROXY_LOCKING
29341**
29342**       Database files accessed on non-local file systems are
29343**       automatically configured for proxy locking, lock files are
29344**       named automatically using the same logic as
29345**       PRAGMA lock_proxy_file=":auto:"
29346**
29347**  SQLITE_PROXY_DEBUG
29348**
29349**       Enables the logging of error messages during host id file
29350**       retrieval and creation
29351**
29352**  LOCKPROXYDIR
29353**
29354**       Overrides the default directory used for lock proxy files that
29355**       are named automatically via the ":auto:" setting
29356**
29357**  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
29358**
29359**       Permissions to use when creating a directory for storing the
29360**       lock proxy files, only used when LOCKPROXYDIR is not set.
29361**
29362**
29363** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
29364** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
29365** force proxy locking to be used for every database file opened, and 0
29366** will force automatic proxy locking to be disabled for all database
29367** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
29368** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
29369*/
29370
29371/*
29372** Proxy locking is only available on MacOSX
29373*/
29374#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29375
29376/*
29377** The proxyLockingContext has the path and file structures for the remote
29378** and local proxy files in it
29379*/
29380typedef struct proxyLockingContext proxyLockingContext;
29381struct proxyLockingContext {
29382  unixFile *conchFile;         /* Open conch file */
29383  char *conchFilePath;         /* Name of the conch file */
29384  unixFile *lockProxy;         /* Open proxy lock file */
29385  char *lockProxyPath;         /* Name of the proxy lock file */
29386  char *dbPath;                /* Name of the open file */
29387  int conchHeld;               /* 1 if the conch is held, -1 if lockless */
29388  void *oldLockingContext;     /* Original lockingcontext to restore on close */
29389  sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */
29390};
29391
29392/*
29393** The proxy lock file path for the database at dbPath is written into lPath,
29394** which must point to valid, writable memory large enough for a maxLen length
29395** file path.
29396*/
29397static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
29398  int len;
29399  int dbLen;
29400  int i;
29401
29402#ifdef LOCKPROXYDIR
29403  len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
29404#else
29405# ifdef _CS_DARWIN_USER_TEMP_DIR
29406  {
29407    if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
29408      OSTRACE(("GETLOCKPATH  failed %s errno=%d pid=%d\n",
29409               lPath, errno, getpid()));
29410      return SQLITE_IOERR_LOCK;
29411    }
29412    len = strlcat(lPath, "sqliteplocks", maxLen);
29413  }
29414# else
29415  len = strlcpy(lPath, "/tmp/", maxLen);
29416# endif
29417#endif
29418
29419  if( lPath[len-1]!='/' ){
29420    len = strlcat(lPath, "/", maxLen);
29421  }
29422
29423  /* transform the db path to a unique cache name */
29424  dbLen = (int)strlen(dbPath);
29425  for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
29426    char c = dbPath[i];
29427    lPath[i+len] = (c=='/')?'_':c;
29428  }
29429  lPath[i+len]='\0';
29430  strlcat(lPath, ":auto:", maxLen);
29431  OSTRACE(("GETLOCKPATH  proxy lock path=%s pid=%d\n", lPath, getpid()));
29432  return SQLITE_OK;
29433}
29434
29435/*
29436 ** Creates the lock file and any missing directories in lockPath
29437 */
29438static int proxyCreateLockPath(const char *lockPath){
29439  int i, len;
29440  char buf[MAXPATHLEN];
29441  int start = 0;
29442
29443  assert(lockPath!=NULL);
29444  /* try to create all the intermediate directories */
29445  len = (int)strlen(lockPath);
29446  buf[0] = lockPath[0];
29447  for( i=1; i<len; i++ ){
29448    if( lockPath[i] == '/' && (i - start > 0) ){
29449      /* only mkdir if leaf dir != "." or "/" or ".." */
29450      if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
29451         || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
29452        buf[i]='\0';
29453        if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
29454          int err=errno;
29455          if( err!=EEXIST ) {
29456            OSTRACE(("CREATELOCKPATH  FAILED creating %s, "
29457                     "'%s' proxy lock path=%s pid=%d\n",
29458                     buf, strerror(err), lockPath, getpid()));
29459            return err;
29460          }
29461        }
29462      }
29463      start=i+1;
29464    }
29465    buf[i] = lockPath[i];
29466  }
29467  OSTRACE(("CREATELOCKPATH  proxy lock path=%s pid=%d\n", lockPath, getpid()));
29468  return 0;
29469}
29470
29471/*
29472** Create a new VFS file descriptor (stored in memory obtained from
29473** sqlite3_malloc) and open the file named "path" in the file descriptor.
29474**
29475** The caller is responsible not only for closing the file descriptor
29476** but also for freeing the memory associated with the file descriptor.
29477*/
29478static int proxyCreateUnixFile(
29479    const char *path,        /* path for the new unixFile */
29480    unixFile **ppFile,       /* unixFile created and returned by ref */
29481    int islockfile           /* if non zero missing dirs will be created */
29482) {
29483  int fd = -1;
29484  unixFile *pNew;
29485  int rc = SQLITE_OK;
29486  int openFlags = O_RDWR | O_CREAT;
29487  sqlite3_vfs dummyVfs;
29488  int terrno = 0;
29489  UnixUnusedFd *pUnused = NULL;
29490
29491  /* 1. first try to open/create the file
29492  ** 2. if that fails, and this is a lock file (not-conch), try creating
29493  ** the parent directories and then try again.
29494  ** 3. if that fails, try to open the file read-only
29495  ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
29496  */
29497  pUnused = findReusableFd(path, openFlags);
29498  if( pUnused ){
29499    fd = pUnused->fd;
29500  }else{
29501    pUnused = sqlite3_malloc(sizeof(*pUnused));
29502    if( !pUnused ){
29503      return SQLITE_NOMEM;
29504    }
29505  }
29506  if( fd<0 ){
29507    fd = robust_open(path, openFlags, 0);
29508    terrno = errno;
29509    if( fd<0 && errno==ENOENT && islockfile ){
29510      if( proxyCreateLockPath(path) == SQLITE_OK ){
29511        fd = robust_open(path, openFlags, 0);
29512      }
29513    }
29514  }
29515  if( fd<0 ){
29516    openFlags = O_RDONLY;
29517    fd = robust_open(path, openFlags, 0);
29518    terrno = errno;
29519  }
29520  if( fd<0 ){
29521    if( islockfile ){
29522      return SQLITE_BUSY;
29523    }
29524    switch (terrno) {
29525      case EACCES:
29526        return SQLITE_PERM;
29527      case EIO:
29528        return SQLITE_IOERR_LOCK; /* even though it is the conch */
29529      default:
29530        return SQLITE_CANTOPEN_BKPT;
29531    }
29532  }
29533
29534  pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
29535  if( pNew==NULL ){
29536    rc = SQLITE_NOMEM;
29537    goto end_create_proxy;
29538  }
29539  memset(pNew, 0, sizeof(unixFile));
29540  pNew->openFlags = openFlags;
29541  memset(&dummyVfs, 0, sizeof(dummyVfs));
29542  dummyVfs.pAppData = (void*)&autolockIoFinder;
29543  dummyVfs.zName = "dummy";
29544  pUnused->fd = fd;
29545  pUnused->flags = openFlags;
29546  pNew->pUnused = pUnused;
29547
29548  rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
29549  if( rc==SQLITE_OK ){
29550    *ppFile = pNew;
29551    return SQLITE_OK;
29552  }
29553end_create_proxy:
29554  robust_close(pNew, fd, __LINE__);
29555  sqlite3_free(pNew);
29556  sqlite3_free(pUnused);
29557  return rc;
29558}
29559
29560#ifdef SQLITE_TEST
29561/* simulate multiple hosts by creating unique hostid file paths */
29562SQLITE_API int sqlite3_hostid_num = 0;
29563#endif
29564
29565#define PROXY_HOSTIDLEN    16  /* conch file host id length */
29566
29567/* Not always defined in the headers as it ought to be */
29568extern int gethostuuid(uuid_t id, const struct timespec *wait);
29569
29570/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
29571** bytes of writable memory.
29572*/
29573static int proxyGetHostID(unsigned char *pHostID, int *pError){
29574  assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
29575  memset(pHostID, 0, PROXY_HOSTIDLEN);
29576#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
29577               && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
29578  {
29579    static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
29580    if( gethostuuid(pHostID, &timeout) ){
29581      int err = errno;
29582      if( pError ){
29583        *pError = err;
29584      }
29585      return SQLITE_IOERR;
29586    }
29587  }
29588#else
29589  UNUSED_PARAMETER(pError);
29590#endif
29591#ifdef SQLITE_TEST
29592  /* simulate multiple hosts by creating unique hostid file paths */
29593  if( sqlite3_hostid_num != 0){
29594    pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
29595  }
29596#endif
29597
29598  return SQLITE_OK;
29599}
29600
29601/* The conch file contains the header, host id and lock file path
29602 */
29603#define PROXY_CONCHVERSION 2   /* 1-byte header, 16-byte host id, path */
29604#define PROXY_HEADERLEN    1   /* conch file header length */
29605#define PROXY_PATHINDEX    (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
29606#define PROXY_MAXCONCHLEN  (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
29607
29608/*
29609** Takes an open conch file, copies the contents to a new path and then moves
29610** it back.  The newly created file's file descriptor is assigned to the
29611** conch file structure and finally the original conch file descriptor is
29612** closed.  Returns zero if successful.
29613*/
29614static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
29615  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
29616  unixFile *conchFile = pCtx->conchFile;
29617  char tPath[MAXPATHLEN];
29618  char buf[PROXY_MAXCONCHLEN];
29619  char *cPath = pCtx->conchFilePath;
29620  size_t readLen = 0;
29621  size_t pathLen = 0;
29622  char errmsg[64] = "";
29623  int fd = -1;
29624  int rc = -1;
29625  UNUSED_PARAMETER(myHostID);
29626
29627  /* create a new path by replace the trailing '-conch' with '-break' */
29628  pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
29629  if( pathLen>MAXPATHLEN || pathLen<6 ||
29630     (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
29631    sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
29632    goto end_breaklock;
29633  }
29634  /* read the conch content */
29635  readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
29636  if( readLen<PROXY_PATHINDEX ){
29637    sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
29638    goto end_breaklock;
29639  }
29640  /* write it out to the temporary break file */
29641  fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
29642  if( fd<0 ){
29643    sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
29644    goto end_breaklock;
29645  }
29646  if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
29647    sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
29648    goto end_breaklock;
29649  }
29650  if( rename(tPath, cPath) ){
29651    sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
29652    goto end_breaklock;
29653  }
29654  rc = 0;
29655  fprintf(stderr, "broke stale lock on %s\n", cPath);
29656  robust_close(pFile, conchFile->h, __LINE__);
29657  conchFile->h = fd;
29658  conchFile->openFlags = O_RDWR | O_CREAT;
29659
29660end_breaklock:
29661  if( rc ){
29662    if( fd>=0 ){
29663      osUnlink(tPath);
29664      robust_close(pFile, fd, __LINE__);
29665    }
29666    fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
29667  }
29668  return rc;
29669}
29670
29671/* Take the requested lock on the conch file and break a stale lock if the
29672** host id matches.
29673*/
29674static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
29675  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
29676  unixFile *conchFile = pCtx->conchFile;
29677  int rc = SQLITE_OK;
29678  int nTries = 0;
29679  struct timespec conchModTime;
29680
29681  memset(&conchModTime, 0, sizeof(conchModTime));
29682  do {
29683    rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
29684    nTries ++;
29685    if( rc==SQLITE_BUSY ){
29686      /* If the lock failed (busy):
29687       * 1st try: get the mod time of the conch, wait 0.5s and try again.
29688       * 2nd try: fail if the mod time changed or host id is different, wait
29689       *           10 sec and try again
29690       * 3rd try: break the lock unless the mod time has changed.
29691       */
29692      struct stat buf;
29693      if( osFstat(conchFile->h, &buf) ){
29694        pFile->lastErrno = errno;
29695        return SQLITE_IOERR_LOCK;
29696      }
29697
29698      if( nTries==1 ){
29699        conchModTime = buf.st_mtimespec;
29700        usleep(500000); /* wait 0.5 sec and try the lock again*/
29701        continue;
29702      }
29703
29704      assert( nTries>1 );
29705      if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
29706         conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
29707        return SQLITE_BUSY;
29708      }
29709
29710      if( nTries==2 ){
29711        char tBuf[PROXY_MAXCONCHLEN];
29712        int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
29713        if( len<0 ){
29714          pFile->lastErrno = errno;
29715          return SQLITE_IOERR_LOCK;
29716        }
29717        if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
29718          /* don't break the lock if the host id doesn't match */
29719          if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
29720            return SQLITE_BUSY;
29721          }
29722        }else{
29723          /* don't break the lock on short read or a version mismatch */
29724          return SQLITE_BUSY;
29725        }
29726        usleep(10000000); /* wait 10 sec and try the lock again */
29727        continue;
29728      }
29729
29730      assert( nTries==3 );
29731      if( 0==proxyBreakConchLock(pFile, myHostID) ){
29732        rc = SQLITE_OK;
29733        if( lockType==EXCLUSIVE_LOCK ){
29734          rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
29735        }
29736        if( !rc ){
29737          rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
29738        }
29739      }
29740    }
29741  } while( rc==SQLITE_BUSY && nTries<3 );
29742
29743  return rc;
29744}
29745
29746/* Takes the conch by taking a shared lock and read the contents conch, if
29747** lockPath is non-NULL, the host ID and lock file path must match.  A NULL
29748** lockPath means that the lockPath in the conch file will be used if the
29749** host IDs match, or a new lock path will be generated automatically
29750** and written to the conch file.
29751*/
29752static int proxyTakeConch(unixFile *pFile){
29753  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
29754
29755  if( pCtx->conchHeld!=0 ){
29756    return SQLITE_OK;
29757  }else{
29758    unixFile *conchFile = pCtx->conchFile;
29759    uuid_t myHostID;
29760    int pError = 0;
29761    char readBuf[PROXY_MAXCONCHLEN];
29762    char lockPath[MAXPATHLEN];
29763    char *tempLockPath = NULL;
29764    int rc = SQLITE_OK;
29765    int createConch = 0;
29766    int hostIdMatch = 0;
29767    int readLen = 0;
29768    int tryOldLockPath = 0;
29769    int forceNewLockPath = 0;
29770
29771    OSTRACE(("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
29772             (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
29773
29774    rc = proxyGetHostID(myHostID, &pError);
29775    if( (rc&0xff)==SQLITE_IOERR ){
29776      pFile->lastErrno = pError;
29777      goto end_takeconch;
29778    }
29779    rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
29780    if( rc!=SQLITE_OK ){
29781      goto end_takeconch;
29782    }
29783    /* read the existing conch file */
29784    readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
29785    if( readLen<0 ){
29786      /* I/O error: lastErrno set by seekAndRead */
29787      pFile->lastErrno = conchFile->lastErrno;
29788      rc = SQLITE_IOERR_READ;
29789      goto end_takeconch;
29790    }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
29791             readBuf[0]!=(char)PROXY_CONCHVERSION ){
29792      /* a short read or version format mismatch means we need to create a new
29793      ** conch file.
29794      */
29795      createConch = 1;
29796    }
29797    /* if the host id matches and the lock path already exists in the conch
29798    ** we'll try to use the path there, if we can't open that path, we'll
29799    ** retry with a new auto-generated path
29800    */
29801    do { /* in case we need to try again for an :auto: named lock file */
29802
29803      if( !createConch && !forceNewLockPath ){
29804        hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
29805                                  PROXY_HOSTIDLEN);
29806        /* if the conch has data compare the contents */
29807        if( !pCtx->lockProxyPath ){
29808          /* for auto-named local lock file, just check the host ID and we'll
29809           ** use the local lock file path that's already in there
29810           */
29811          if( hostIdMatch ){
29812            size_t pathLen = (readLen - PROXY_PATHINDEX);
29813
29814            if( pathLen>=MAXPATHLEN ){
29815              pathLen=MAXPATHLEN-1;
29816            }
29817            memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
29818            lockPath[pathLen] = 0;
29819            tempLockPath = lockPath;
29820            tryOldLockPath = 1;
29821            /* create a copy of the lock path if the conch is taken */
29822            goto end_takeconch;
29823          }
29824        }else if( hostIdMatch
29825               && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
29826                           readLen-PROXY_PATHINDEX)
29827        ){
29828          /* conch host and lock path match */
29829          goto end_takeconch;
29830        }
29831      }
29832
29833      /* if the conch isn't writable and doesn't match, we can't take it */
29834      if( (conchFile->openFlags&O_RDWR) == 0 ){
29835        rc = SQLITE_BUSY;
29836        goto end_takeconch;
29837      }
29838
29839      /* either the conch didn't match or we need to create a new one */
29840      if( !pCtx->lockProxyPath ){
29841        proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
29842        tempLockPath = lockPath;
29843        /* create a copy of the lock path _only_ if the conch is taken */
29844      }
29845
29846      /* update conch with host and path (this will fail if other process
29847      ** has a shared lock already), if the host id matches, use the big
29848      ** stick.
29849      */
29850      futimes(conchFile->h, NULL);
29851      if( hostIdMatch && !createConch ){
29852        if( conchFile->pInode && conchFile->pInode->nShared>1 ){
29853          /* We are trying for an exclusive lock but another thread in this
29854           ** same process is still holding a shared lock. */
29855          rc = SQLITE_BUSY;
29856        } else {
29857          rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
29858        }
29859      }else{
29860        rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
29861      }
29862      if( rc==SQLITE_OK ){
29863        char writeBuffer[PROXY_MAXCONCHLEN];
29864        int writeSize = 0;
29865
29866        writeBuffer[0] = (char)PROXY_CONCHVERSION;
29867        memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
29868        if( pCtx->lockProxyPath!=NULL ){
29869          strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
29870        }else{
29871          strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
29872        }
29873        writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
29874        robust_ftruncate(conchFile->h, writeSize);
29875        rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
29876        fsync(conchFile->h);
29877        /* If we created a new conch file (not just updated the contents of a
29878         ** valid conch file), try to match the permissions of the database
29879         */
29880        if( rc==SQLITE_OK && createConch ){
29881          struct stat buf;
29882          int err = osFstat(pFile->h, &buf);
29883          if( err==0 ){
29884            mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
29885                                        S_IROTH|S_IWOTH);
29886            /* try to match the database file R/W permissions, ignore failure */
29887#ifndef SQLITE_PROXY_DEBUG
29888            osFchmod(conchFile->h, cmode);
29889#else
29890            do{
29891              rc = osFchmod(conchFile->h, cmode);
29892            }while( rc==(-1) && errno==EINTR );
29893            if( rc!=0 ){
29894              int code = errno;
29895              fprintf(stderr, "fchmod %o FAILED with %d %s\n",
29896                      cmode, code, strerror(code));
29897            } else {
29898              fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
29899            }
29900          }else{
29901            int code = errno;
29902            fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
29903                    err, code, strerror(code));
29904#endif
29905          }
29906        }
29907      }
29908      conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
29909
29910    end_takeconch:
29911      OSTRACE(("TRANSPROXY: CLOSE  %d\n", pFile->h));
29912      if( rc==SQLITE_OK && pFile->openFlags ){
29913        int fd;
29914        if( pFile->h>=0 ){
29915          robust_close(pFile, pFile->h, __LINE__);
29916        }
29917        pFile->h = -1;
29918        fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
29919        OSTRACE(("TRANSPROXY: OPEN  %d\n", fd));
29920        if( fd>=0 ){
29921          pFile->h = fd;
29922        }else{
29923          rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
29924           during locking */
29925        }
29926      }
29927      if( rc==SQLITE_OK && !pCtx->lockProxy ){
29928        char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
29929        rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
29930        if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
29931          /* we couldn't create the proxy lock file with the old lock file path
29932           ** so try again via auto-naming
29933           */
29934          forceNewLockPath = 1;
29935          tryOldLockPath = 0;
29936          continue; /* go back to the do {} while start point, try again */
29937        }
29938      }
29939      if( rc==SQLITE_OK ){
29940        /* Need to make a copy of path if we extracted the value
29941         ** from the conch file or the path was allocated on the stack
29942         */
29943        if( tempLockPath ){
29944          pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
29945          if( !pCtx->lockProxyPath ){
29946            rc = SQLITE_NOMEM;
29947          }
29948        }
29949      }
29950      if( rc==SQLITE_OK ){
29951        pCtx->conchHeld = 1;
29952
29953        if( pCtx->lockProxy->pMethod == &afpIoMethods ){
29954          afpLockingContext *afpCtx;
29955          afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
29956          afpCtx->dbPath = pCtx->lockProxyPath;
29957        }
29958      } else {
29959        conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
29960      }
29961      OSTRACE(("TAKECONCH  %d %s\n", conchFile->h,
29962               rc==SQLITE_OK?"ok":"failed"));
29963      return rc;
29964    } while (1); /* in case we need to retry the :auto: lock file -
29965                 ** we should never get here except via the 'continue' call. */
29966  }
29967}
29968
29969/*
29970** If pFile holds a lock on a conch file, then release that lock.
29971*/
29972static int proxyReleaseConch(unixFile *pFile){
29973  int rc = SQLITE_OK;         /* Subroutine return code */
29974  proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
29975  unixFile *conchFile;        /* Name of the conch file */
29976
29977  pCtx = (proxyLockingContext *)pFile->lockingContext;
29978  conchFile = pCtx->conchFile;
29979  OSTRACE(("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
29980           (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
29981           getpid()));
29982  if( pCtx->conchHeld>0 ){
29983    rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
29984  }
29985  pCtx->conchHeld = 0;
29986  OSTRACE(("RELEASECONCH  %d %s\n", conchFile->h,
29987           (rc==SQLITE_OK ? "ok" : "failed")));
29988  return rc;
29989}
29990
29991/*
29992** Given the name of a database file, compute the name of its conch file.
29993** Store the conch filename in memory obtained from sqlite3_malloc().
29994** Make *pConchPath point to the new name.  Return SQLITE_OK on success
29995** or SQLITE_NOMEM if unable to obtain memory.
29996**
29997** The caller is responsible for ensuring that the allocated memory
29998** space is eventually freed.
29999**
30000** *pConchPath is set to NULL if a memory allocation error occurs.
30001*/
30002static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
30003  int i;                        /* Loop counter */
30004  int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
30005  char *conchPath;              /* buffer in which to construct conch name */
30006
30007  /* Allocate space for the conch filename and initialize the name to
30008  ** the name of the original database file. */
30009  *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
30010  if( conchPath==0 ){
30011    return SQLITE_NOMEM;
30012  }
30013  memcpy(conchPath, dbPath, len+1);
30014
30015  /* now insert a "." before the last / character */
30016  for( i=(len-1); i>=0; i-- ){
30017    if( conchPath[i]=='/' ){
30018      i++;
30019      break;
30020    }
30021  }
30022  conchPath[i]='.';
30023  while ( i<len ){
30024    conchPath[i+1]=dbPath[i];
30025    i++;
30026  }
30027
30028  /* append the "-conch" suffix to the file */
30029  memcpy(&conchPath[i+1], "-conch", 7);
30030  assert( (int)strlen(conchPath) == len+7 );
30031
30032  return SQLITE_OK;
30033}
30034
30035
30036/* Takes a fully configured proxy locking-style unix file and switches
30037** the local lock file path
30038*/
30039static int switchLockProxyPath(unixFile *pFile, const char *path) {
30040  proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
30041  char *oldPath = pCtx->lockProxyPath;
30042  int rc = SQLITE_OK;
30043
30044  if( pFile->eFileLock!=NO_LOCK ){
30045    return SQLITE_BUSY;
30046  }
30047
30048  /* nothing to do if the path is NULL, :auto: or matches the existing path */
30049  if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
30050    (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
30051    return SQLITE_OK;
30052  }else{
30053    unixFile *lockProxy = pCtx->lockProxy;
30054    pCtx->lockProxy=NULL;
30055    pCtx->conchHeld = 0;
30056    if( lockProxy!=NULL ){
30057      rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
30058      if( rc ) return rc;
30059      sqlite3_free(lockProxy);
30060    }
30061    sqlite3_free(oldPath);
30062    pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
30063  }
30064
30065  return rc;
30066}
30067
30068/*
30069** pFile is a file that has been opened by a prior xOpen call.  dbPath
30070** is a string buffer at least MAXPATHLEN+1 characters in size.
30071**
30072** This routine find the filename associated with pFile and writes it
30073** int dbPath.
30074*/
30075static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
30076#if defined(__APPLE__)
30077  if( pFile->pMethod == &afpIoMethods ){
30078    /* afp style keeps a reference to the db path in the filePath field
30079    ** of the struct */
30080    assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
30081    strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
30082  } else
30083#endif
30084  if( pFile->pMethod == &dotlockIoMethods ){
30085    /* dot lock style uses the locking context to store the dot lock
30086    ** file path */
30087    int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
30088    memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
30089  }else{
30090    /* all other styles use the locking context to store the db file path */
30091    assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
30092    strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
30093  }
30094  return SQLITE_OK;
30095}
30096
30097/*
30098** Takes an already filled in unix file and alters it so all file locking
30099** will be performed on the local proxy lock file.  The following fields
30100** are preserved in the locking context so that they can be restored and
30101** the unix structure properly cleaned up at close time:
30102**  ->lockingContext
30103**  ->pMethod
30104*/
30105static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
30106  proxyLockingContext *pCtx;
30107  char dbPath[MAXPATHLEN+1];       /* Name of the database file */
30108  char *lockPath=NULL;
30109  int rc = SQLITE_OK;
30110
30111  if( pFile->eFileLock!=NO_LOCK ){
30112    return SQLITE_BUSY;
30113  }
30114  proxyGetDbPathForUnixFile(pFile, dbPath);
30115  if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
30116    lockPath=NULL;
30117  }else{
30118    lockPath=(char *)path;
30119  }
30120
30121  OSTRACE(("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
30122           (lockPath ? lockPath : ":auto:"), getpid()));
30123
30124  pCtx = sqlite3_malloc( sizeof(*pCtx) );
30125  if( pCtx==0 ){
30126    return SQLITE_NOMEM;
30127  }
30128  memset(pCtx, 0, sizeof(*pCtx));
30129
30130  rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
30131  if( rc==SQLITE_OK ){
30132    rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
30133    if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
30134      /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
30135      ** (c) the file system is read-only, then enable no-locking access.
30136      ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
30137      ** that openFlags will have only one of O_RDONLY or O_RDWR.
30138      */
30139      struct statfs fsInfo;
30140      struct stat conchInfo;
30141      int goLockless = 0;
30142
30143      if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
30144        int err = errno;
30145        if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
30146          goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
30147        }
30148      }
30149      if( goLockless ){
30150        pCtx->conchHeld = -1; /* read only FS/ lockless */
30151        rc = SQLITE_OK;
30152      }
30153    }
30154  }
30155  if( rc==SQLITE_OK && lockPath ){
30156    pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
30157  }
30158
30159  if( rc==SQLITE_OK ){
30160    pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
30161    if( pCtx->dbPath==NULL ){
30162      rc = SQLITE_NOMEM;
30163    }
30164  }
30165  if( rc==SQLITE_OK ){
30166    /* all memory is allocated, proxys are created and assigned,
30167    ** switch the locking context and pMethod then return.
30168    */
30169    pCtx->oldLockingContext = pFile->lockingContext;
30170    pFile->lockingContext = pCtx;
30171    pCtx->pOldMethod = pFile->pMethod;
30172    pFile->pMethod = &proxyIoMethods;
30173  }else{
30174    if( pCtx->conchFile ){
30175      pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
30176      sqlite3_free(pCtx->conchFile);
30177    }
30178    sqlite3DbFree(0, pCtx->lockProxyPath);
30179    sqlite3_free(pCtx->conchFilePath);
30180    sqlite3_free(pCtx);
30181  }
30182  OSTRACE(("TRANSPROXY  %d %s\n", pFile->h,
30183           (rc==SQLITE_OK ? "ok" : "failed")));
30184  return rc;
30185}
30186
30187
30188/*
30189** This routine handles sqlite3_file_control() calls that are specific
30190** to proxy locking.
30191*/
30192static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
30193  switch( op ){
30194    case SQLITE_GET_LOCKPROXYFILE: {
30195      unixFile *pFile = (unixFile*)id;
30196      if( pFile->pMethod == &proxyIoMethods ){
30197        proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
30198        proxyTakeConch(pFile);
30199        if( pCtx->lockProxyPath ){
30200          *(const char **)pArg = pCtx->lockProxyPath;
30201        }else{
30202          *(const char **)pArg = ":auto: (not held)";
30203        }
30204      } else {
30205        *(const char **)pArg = NULL;
30206      }
30207      return SQLITE_OK;
30208    }
30209    case SQLITE_SET_LOCKPROXYFILE: {
30210      unixFile *pFile = (unixFile*)id;
30211      int rc = SQLITE_OK;
30212      int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
30213      if( pArg==NULL || (const char *)pArg==0 ){
30214        if( isProxyStyle ){
30215          /* turn off proxy locking - not supported */
30216          rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
30217        }else{
30218          /* turn off proxy locking - already off - NOOP */
30219          rc = SQLITE_OK;
30220        }
30221      }else{
30222        const char *proxyPath = (const char *)pArg;
30223        if( isProxyStyle ){
30224          proxyLockingContext *pCtx =
30225            (proxyLockingContext*)pFile->lockingContext;
30226          if( !strcmp(pArg, ":auto:")
30227           || (pCtx->lockProxyPath &&
30228               !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
30229          ){
30230            rc = SQLITE_OK;
30231          }else{
30232            rc = switchLockProxyPath(pFile, proxyPath);
30233          }
30234        }else{
30235          /* turn on proxy file locking */
30236          rc = proxyTransformUnixFile(pFile, proxyPath);
30237        }
30238      }
30239      return rc;
30240    }
30241    default: {
30242      assert( 0 );  /* The call assures that only valid opcodes are sent */
30243    }
30244  }
30245  /*NOTREACHED*/
30246  return SQLITE_ERROR;
30247}
30248
30249/*
30250** Within this division (the proxying locking implementation) the procedures
30251** above this point are all utilities.  The lock-related methods of the
30252** proxy-locking sqlite3_io_method object follow.
30253*/
30254
30255
30256/*
30257** This routine checks if there is a RESERVED lock held on the specified
30258** file by this or any other process. If such a lock is held, set *pResOut
30259** to a non-zero value otherwise *pResOut is set to zero.  The return value
30260** is set to SQLITE_OK unless an I/O error occurs during lock checking.
30261*/
30262static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
30263  unixFile *pFile = (unixFile*)id;
30264  int rc = proxyTakeConch(pFile);
30265  if( rc==SQLITE_OK ){
30266    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30267    if( pCtx->conchHeld>0 ){
30268      unixFile *proxy = pCtx->lockProxy;
30269      return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
30270    }else{ /* conchHeld < 0 is lockless */
30271      pResOut=0;
30272    }
30273  }
30274  return rc;
30275}
30276
30277/*
30278** Lock the file with the lock specified by parameter eFileLock - one
30279** of the following:
30280**
30281**     (1) SHARED_LOCK
30282**     (2) RESERVED_LOCK
30283**     (3) PENDING_LOCK
30284**     (4) EXCLUSIVE_LOCK
30285**
30286** Sometimes when requesting one lock state, additional lock states
30287** are inserted in between.  The locking might fail on one of the later
30288** transitions leaving the lock state different from what it started but
30289** still short of its goal.  The following chart shows the allowed
30290** transitions and the inserted intermediate states:
30291**
30292**    UNLOCKED -> SHARED
30293**    SHARED -> RESERVED
30294**    SHARED -> (PENDING) -> EXCLUSIVE
30295**    RESERVED -> (PENDING) -> EXCLUSIVE
30296**    PENDING -> EXCLUSIVE
30297**
30298** This routine will only increase a lock.  Use the sqlite3OsUnlock()
30299** routine to lower a locking level.
30300*/
30301static int proxyLock(sqlite3_file *id, int eFileLock) {
30302  unixFile *pFile = (unixFile*)id;
30303  int rc = proxyTakeConch(pFile);
30304  if( rc==SQLITE_OK ){
30305    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30306    if( pCtx->conchHeld>0 ){
30307      unixFile *proxy = pCtx->lockProxy;
30308      rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
30309      pFile->eFileLock = proxy->eFileLock;
30310    }else{
30311      /* conchHeld < 0 is lockless */
30312    }
30313  }
30314  return rc;
30315}
30316
30317
30318/*
30319** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
30320** must be either NO_LOCK or SHARED_LOCK.
30321**
30322** If the locking level of the file descriptor is already at or below
30323** the requested locking level, this routine is a no-op.
30324*/
30325static int proxyUnlock(sqlite3_file *id, int eFileLock) {
30326  unixFile *pFile = (unixFile*)id;
30327  int rc = proxyTakeConch(pFile);
30328  if( rc==SQLITE_OK ){
30329    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30330    if( pCtx->conchHeld>0 ){
30331      unixFile *proxy = pCtx->lockProxy;
30332      rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
30333      pFile->eFileLock = proxy->eFileLock;
30334    }else{
30335      /* conchHeld < 0 is lockless */
30336    }
30337  }
30338  return rc;
30339}
30340
30341/*
30342** Close a file that uses proxy locks.
30343*/
30344static int proxyClose(sqlite3_file *id) {
30345  if( id ){
30346    unixFile *pFile = (unixFile*)id;
30347    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30348    unixFile *lockProxy = pCtx->lockProxy;
30349    unixFile *conchFile = pCtx->conchFile;
30350    int rc = SQLITE_OK;
30351
30352    if( lockProxy ){
30353      rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
30354      if( rc ) return rc;
30355      rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
30356      if( rc ) return rc;
30357      sqlite3_free(lockProxy);
30358      pCtx->lockProxy = 0;
30359    }
30360    if( conchFile ){
30361      if( pCtx->conchHeld ){
30362        rc = proxyReleaseConch(pFile);
30363        if( rc ) return rc;
30364      }
30365      rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
30366      if( rc ) return rc;
30367      sqlite3_free(conchFile);
30368    }
30369    sqlite3DbFree(0, pCtx->lockProxyPath);
30370    sqlite3_free(pCtx->conchFilePath);
30371    sqlite3DbFree(0, pCtx->dbPath);
30372    /* restore the original locking context and pMethod then close it */
30373    pFile->lockingContext = pCtx->oldLockingContext;
30374    pFile->pMethod = pCtx->pOldMethod;
30375    sqlite3_free(pCtx);
30376    return pFile->pMethod->xClose(id);
30377  }
30378  return SQLITE_OK;
30379}
30380
30381
30382
30383#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
30384/*
30385** The proxy locking style is intended for use with AFP filesystems.
30386** And since AFP is only supported on MacOSX, the proxy locking is also
30387** restricted to MacOSX.
30388**
30389**
30390******************* End of the proxy lock implementation **********************
30391******************************************************************************/
30392
30393/*
30394** Initialize the operating system interface.
30395**
30396** This routine registers all VFS implementations for unix-like operating
30397** systems.  This routine, and the sqlite3_os_end() routine that follows,
30398** should be the only routines in this file that are visible from other
30399** files.
30400**
30401** This routine is called once during SQLite initialization and by a
30402** single thread.  The memory allocation and mutex subsystems have not
30403** necessarily been initialized when this routine is called, and so they
30404** should not be used.
30405*/
30406SQLITE_API int sqlite3_os_init(void){
30407  /*
30408  ** The following macro defines an initializer for an sqlite3_vfs object.
30409  ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
30410  ** to the "finder" function.  (pAppData is a pointer to a pointer because
30411  ** silly C90 rules prohibit a void* from being cast to a function pointer
30412  ** and so we have to go through the intermediate pointer to avoid problems
30413  ** when compiling with -pedantic-errors on GCC.)
30414  **
30415  ** The FINDER parameter to this macro is the name of the pointer to the
30416  ** finder-function.  The finder-function returns a pointer to the
30417  ** sqlite_io_methods object that implements the desired locking
30418  ** behaviors.  See the division above that contains the IOMETHODS
30419  ** macro for addition information on finder-functions.
30420  **
30421  ** Most finders simply return a pointer to a fixed sqlite3_io_methods
30422  ** object.  But the "autolockIoFinder" available on MacOSX does a little
30423  ** more than that; it looks at the filesystem type that hosts the
30424  ** database file and tries to choose an locking method appropriate for
30425  ** that filesystem time.
30426  */
30427  #define UNIXVFS(VFSNAME, FINDER) {                        \
30428    3,                    /* iVersion */                    \
30429    sizeof(unixFile),     /* szOsFile */                    \
30430    MAX_PATHNAME,         /* mxPathname */                  \
30431    0,                    /* pNext */                       \
30432    VFSNAME,              /* zName */                       \
30433    (void*)&FINDER,       /* pAppData */                    \
30434    unixOpen,             /* xOpen */                       \
30435    unixDelete,           /* xDelete */                     \
30436    unixAccess,           /* xAccess */                     \
30437    unixFullPathname,     /* xFullPathname */               \
30438    unixDlOpen,           /* xDlOpen */                     \
30439    unixDlError,          /* xDlError */                    \
30440    unixDlSym,            /* xDlSym */                      \
30441    unixDlClose,          /* xDlClose */                    \
30442    unixRandomness,       /* xRandomness */                 \
30443    unixSleep,            /* xSleep */                      \
30444    unixCurrentTime,      /* xCurrentTime */                \
30445    unixGetLastError,     /* xGetLastError */               \
30446    unixCurrentTimeInt64, /* xCurrentTimeInt64 */           \
30447    unixSetSystemCall,    /* xSetSystemCall */              \
30448    unixGetSystemCall,    /* xGetSystemCall */              \
30449    unixNextSystemCall,   /* xNextSystemCall */             \
30450  }
30451
30452  /*
30453  ** All default VFSes for unix are contained in the following array.
30454  **
30455  ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
30456  ** by the SQLite core when the VFS is registered.  So the following
30457  ** array cannot be const.
30458  */
30459  static sqlite3_vfs aVfs[] = {
30460#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
30461    UNIXVFS("unix",          autolockIoFinder ),
30462#else
30463    UNIXVFS("unix",          posixIoFinder ),
30464#endif
30465    UNIXVFS("unix-none",     nolockIoFinder ),
30466    UNIXVFS("unix-dotfile",  dotlockIoFinder ),
30467    UNIXVFS("unix-excl",     posixIoFinder ),
30468#if OS_VXWORKS
30469    UNIXVFS("unix-namedsem", semIoFinder ),
30470#endif
30471#if SQLITE_ENABLE_LOCKING_STYLE
30472    UNIXVFS("unix-posix",    posixIoFinder ),
30473#if !OS_VXWORKS
30474    UNIXVFS("unix-flock",    flockIoFinder ),
30475#endif
30476#endif
30477#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
30478    UNIXVFS("unix-afp",      afpIoFinder ),
30479    UNIXVFS("unix-nfs",      nfsIoFinder ),
30480    UNIXVFS("unix-proxy",    proxyIoFinder ),
30481#endif
30482  };
30483  unsigned int i;          /* Loop counter */
30484
30485  /* Double-check that the aSyscall[] array has been constructed
30486  ** correctly.  See ticket [bb3a86e890c8e96ab] */
30487  assert( ArraySize(aSyscall)==24 );
30488
30489  /* Register all VFSes defined in the aVfs[] array */
30490  for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
30491    sqlite3_vfs_register(&aVfs[i], i==0);
30492  }
30493  return SQLITE_OK;
30494}
30495
30496/*
30497** Shutdown the operating system interface.
30498**
30499** Some operating systems might need to do some cleanup in this routine,
30500** to release dynamically allocated objects.  But not on unix.
30501** This routine is a no-op for unix.
30502*/
30503SQLITE_API int sqlite3_os_end(void){
30504  return SQLITE_OK;
30505}
30506
30507#endif /* SQLITE_OS_UNIX */
30508
30509/************** End of os_unix.c *********************************************/
30510/************** Begin file os_win.c ******************************************/
30511/*
30512** 2004 May 22
30513**
30514** The author disclaims copyright to this source code.  In place of
30515** a legal notice, here is a blessing:
30516**
30517**    May you do good and not evil.
30518**    May you find forgiveness for yourself and forgive others.
30519**    May you share freely, never taking more than you give.
30520**
30521******************************************************************************
30522**
30523** This file contains code that is specific to Windows.
30524*/
30525#if SQLITE_OS_WIN               /* This file is used for Windows only */
30526
30527#ifdef __CYGWIN__
30528# include <sys/cygwin.h>
30529#endif
30530
30531/*
30532** Include code that is common to all os_*.c files
30533*/
30534/************** Include os_common.h in the middle of os_win.c ****************/
30535/************** Begin file os_common.h ***************************************/
30536/*
30537** 2004 May 22
30538**
30539** The author disclaims copyright to this source code.  In place of
30540** a legal notice, here is a blessing:
30541**
30542**    May you do good and not evil.
30543**    May you find forgiveness for yourself and forgive others.
30544**    May you share freely, never taking more than you give.
30545**
30546******************************************************************************
30547**
30548** This file contains macros and a little bit of code that is common to
30549** all of the platform-specific files (os_*.c) and is #included into those
30550** files.
30551**
30552** This file should be #included by the os_*.c files only.  It is not a
30553** general purpose header file.
30554*/
30555#ifndef _OS_COMMON_H_
30556#define _OS_COMMON_H_
30557
30558/*
30559** At least two bugs have slipped in because we changed the MEMORY_DEBUG
30560** macro to SQLITE_DEBUG and some older makefiles have not yet made the
30561** switch.  The following code should catch this problem at compile-time.
30562*/
30563#ifdef MEMORY_DEBUG
30564# error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
30565#endif
30566
30567#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
30568# ifndef SQLITE_DEBUG_OS_TRACE
30569#   define SQLITE_DEBUG_OS_TRACE 0
30570# endif
30571  int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
30572# define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
30573#else
30574# define OSTRACE(X)
30575#endif
30576
30577/*
30578** Macros for performance tracing.  Normally turned off.  Only works
30579** on i486 hardware.
30580*/
30581#ifdef SQLITE_PERFORMANCE_TRACE
30582
30583/*
30584** hwtime.h contains inline assembler code for implementing
30585** high-performance timing routines.
30586*/
30587/************** Include hwtime.h in the middle of os_common.h ****************/
30588/************** Begin file hwtime.h ******************************************/
30589/*
30590** 2008 May 27
30591**
30592** The author disclaims copyright to this source code.  In place of
30593** a legal notice, here is a blessing:
30594**
30595**    May you do good and not evil.
30596**    May you find forgiveness for yourself and forgive others.
30597**    May you share freely, never taking more than you give.
30598**
30599******************************************************************************
30600**
30601** This file contains inline asm code for retrieving "high-performance"
30602** counters for x86 class CPUs.
30603*/
30604#ifndef _HWTIME_H_
30605#define _HWTIME_H_
30606
30607/*
30608** The following routine only works on pentium-class (or newer) processors.
30609** It uses the RDTSC opcode to read the cycle count value out of the
30610** processor and returns that value.  This can be used for high-res
30611** profiling.
30612*/
30613#if (defined(__GNUC__) || defined(_MSC_VER)) && \
30614      (defined(i386) || defined(__i386__) || defined(_M_IX86))
30615
30616  #if defined(__GNUC__)
30617
30618  __inline__ sqlite_uint64 sqlite3Hwtime(void){
30619     unsigned int lo, hi;
30620     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
30621     return (sqlite_uint64)hi << 32 | lo;
30622  }
30623
30624  #elif defined(_MSC_VER)
30625
30626  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
30627     __asm {
30628        rdtsc
30629        ret       ; return value at EDX:EAX
30630     }
30631  }
30632
30633  #endif
30634
30635#elif (defined(__GNUC__) && defined(__x86_64__))
30636
30637  __inline__ sqlite_uint64 sqlite3Hwtime(void){
30638      unsigned long val;
30639      __asm__ __volatile__ ("rdtsc" : "=A" (val));
30640      return val;
30641  }
30642
30643#elif (defined(__GNUC__) && defined(__ppc__))
30644
30645  __inline__ sqlite_uint64 sqlite3Hwtime(void){
30646      unsigned long long retval;
30647      unsigned long junk;
30648      __asm__ __volatile__ ("\n\
30649          1:      mftbu   %1\n\
30650                  mftb    %L0\n\
30651                  mftbu   %0\n\
30652                  cmpw    %0,%1\n\
30653                  bne     1b"
30654                  : "=r" (retval), "=r" (junk));
30655      return retval;
30656  }
30657
30658#else
30659
30660  #error Need implementation of sqlite3Hwtime() for your platform.
30661
30662  /*
30663  ** To compile without implementing sqlite3Hwtime() for your platform,
30664  ** you can remove the above #error and use the following
30665  ** stub function.  You will lose timing support for many
30666  ** of the debugging and testing utilities, but it should at
30667  ** least compile and run.
30668  */
30669SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
30670
30671#endif
30672
30673#endif /* !defined(_HWTIME_H_) */
30674
30675/************** End of hwtime.h **********************************************/
30676/************** Continuing where we left off in os_common.h ******************/
30677
30678static sqlite_uint64 g_start;
30679static sqlite_uint64 g_elapsed;
30680#define TIMER_START       g_start=sqlite3Hwtime()
30681#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
30682#define TIMER_ELAPSED     g_elapsed
30683#else
30684#define TIMER_START
30685#define TIMER_END
30686#define TIMER_ELAPSED     ((sqlite_uint64)0)
30687#endif
30688
30689/*
30690** If we compile with the SQLITE_TEST macro set, then the following block
30691** of code will give us the ability to simulate a disk I/O error.  This
30692** is used for testing the I/O recovery logic.
30693*/
30694#ifdef SQLITE_TEST
30695SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
30696SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
30697SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
30698SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
30699SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
30700SQLITE_API int sqlite3_diskfull_pending = 0;
30701SQLITE_API int sqlite3_diskfull = 0;
30702#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
30703#define SimulateIOError(CODE)  \
30704  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
30705       || sqlite3_io_error_pending-- == 1 )  \
30706              { local_ioerr(); CODE; }
30707static void local_ioerr(){
30708  IOTRACE(("IOERR\n"));
30709  sqlite3_io_error_hit++;
30710  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
30711}
30712#define SimulateDiskfullError(CODE) \
30713   if( sqlite3_diskfull_pending ){ \
30714     if( sqlite3_diskfull_pending == 1 ){ \
30715       local_ioerr(); \
30716       sqlite3_diskfull = 1; \
30717       sqlite3_io_error_hit = 1; \
30718       CODE; \
30719     }else{ \
30720       sqlite3_diskfull_pending--; \
30721     } \
30722   }
30723#else
30724#define SimulateIOErrorBenign(X)
30725#define SimulateIOError(A)
30726#define SimulateDiskfullError(A)
30727#endif
30728
30729/*
30730** When testing, keep a count of the number of open files.
30731*/
30732#ifdef SQLITE_TEST
30733SQLITE_API int sqlite3_open_file_count = 0;
30734#define OpenCounter(X)  sqlite3_open_file_count+=(X)
30735#else
30736#define OpenCounter(X)
30737#endif
30738
30739#endif /* !defined(_OS_COMMON_H_) */
30740
30741/************** End of os_common.h *******************************************/
30742/************** Continuing where we left off in os_win.c *********************/
30743
30744/*
30745** Compiling and using WAL mode requires several APIs that are only
30746** available in Windows platforms based on the NT kernel.
30747*/
30748#if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
30749# error "WAL mode requires support from the Windows NT kernel, compile\
30750 with SQLITE_OMIT_WAL."
30751#endif
30752
30753/*
30754** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
30755** based on the sub-platform)?
30756*/
30757#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
30758#  define SQLITE_WIN32_HAS_ANSI
30759#endif
30760
30761/*
30762** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
30763** based on the sub-platform)?
30764*/
30765#if SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT
30766#  define SQLITE_WIN32_HAS_WIDE
30767#endif
30768
30769/*
30770** Do we need to manually define the Win32 file mapping APIs for use with WAL
30771** mode (e.g. these APIs are available in the Windows CE SDK; however, they
30772** are not present in the header file)?
30773*/
30774#if SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL)
30775/*
30776** Two of the file mapping APIs are different under WinRT.  Figure out which
30777** set we need.
30778*/
30779#if SQLITE_OS_WINRT
30780WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
30781        LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
30782
30783WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
30784#else
30785#if defined(SQLITE_WIN32_HAS_ANSI)
30786WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
30787        DWORD, DWORD, DWORD, LPCSTR);
30788#endif /* defined(SQLITE_WIN32_HAS_ANSI) */
30789
30790#if defined(SQLITE_WIN32_HAS_WIDE)
30791WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
30792        DWORD, DWORD, DWORD, LPCWSTR);
30793#endif /* defined(SQLITE_WIN32_HAS_WIDE) */
30794
30795WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
30796#endif /* SQLITE_OS_WINRT */
30797
30798/*
30799** This file mapping API is common to both Win32 and WinRT.
30800*/
30801WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
30802#endif /* SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL) */
30803
30804/*
30805** Macro to find the minimum of two numeric values.
30806*/
30807#ifndef MIN
30808# define MIN(x,y) ((x)<(y)?(x):(y))
30809#endif
30810
30811/*
30812** Some Microsoft compilers lack this definition.
30813*/
30814#ifndef INVALID_FILE_ATTRIBUTES
30815# define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
30816#endif
30817
30818#ifndef FILE_FLAG_MASK
30819# define FILE_FLAG_MASK          (0xFF3C0000)
30820#endif
30821
30822#ifndef FILE_ATTRIBUTE_MASK
30823# define FILE_ATTRIBUTE_MASK     (0x0003FFF7)
30824#endif
30825
30826#ifndef SQLITE_OMIT_WAL
30827/* Forward references */
30828typedef struct winShm winShm;           /* A connection to shared-memory */
30829typedef struct winShmNode winShmNode;   /* A region of shared-memory */
30830#endif
30831
30832/*
30833** WinCE lacks native support for file locking so we have to fake it
30834** with some code of our own.
30835*/
30836#if SQLITE_OS_WINCE
30837typedef struct winceLock {
30838  int nReaders;       /* Number of reader locks obtained */
30839  BOOL bPending;      /* Indicates a pending lock has been obtained */
30840  BOOL bReserved;     /* Indicates a reserved lock has been obtained */
30841  BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
30842} winceLock;
30843#endif
30844
30845/*
30846** The winFile structure is a subclass of sqlite3_file* specific to the win32
30847** portability layer.
30848*/
30849typedef struct winFile winFile;
30850struct winFile {
30851  const sqlite3_io_methods *pMethod; /*** Must be first ***/
30852  sqlite3_vfs *pVfs;      /* The VFS used to open this file */
30853  HANDLE h;               /* Handle for accessing the file */
30854  u8 locktype;            /* Type of lock currently held on this file */
30855  short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
30856  u8 ctrlFlags;           /* Flags.  See WINFILE_* below */
30857  DWORD lastErrno;        /* The Windows errno from the last I/O error */
30858#ifndef SQLITE_OMIT_WAL
30859  winShm *pShm;           /* Instance of shared memory on this file */
30860#endif
30861  const char *zPath;      /* Full pathname of this file */
30862  int szChunk;            /* Chunk size configured by FCNTL_CHUNK_SIZE */
30863#if SQLITE_OS_WINCE
30864  LPWSTR zDeleteOnClose;  /* Name of file to delete when closing */
30865  HANDLE hMutex;          /* Mutex used to control access to shared lock */
30866  HANDLE hShared;         /* Shared memory segment used for locking */
30867  winceLock local;        /* Locks obtained by this instance of winFile */
30868  winceLock *shared;      /* Global shared lock memory for the file  */
30869#endif
30870#if SQLITE_MAX_MMAP_SIZE>0
30871  int nFetchOut;                /* Number of outstanding xFetch references */
30872  HANDLE hMap;                  /* Handle for accessing memory mapping */
30873  void *pMapRegion;             /* Area memory mapped */
30874  sqlite3_int64 mmapSize;       /* Usable size of mapped region */
30875  sqlite3_int64 mmapSizeActual; /* Actual size of mapped region */
30876  sqlite3_int64 mmapSizeMax;    /* Configured FCNTL_MMAP_SIZE value */
30877#endif
30878};
30879
30880/*
30881** Allowed values for winFile.ctrlFlags
30882*/
30883#define WINFILE_RDONLY          0x02   /* Connection is read only */
30884#define WINFILE_PERSIST_WAL     0x04   /* Persistent WAL mode */
30885#define WINFILE_PSOW            0x10   /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
30886
30887/*
30888 * The size of the buffer used by sqlite3_win32_write_debug().
30889 */
30890#ifndef SQLITE_WIN32_DBG_BUF_SIZE
30891#  define SQLITE_WIN32_DBG_BUF_SIZE   ((int)(4096-sizeof(DWORD)))
30892#endif
30893
30894/*
30895 * The value used with sqlite3_win32_set_directory() to specify that
30896 * the data directory should be changed.
30897 */
30898#ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE
30899#  define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1)
30900#endif
30901
30902/*
30903 * The value used with sqlite3_win32_set_directory() to specify that
30904 * the temporary directory should be changed.
30905 */
30906#ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE
30907#  define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2)
30908#endif
30909
30910/*
30911 * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
30912 * various Win32 API heap functions instead of our own.
30913 */
30914#ifdef SQLITE_WIN32_MALLOC
30915
30916/*
30917 * If this is non-zero, an isolated heap will be created by the native Win32
30918 * allocator subsystem; otherwise, the default process heap will be used.  This
30919 * setting has no effect when compiling for WinRT.  By default, this is enabled
30920 * and an isolated heap will be created to store all allocated data.
30921 *
30922 ******************************************************************************
30923 * WARNING: It is important to note that when this setting is non-zero and the
30924 *          winMemShutdown function is called (e.g. by the sqlite3_shutdown
30925 *          function), all data that was allocated using the isolated heap will
30926 *          be freed immediately and any attempt to access any of that freed
30927 *          data will almost certainly result in an immediate access violation.
30928 ******************************************************************************
30929 */
30930#ifndef SQLITE_WIN32_HEAP_CREATE
30931#  define SQLITE_WIN32_HEAP_CREATE    (TRUE)
30932#endif
30933
30934/*
30935 * The initial size of the Win32-specific heap.  This value may be zero.
30936 */
30937#ifndef SQLITE_WIN32_HEAP_INIT_SIZE
30938#  define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_DEFAULT_CACHE_SIZE) * \
30939                                       (SQLITE_DEFAULT_PAGE_SIZE) + 4194304)
30940#endif
30941
30942/*
30943 * The maximum size of the Win32-specific heap.  This value may be zero.
30944 */
30945#ifndef SQLITE_WIN32_HEAP_MAX_SIZE
30946#  define SQLITE_WIN32_HEAP_MAX_SIZE  (0)
30947#endif
30948
30949/*
30950 * The extra flags to use in calls to the Win32 heap APIs.  This value may be
30951 * zero for the default behavior.
30952 */
30953#ifndef SQLITE_WIN32_HEAP_FLAGS
30954#  define SQLITE_WIN32_HEAP_FLAGS     (0)
30955#endif
30956
30957/*
30958** The winMemData structure stores information required by the Win32-specific
30959** sqlite3_mem_methods implementation.
30960*/
30961typedef struct winMemData winMemData;
30962struct winMemData {
30963#ifndef NDEBUG
30964  u32 magic;    /* Magic number to detect structure corruption. */
30965#endif
30966  HANDLE hHeap; /* The handle to our heap. */
30967  BOOL bOwned;  /* Do we own the heap (i.e. destroy it on shutdown)? */
30968};
30969
30970#ifndef NDEBUG
30971#define WINMEM_MAGIC     0x42b2830b
30972#endif
30973
30974static struct winMemData win_mem_data = {
30975#ifndef NDEBUG
30976  WINMEM_MAGIC,
30977#endif
30978  NULL, FALSE
30979};
30980
30981#ifndef NDEBUG
30982#define winMemAssertMagic() assert( win_mem_data.magic==WINMEM_MAGIC )
30983#else
30984#define winMemAssertMagic()
30985#endif
30986
30987#define winMemGetHeap() win_mem_data.hHeap
30988
30989static void *winMemMalloc(int nBytes);
30990static void winMemFree(void *pPrior);
30991static void *winMemRealloc(void *pPrior, int nBytes);
30992static int winMemSize(void *p);
30993static int winMemRoundup(int n);
30994static int winMemInit(void *pAppData);
30995static void winMemShutdown(void *pAppData);
30996
30997SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
30998#endif /* SQLITE_WIN32_MALLOC */
30999
31000/*
31001** The following variable is (normally) set once and never changes
31002** thereafter.  It records whether the operating system is Win9x
31003** or WinNT.
31004**
31005** 0:   Operating system unknown.
31006** 1:   Operating system is Win9x.
31007** 2:   Operating system is WinNT.
31008**
31009** In order to facilitate testing on a WinNT system, the test fixture
31010** can manually set this value to 1 to emulate Win98 behavior.
31011*/
31012#ifdef SQLITE_TEST
31013SQLITE_API int sqlite3_os_type = 0;
31014#else
31015static int sqlite3_os_type = 0;
31016#endif
31017
31018#ifndef SYSCALL
31019#  define SYSCALL sqlite3_syscall_ptr
31020#endif
31021
31022/*
31023** This function is not available on Windows CE or WinRT.
31024 */
31025
31026#if SQLITE_OS_WINCE || SQLITE_OS_WINRT
31027#  define osAreFileApisANSI()       1
31028#endif
31029
31030/*
31031** Many system calls are accessed through pointer-to-functions so that
31032** they may be overridden at runtime to facilitate fault injection during
31033** testing and sandboxing.  The following array holds the names and pointers
31034** to all overrideable system calls.
31035*/
31036static struct win_syscall {
31037  const char *zName;            /* Name of the system call */
31038  sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
31039  sqlite3_syscall_ptr pDefault; /* Default value */
31040} aSyscall[] = {
31041#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
31042  { "AreFileApisANSI",         (SYSCALL)AreFileApisANSI,         0 },
31043#else
31044  { "AreFileApisANSI",         (SYSCALL)0,                       0 },
31045#endif
31046
31047#ifndef osAreFileApisANSI
31048#define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
31049#endif
31050
31051#if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
31052  { "CharLowerW",              (SYSCALL)CharLowerW,              0 },
31053#else
31054  { "CharLowerW",              (SYSCALL)0,                       0 },
31055#endif
31056
31057#define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
31058
31059#if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
31060  { "CharUpperW",              (SYSCALL)CharUpperW,              0 },
31061#else
31062  { "CharUpperW",              (SYSCALL)0,                       0 },
31063#endif
31064
31065#define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
31066
31067  { "CloseHandle",             (SYSCALL)CloseHandle,             0 },
31068
31069#define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
31070
31071#if defined(SQLITE_WIN32_HAS_ANSI)
31072  { "CreateFileA",             (SYSCALL)CreateFileA,             0 },
31073#else
31074  { "CreateFileA",             (SYSCALL)0,                       0 },
31075#endif
31076
31077#define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
31078        LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
31079
31080#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
31081  { "CreateFileW",             (SYSCALL)CreateFileW,             0 },
31082#else
31083  { "CreateFileW",             (SYSCALL)0,                       0 },
31084#endif
31085
31086#define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
31087        LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
31088
31089#if (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
31090        !defined(SQLITE_OMIT_WAL))
31091  { "CreateFileMappingA",      (SYSCALL)CreateFileMappingA,      0 },
31092#else
31093  { "CreateFileMappingA",      (SYSCALL)0,                       0 },
31094#endif
31095
31096#define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
31097        DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
31098
31099#if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
31100        !defined(SQLITE_OMIT_WAL))
31101  { "CreateFileMappingW",      (SYSCALL)CreateFileMappingW,      0 },
31102#else
31103  { "CreateFileMappingW",      (SYSCALL)0,                       0 },
31104#endif
31105
31106#define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
31107        DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
31108
31109#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
31110  { "CreateMutexW",            (SYSCALL)CreateMutexW,            0 },
31111#else
31112  { "CreateMutexW",            (SYSCALL)0,                       0 },
31113#endif
31114
31115#define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
31116        LPCWSTR))aSyscall[8].pCurrent)
31117
31118#if defined(SQLITE_WIN32_HAS_ANSI)
31119  { "DeleteFileA",             (SYSCALL)DeleteFileA,             0 },
31120#else
31121  { "DeleteFileA",             (SYSCALL)0,                       0 },
31122#endif
31123
31124#define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
31125
31126#if defined(SQLITE_WIN32_HAS_WIDE)
31127  { "DeleteFileW",             (SYSCALL)DeleteFileW,             0 },
31128#else
31129  { "DeleteFileW",             (SYSCALL)0,                       0 },
31130#endif
31131
31132#define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
31133
31134#if SQLITE_OS_WINCE
31135  { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
31136#else
31137  { "FileTimeToLocalFileTime", (SYSCALL)0,                       0 },
31138#endif
31139
31140#define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
31141        LPFILETIME))aSyscall[11].pCurrent)
31142
31143#if SQLITE_OS_WINCE
31144  { "FileTimeToSystemTime",    (SYSCALL)FileTimeToSystemTime,    0 },
31145#else
31146  { "FileTimeToSystemTime",    (SYSCALL)0,                       0 },
31147#endif
31148
31149#define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
31150        LPSYSTEMTIME))aSyscall[12].pCurrent)
31151
31152  { "FlushFileBuffers",        (SYSCALL)FlushFileBuffers,        0 },
31153
31154#define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
31155
31156#if defined(SQLITE_WIN32_HAS_ANSI)
31157  { "FormatMessageA",          (SYSCALL)FormatMessageA,          0 },
31158#else
31159  { "FormatMessageA",          (SYSCALL)0,                       0 },
31160#endif
31161
31162#define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
31163        DWORD,va_list*))aSyscall[14].pCurrent)
31164
31165#if defined(SQLITE_WIN32_HAS_WIDE)
31166  { "FormatMessageW",          (SYSCALL)FormatMessageW,          0 },
31167#else
31168  { "FormatMessageW",          (SYSCALL)0,                       0 },
31169#endif
31170
31171#define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
31172        DWORD,va_list*))aSyscall[15].pCurrent)
31173
31174#if !defined(SQLITE_OMIT_LOAD_EXTENSION)
31175  { "FreeLibrary",             (SYSCALL)FreeLibrary,             0 },
31176#else
31177  { "FreeLibrary",             (SYSCALL)0,                       0 },
31178#endif
31179
31180#define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
31181
31182  { "GetCurrentProcessId",     (SYSCALL)GetCurrentProcessId,     0 },
31183
31184#define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
31185
31186#if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
31187  { "GetDiskFreeSpaceA",       (SYSCALL)GetDiskFreeSpaceA,       0 },
31188#else
31189  { "GetDiskFreeSpaceA",       (SYSCALL)0,                       0 },
31190#endif
31191
31192#define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
31193        LPDWORD))aSyscall[18].pCurrent)
31194
31195#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
31196  { "GetDiskFreeSpaceW",       (SYSCALL)GetDiskFreeSpaceW,       0 },
31197#else
31198  { "GetDiskFreeSpaceW",       (SYSCALL)0,                       0 },
31199#endif
31200
31201#define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
31202        LPDWORD))aSyscall[19].pCurrent)
31203
31204#if defined(SQLITE_WIN32_HAS_ANSI)
31205  { "GetFileAttributesA",      (SYSCALL)GetFileAttributesA,      0 },
31206#else
31207  { "GetFileAttributesA",      (SYSCALL)0,                       0 },
31208#endif
31209
31210#define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
31211
31212#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
31213  { "GetFileAttributesW",      (SYSCALL)GetFileAttributesW,      0 },
31214#else
31215  { "GetFileAttributesW",      (SYSCALL)0,                       0 },
31216#endif
31217
31218#define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
31219
31220#if defined(SQLITE_WIN32_HAS_WIDE)
31221  { "GetFileAttributesExW",    (SYSCALL)GetFileAttributesExW,    0 },
31222#else
31223  { "GetFileAttributesExW",    (SYSCALL)0,                       0 },
31224#endif
31225
31226#define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
31227        LPVOID))aSyscall[22].pCurrent)
31228
31229#if !SQLITE_OS_WINRT
31230  { "GetFileSize",             (SYSCALL)GetFileSize,             0 },
31231#else
31232  { "GetFileSize",             (SYSCALL)0,                       0 },
31233#endif
31234
31235#define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
31236
31237#if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
31238  { "GetFullPathNameA",        (SYSCALL)GetFullPathNameA,        0 },
31239#else
31240  { "GetFullPathNameA",        (SYSCALL)0,                       0 },
31241#endif
31242
31243#define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
31244        LPSTR*))aSyscall[24].pCurrent)
31245
31246#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
31247  { "GetFullPathNameW",        (SYSCALL)GetFullPathNameW,        0 },
31248#else
31249  { "GetFullPathNameW",        (SYSCALL)0,                       0 },
31250#endif
31251
31252#define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
31253        LPWSTR*))aSyscall[25].pCurrent)
31254
31255  { "GetLastError",            (SYSCALL)GetLastError,            0 },
31256
31257#define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
31258
31259#if !defined(SQLITE_OMIT_LOAD_EXTENSION)
31260#if SQLITE_OS_WINCE
31261  /* The GetProcAddressA() routine is only available on Windows CE. */
31262  { "GetProcAddressA",         (SYSCALL)GetProcAddressA,         0 },
31263#else
31264  /* All other Windows platforms expect GetProcAddress() to take
31265  ** an ANSI string regardless of the _UNICODE setting */
31266  { "GetProcAddressA",         (SYSCALL)GetProcAddress,          0 },
31267#endif
31268#else
31269  { "GetProcAddressA",         (SYSCALL)0,                       0 },
31270#endif
31271
31272#define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
31273        LPCSTR))aSyscall[27].pCurrent)
31274
31275#if !SQLITE_OS_WINRT
31276  { "GetSystemInfo",           (SYSCALL)GetSystemInfo,           0 },
31277#else
31278  { "GetSystemInfo",           (SYSCALL)0,                       0 },
31279#endif
31280
31281#define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
31282
31283  { "GetSystemTime",           (SYSCALL)GetSystemTime,           0 },
31284
31285#define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
31286
31287#if !SQLITE_OS_WINCE
31288  { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
31289#else
31290  { "GetSystemTimeAsFileTime", (SYSCALL)0,                       0 },
31291#endif
31292
31293#define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
31294        LPFILETIME))aSyscall[30].pCurrent)
31295
31296#if defined(SQLITE_WIN32_HAS_ANSI)
31297  { "GetTempPathA",            (SYSCALL)GetTempPathA,            0 },
31298#else
31299  { "GetTempPathA",            (SYSCALL)0,                       0 },
31300#endif
31301
31302#define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
31303
31304#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
31305  { "GetTempPathW",            (SYSCALL)GetTempPathW,            0 },
31306#else
31307  { "GetTempPathW",            (SYSCALL)0,                       0 },
31308#endif
31309
31310#define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
31311
31312#if !SQLITE_OS_WINRT
31313  { "GetTickCount",            (SYSCALL)GetTickCount,            0 },
31314#else
31315  { "GetTickCount",            (SYSCALL)0,                       0 },
31316#endif
31317
31318#define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
31319
31320#if defined(SQLITE_WIN32_HAS_ANSI)
31321  { "GetVersionExA",           (SYSCALL)GetVersionExA,           0 },
31322#else
31323  { "GetVersionExA",           (SYSCALL)0,                       0 },
31324#endif
31325
31326#define osGetVersionExA ((BOOL(WINAPI*)( \
31327        LPOSVERSIONINFOA))aSyscall[34].pCurrent)
31328
31329  { "HeapAlloc",               (SYSCALL)HeapAlloc,               0 },
31330
31331#define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
31332        SIZE_T))aSyscall[35].pCurrent)
31333
31334#if !SQLITE_OS_WINRT
31335  { "HeapCreate",              (SYSCALL)HeapCreate,              0 },
31336#else
31337  { "HeapCreate",              (SYSCALL)0,                       0 },
31338#endif
31339
31340#define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
31341        SIZE_T))aSyscall[36].pCurrent)
31342
31343#if !SQLITE_OS_WINRT
31344  { "HeapDestroy",             (SYSCALL)HeapDestroy,             0 },
31345#else
31346  { "HeapDestroy",             (SYSCALL)0,                       0 },
31347#endif
31348
31349#define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[37].pCurrent)
31350
31351  { "HeapFree",                (SYSCALL)HeapFree,                0 },
31352
31353#define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[38].pCurrent)
31354
31355  { "HeapReAlloc",             (SYSCALL)HeapReAlloc,             0 },
31356
31357#define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
31358        SIZE_T))aSyscall[39].pCurrent)
31359
31360  { "HeapSize",                (SYSCALL)HeapSize,                0 },
31361
31362#define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
31363        LPCVOID))aSyscall[40].pCurrent)
31364
31365#if !SQLITE_OS_WINRT
31366  { "HeapValidate",            (SYSCALL)HeapValidate,            0 },
31367#else
31368  { "HeapValidate",            (SYSCALL)0,                       0 },
31369#endif
31370
31371#define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
31372        LPCVOID))aSyscall[41].pCurrent)
31373
31374#if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
31375  { "LoadLibraryA",            (SYSCALL)LoadLibraryA,            0 },
31376#else
31377  { "LoadLibraryA",            (SYSCALL)0,                       0 },
31378#endif
31379
31380#define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[42].pCurrent)
31381
31382#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
31383        !defined(SQLITE_OMIT_LOAD_EXTENSION)
31384  { "LoadLibraryW",            (SYSCALL)LoadLibraryW,            0 },
31385#else
31386  { "LoadLibraryW",            (SYSCALL)0,                       0 },
31387#endif
31388
31389#define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[43].pCurrent)
31390
31391#if !SQLITE_OS_WINRT
31392  { "LocalFree",               (SYSCALL)LocalFree,               0 },
31393#else
31394  { "LocalFree",               (SYSCALL)0,                       0 },
31395#endif
31396
31397#define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[44].pCurrent)
31398
31399#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
31400  { "LockFile",                (SYSCALL)LockFile,                0 },
31401#else
31402  { "LockFile",                (SYSCALL)0,                       0 },
31403#endif
31404
31405#ifndef osLockFile
31406#define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
31407        DWORD))aSyscall[45].pCurrent)
31408#endif
31409
31410#if !SQLITE_OS_WINCE
31411  { "LockFileEx",              (SYSCALL)LockFileEx,              0 },
31412#else
31413  { "LockFileEx",              (SYSCALL)0,                       0 },
31414#endif
31415
31416#ifndef osLockFileEx
31417#define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
31418        LPOVERLAPPED))aSyscall[46].pCurrent)
31419#endif
31420
31421#if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL))
31422  { "MapViewOfFile",           (SYSCALL)MapViewOfFile,           0 },
31423#else
31424  { "MapViewOfFile",           (SYSCALL)0,                       0 },
31425#endif
31426
31427#define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
31428        SIZE_T))aSyscall[47].pCurrent)
31429
31430  { "MultiByteToWideChar",     (SYSCALL)MultiByteToWideChar,     0 },
31431
31432#define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
31433        int))aSyscall[48].pCurrent)
31434
31435  { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
31436
31437#define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
31438        LARGE_INTEGER*))aSyscall[49].pCurrent)
31439
31440  { "ReadFile",                (SYSCALL)ReadFile,                0 },
31441
31442#define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
31443        LPOVERLAPPED))aSyscall[50].pCurrent)
31444
31445  { "SetEndOfFile",            (SYSCALL)SetEndOfFile,            0 },
31446
31447#define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[51].pCurrent)
31448
31449#if !SQLITE_OS_WINRT
31450  { "SetFilePointer",          (SYSCALL)SetFilePointer,          0 },
31451#else
31452  { "SetFilePointer",          (SYSCALL)0,                       0 },
31453#endif
31454
31455#define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
31456        DWORD))aSyscall[52].pCurrent)
31457
31458#if !SQLITE_OS_WINRT
31459  { "Sleep",                   (SYSCALL)Sleep,                   0 },
31460#else
31461  { "Sleep",                   (SYSCALL)0,                       0 },
31462#endif
31463
31464#define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[53].pCurrent)
31465
31466  { "SystemTimeToFileTime",    (SYSCALL)SystemTimeToFileTime,    0 },
31467
31468#define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
31469        LPFILETIME))aSyscall[54].pCurrent)
31470
31471#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
31472  { "UnlockFile",              (SYSCALL)UnlockFile,              0 },
31473#else
31474  { "UnlockFile",              (SYSCALL)0,                       0 },
31475#endif
31476
31477#ifndef osUnlockFile
31478#define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
31479        DWORD))aSyscall[55].pCurrent)
31480#endif
31481
31482#if !SQLITE_OS_WINCE
31483  { "UnlockFileEx",            (SYSCALL)UnlockFileEx,            0 },
31484#else
31485  { "UnlockFileEx",            (SYSCALL)0,                       0 },
31486#endif
31487
31488#define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
31489        LPOVERLAPPED))aSyscall[56].pCurrent)
31490
31491#if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL)
31492  { "UnmapViewOfFile",         (SYSCALL)UnmapViewOfFile,         0 },
31493#else
31494  { "UnmapViewOfFile",         (SYSCALL)0,                       0 },
31495#endif
31496
31497#define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[57].pCurrent)
31498
31499  { "WideCharToMultiByte",     (SYSCALL)WideCharToMultiByte,     0 },
31500
31501#define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
31502        LPCSTR,LPBOOL))aSyscall[58].pCurrent)
31503
31504  { "WriteFile",               (SYSCALL)WriteFile,               0 },
31505
31506#define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
31507        LPOVERLAPPED))aSyscall[59].pCurrent)
31508
31509#if SQLITE_OS_WINRT
31510  { "CreateEventExW",          (SYSCALL)CreateEventExW,          0 },
31511#else
31512  { "CreateEventExW",          (SYSCALL)0,                       0 },
31513#endif
31514
31515#define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
31516        DWORD,DWORD))aSyscall[60].pCurrent)
31517
31518#if !SQLITE_OS_WINRT
31519  { "WaitForSingleObject",     (SYSCALL)WaitForSingleObject,     0 },
31520#else
31521  { "WaitForSingleObject",     (SYSCALL)0,                       0 },
31522#endif
31523
31524#define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
31525        DWORD))aSyscall[61].pCurrent)
31526
31527#if SQLITE_OS_WINRT
31528  { "WaitForSingleObjectEx",   (SYSCALL)WaitForSingleObjectEx,   0 },
31529#else
31530  { "WaitForSingleObjectEx",   (SYSCALL)0,                       0 },
31531#endif
31532
31533#define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
31534        BOOL))aSyscall[62].pCurrent)
31535
31536#if SQLITE_OS_WINRT
31537  { "SetFilePointerEx",        (SYSCALL)SetFilePointerEx,        0 },
31538#else
31539  { "SetFilePointerEx",        (SYSCALL)0,                       0 },
31540#endif
31541
31542#define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
31543        PLARGE_INTEGER,DWORD))aSyscall[63].pCurrent)
31544
31545#if SQLITE_OS_WINRT
31546  { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
31547#else
31548  { "GetFileInformationByHandleEx", (SYSCALL)0,                  0 },
31549#endif
31550
31551#define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
31552        FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[64].pCurrent)
31553
31554#if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)
31555  { "MapViewOfFileFromApp",    (SYSCALL)MapViewOfFileFromApp,    0 },
31556#else
31557  { "MapViewOfFileFromApp",    (SYSCALL)0,                       0 },
31558#endif
31559
31560#define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
31561        SIZE_T))aSyscall[65].pCurrent)
31562
31563#if SQLITE_OS_WINRT
31564  { "CreateFile2",             (SYSCALL)CreateFile2,             0 },
31565#else
31566  { "CreateFile2",             (SYSCALL)0,                       0 },
31567#endif
31568
31569#define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
31570        LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[66].pCurrent)
31571
31572#if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
31573  { "LoadPackagedLibrary",     (SYSCALL)LoadPackagedLibrary,     0 },
31574#else
31575  { "LoadPackagedLibrary",     (SYSCALL)0,                       0 },
31576#endif
31577
31578#define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
31579        DWORD))aSyscall[67].pCurrent)
31580
31581#if SQLITE_OS_WINRT
31582  { "GetTickCount64",          (SYSCALL)GetTickCount64,          0 },
31583#else
31584  { "GetTickCount64",          (SYSCALL)0,                       0 },
31585#endif
31586
31587#define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[68].pCurrent)
31588
31589#if SQLITE_OS_WINRT
31590  { "GetNativeSystemInfo",     (SYSCALL)GetNativeSystemInfo,     0 },
31591#else
31592  { "GetNativeSystemInfo",     (SYSCALL)0,                       0 },
31593#endif
31594
31595#define osGetNativeSystemInfo ((VOID(WINAPI*)( \
31596        LPSYSTEM_INFO))aSyscall[69].pCurrent)
31597
31598#if defined(SQLITE_WIN32_HAS_ANSI)
31599  { "OutputDebugStringA",      (SYSCALL)OutputDebugStringA,      0 },
31600#else
31601  { "OutputDebugStringA",      (SYSCALL)0,                       0 },
31602#endif
31603
31604#define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[70].pCurrent)
31605
31606#if defined(SQLITE_WIN32_HAS_WIDE)
31607  { "OutputDebugStringW",      (SYSCALL)OutputDebugStringW,      0 },
31608#else
31609  { "OutputDebugStringW",      (SYSCALL)0,                       0 },
31610#endif
31611
31612#define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[71].pCurrent)
31613
31614  { "GetProcessHeap",          (SYSCALL)GetProcessHeap,          0 },
31615
31616#define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[72].pCurrent)
31617
31618#if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)
31619  { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
31620#else
31621  { "CreateFileMappingFromApp", (SYSCALL)0,                      0 },
31622#endif
31623
31624#define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
31625        LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[73].pCurrent)
31626
31627}; /* End of the overrideable system calls */
31628
31629/*
31630** This is the xSetSystemCall() method of sqlite3_vfs for all of the
31631** "win32" VFSes.  Return SQLITE_OK opon successfully updating the
31632** system call pointer, or SQLITE_NOTFOUND if there is no configurable
31633** system call named zName.
31634*/
31635static int winSetSystemCall(
31636  sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
31637  const char *zName,            /* Name of system call to override */
31638  sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
31639){
31640  unsigned int i;
31641  int rc = SQLITE_NOTFOUND;
31642
31643  UNUSED_PARAMETER(pNotUsed);
31644  if( zName==0 ){
31645    /* If no zName is given, restore all system calls to their default
31646    ** settings and return NULL
31647    */
31648    rc = SQLITE_OK;
31649    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
31650      if( aSyscall[i].pDefault ){
31651        aSyscall[i].pCurrent = aSyscall[i].pDefault;
31652      }
31653    }
31654  }else{
31655    /* If zName is specified, operate on only the one system call
31656    ** specified.
31657    */
31658    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
31659      if( strcmp(zName, aSyscall[i].zName)==0 ){
31660        if( aSyscall[i].pDefault==0 ){
31661          aSyscall[i].pDefault = aSyscall[i].pCurrent;
31662        }
31663        rc = SQLITE_OK;
31664        if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
31665        aSyscall[i].pCurrent = pNewFunc;
31666        break;
31667      }
31668    }
31669  }
31670  return rc;
31671}
31672
31673/*
31674** Return the value of a system call.  Return NULL if zName is not a
31675** recognized system call name.  NULL is also returned if the system call
31676** is currently undefined.
31677*/
31678static sqlite3_syscall_ptr winGetSystemCall(
31679  sqlite3_vfs *pNotUsed,
31680  const char *zName
31681){
31682  unsigned int i;
31683
31684  UNUSED_PARAMETER(pNotUsed);
31685  for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
31686    if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
31687  }
31688  return 0;
31689}
31690
31691/*
31692** Return the name of the first system call after zName.  If zName==NULL
31693** then return the name of the first system call.  Return NULL if zName
31694** is the last system call or if zName is not the name of a valid
31695** system call.
31696*/
31697static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
31698  int i = -1;
31699
31700  UNUSED_PARAMETER(p);
31701  if( zName ){
31702    for(i=0; i<ArraySize(aSyscall)-1; i++){
31703      if( strcmp(zName, aSyscall[i].zName)==0 ) break;
31704    }
31705  }
31706  for(i++; i<ArraySize(aSyscall); i++){
31707    if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
31708  }
31709  return 0;
31710}
31711
31712/*
31713** This function outputs the specified (ANSI) string to the Win32 debugger
31714** (if available).
31715*/
31716
31717SQLITE_API void sqlite3_win32_write_debug(const char *zBuf, int nBuf){
31718  char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
31719  int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
31720  if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
31721  assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
31722#if defined(SQLITE_WIN32_HAS_ANSI)
31723  if( nMin>0 ){
31724    memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
31725    memcpy(zDbgBuf, zBuf, nMin);
31726    osOutputDebugStringA(zDbgBuf);
31727  }else{
31728    osOutputDebugStringA(zBuf);
31729  }
31730#elif defined(SQLITE_WIN32_HAS_WIDE)
31731  memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
31732  if ( osMultiByteToWideChar(
31733          osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
31734          nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
31735    return;
31736  }
31737  osOutputDebugStringW((LPCWSTR)zDbgBuf);
31738#else
31739  if( nMin>0 ){
31740    memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
31741    memcpy(zDbgBuf, zBuf, nMin);
31742    fprintf(stderr, "%s", zDbgBuf);
31743  }else{
31744    fprintf(stderr, "%s", zBuf);
31745  }
31746#endif
31747}
31748
31749/*
31750** The following routine suspends the current thread for at least ms
31751** milliseconds.  This is equivalent to the Win32 Sleep() interface.
31752*/
31753#if SQLITE_OS_WINRT
31754static HANDLE sleepObj = NULL;
31755#endif
31756
31757SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds){
31758#if SQLITE_OS_WINRT
31759  if ( sleepObj==NULL ){
31760    sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
31761                                SYNCHRONIZE);
31762  }
31763  assert( sleepObj!=NULL );
31764  osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
31765#else
31766  osSleep(milliseconds);
31767#endif
31768}
31769
31770/*
31771** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
31772** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
31773**
31774** Here is an interesting observation:  Win95, Win98, and WinME lack
31775** the LockFileEx() API.  But we can still statically link against that
31776** API as long as we don't call it when running Win95/98/ME.  A call to
31777** this routine is used to determine if the host is Win95/98/ME or
31778** WinNT/2K/XP so that we will know whether or not we can safely call
31779** the LockFileEx() API.
31780*/
31781#if SQLITE_OS_WINCE || SQLITE_OS_WINRT
31782# define isNT()  (1)
31783#elif !defined(SQLITE_WIN32_HAS_WIDE)
31784# define isNT()  (0)
31785#else
31786  static int isNT(void){
31787    if( sqlite3_os_type==0 ){
31788      OSVERSIONINFOA sInfo;
31789      sInfo.dwOSVersionInfoSize = sizeof(sInfo);
31790      osGetVersionExA(&sInfo);
31791      sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
31792    }
31793    return sqlite3_os_type==2;
31794  }
31795#endif
31796
31797#ifdef SQLITE_WIN32_MALLOC
31798/*
31799** Allocate nBytes of memory.
31800*/
31801static void *winMemMalloc(int nBytes){
31802  HANDLE hHeap;
31803  void *p;
31804
31805  winMemAssertMagic();
31806  hHeap = winMemGetHeap();
31807  assert( hHeap!=0 );
31808  assert( hHeap!=INVALID_HANDLE_VALUE );
31809#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
31810  assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
31811#endif
31812  assert( nBytes>=0 );
31813  p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
31814  if( !p ){
31815    sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%d), heap=%p",
31816                nBytes, osGetLastError(), (void*)hHeap);
31817  }
31818  return p;
31819}
31820
31821/*
31822** Free memory.
31823*/
31824static void winMemFree(void *pPrior){
31825  HANDLE hHeap;
31826
31827  winMemAssertMagic();
31828  hHeap = winMemGetHeap();
31829  assert( hHeap!=0 );
31830  assert( hHeap!=INVALID_HANDLE_VALUE );
31831#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
31832  assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
31833#endif
31834  if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
31835  if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
31836    sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%d), heap=%p",
31837                pPrior, osGetLastError(), (void*)hHeap);
31838  }
31839}
31840
31841/*
31842** Change the size of an existing memory allocation
31843*/
31844static void *winMemRealloc(void *pPrior, int nBytes){
31845  HANDLE hHeap;
31846  void *p;
31847
31848  winMemAssertMagic();
31849  hHeap = winMemGetHeap();
31850  assert( hHeap!=0 );
31851  assert( hHeap!=INVALID_HANDLE_VALUE );
31852#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
31853  assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
31854#endif
31855  assert( nBytes>=0 );
31856  if( !pPrior ){
31857    p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
31858  }else{
31859    p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
31860  }
31861  if( !p ){
31862    sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%d), heap=%p",
31863                pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
31864                (void*)hHeap);
31865  }
31866  return p;
31867}
31868
31869/*
31870** Return the size of an outstanding allocation, in bytes.
31871*/
31872static int winMemSize(void *p){
31873  HANDLE hHeap;
31874  SIZE_T n;
31875
31876  winMemAssertMagic();
31877  hHeap = winMemGetHeap();
31878  assert( hHeap!=0 );
31879  assert( hHeap!=INVALID_HANDLE_VALUE );
31880#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
31881  assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
31882#endif
31883  if( !p ) return 0;
31884  n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
31885  if( n==(SIZE_T)-1 ){
31886    sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%d), heap=%p",
31887                p, osGetLastError(), (void*)hHeap);
31888    return 0;
31889  }
31890  return (int)n;
31891}
31892
31893/*
31894** Round up a request size to the next valid allocation size.
31895*/
31896static int winMemRoundup(int n){
31897  return n;
31898}
31899
31900/*
31901** Initialize this module.
31902*/
31903static int winMemInit(void *pAppData){
31904  winMemData *pWinMemData = (winMemData *)pAppData;
31905
31906  if( !pWinMemData ) return SQLITE_ERROR;
31907  assert( pWinMemData->magic==WINMEM_MAGIC );
31908
31909#if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
31910  if( !pWinMemData->hHeap ){
31911    pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
31912                                      SQLITE_WIN32_HEAP_INIT_SIZE,
31913                                      SQLITE_WIN32_HEAP_MAX_SIZE);
31914    if( !pWinMemData->hHeap ){
31915      sqlite3_log(SQLITE_NOMEM,
31916          "failed to HeapCreate (%d), flags=%u, initSize=%u, maxSize=%u",
31917          osGetLastError(), SQLITE_WIN32_HEAP_FLAGS,
31918          SQLITE_WIN32_HEAP_INIT_SIZE, SQLITE_WIN32_HEAP_MAX_SIZE);
31919      return SQLITE_NOMEM;
31920    }
31921    pWinMemData->bOwned = TRUE;
31922    assert( pWinMemData->bOwned );
31923  }
31924#else
31925  pWinMemData->hHeap = osGetProcessHeap();
31926  if( !pWinMemData->hHeap ){
31927    sqlite3_log(SQLITE_NOMEM,
31928        "failed to GetProcessHeap (%d)", osGetLastError());
31929    return SQLITE_NOMEM;
31930  }
31931  pWinMemData->bOwned = FALSE;
31932  assert( !pWinMemData->bOwned );
31933#endif
31934  assert( pWinMemData->hHeap!=0 );
31935  assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
31936#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
31937  assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
31938#endif
31939  return SQLITE_OK;
31940}
31941
31942/*
31943** Deinitialize this module.
31944*/
31945static void winMemShutdown(void *pAppData){
31946  winMemData *pWinMemData = (winMemData *)pAppData;
31947
31948  if( !pWinMemData ) return;
31949  if( pWinMemData->hHeap ){
31950    assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
31951#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
31952    assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
31953#endif
31954    if( pWinMemData->bOwned ){
31955      if( !osHeapDestroy(pWinMemData->hHeap) ){
31956        sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%d), heap=%p",
31957                    osGetLastError(), (void*)pWinMemData->hHeap);
31958      }
31959      pWinMemData->bOwned = FALSE;
31960    }
31961    pWinMemData->hHeap = NULL;
31962  }
31963}
31964
31965/*
31966** Populate the low-level memory allocation function pointers in
31967** sqlite3GlobalConfig.m with pointers to the routines in this file. The
31968** arguments specify the block of memory to manage.
31969**
31970** This routine is only called by sqlite3_config(), and therefore
31971** is not required to be threadsafe (it is not).
31972*/
31973SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
31974  static const sqlite3_mem_methods winMemMethods = {
31975    winMemMalloc,
31976    winMemFree,
31977    winMemRealloc,
31978    winMemSize,
31979    winMemRoundup,
31980    winMemInit,
31981    winMemShutdown,
31982    &win_mem_data
31983  };
31984  return &winMemMethods;
31985}
31986
31987SQLITE_PRIVATE void sqlite3MemSetDefault(void){
31988  sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
31989}
31990#endif /* SQLITE_WIN32_MALLOC */
31991
31992/*
31993** Convert a UTF-8 string to Microsoft Unicode (UTF-16?).
31994**
31995** Space to hold the returned string is obtained from malloc.
31996*/
31997static LPWSTR utf8ToUnicode(const char *zFilename){
31998  int nChar;
31999  LPWSTR zWideFilename;
32000
32001  nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
32002  if( nChar==0 ){
32003    return 0;
32004  }
32005  zWideFilename = sqlite3MallocZero( nChar*sizeof(zWideFilename[0]) );
32006  if( zWideFilename==0 ){
32007    return 0;
32008  }
32009  nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
32010                                nChar);
32011  if( nChar==0 ){
32012    sqlite3_free(zWideFilename);
32013    zWideFilename = 0;
32014  }
32015  return zWideFilename;
32016}
32017
32018/*
32019** Convert Microsoft Unicode to UTF-8.  Space to hold the returned string is
32020** obtained from sqlite3_malloc().
32021*/
32022static char *unicodeToUtf8(LPCWSTR zWideFilename){
32023  int nByte;
32024  char *zFilename;
32025
32026  nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
32027  if( nByte == 0 ){
32028    return 0;
32029  }
32030  zFilename = sqlite3MallocZero( nByte );
32031  if( zFilename==0 ){
32032    return 0;
32033  }
32034  nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
32035                                0, 0);
32036  if( nByte == 0 ){
32037    sqlite3_free(zFilename);
32038    zFilename = 0;
32039  }
32040  return zFilename;
32041}
32042
32043/*
32044** Convert an ANSI string to Microsoft Unicode, based on the
32045** current codepage settings for file apis.
32046**
32047** Space to hold the returned string is obtained
32048** from sqlite3_malloc.
32049*/
32050static LPWSTR mbcsToUnicode(const char *zFilename){
32051  int nByte;
32052  LPWSTR zMbcsFilename;
32053  int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
32054
32055  nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, NULL,
32056                                0)*sizeof(WCHAR);
32057  if( nByte==0 ){
32058    return 0;
32059  }
32060  zMbcsFilename = sqlite3MallocZero( nByte*sizeof(zMbcsFilename[0]) );
32061  if( zMbcsFilename==0 ){
32062    return 0;
32063  }
32064  nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename,
32065                                nByte);
32066  if( nByte==0 ){
32067    sqlite3_free(zMbcsFilename);
32068    zMbcsFilename = 0;
32069  }
32070  return zMbcsFilename;
32071}
32072
32073/*
32074** Convert Microsoft Unicode to multi-byte character string, based on the
32075** user's ANSI codepage.
32076**
32077** Space to hold the returned string is obtained from
32078** sqlite3_malloc().
32079*/
32080static char *unicodeToMbcs(LPCWSTR zWideFilename){
32081  int nByte;
32082  char *zFilename;
32083  int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
32084
32085  nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
32086  if( nByte == 0 ){
32087    return 0;
32088  }
32089  zFilename = sqlite3MallocZero( nByte );
32090  if( zFilename==0 ){
32091    return 0;
32092  }
32093  nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename,
32094                                nByte, 0, 0);
32095  if( nByte == 0 ){
32096    sqlite3_free(zFilename);
32097    zFilename = 0;
32098  }
32099  return zFilename;
32100}
32101
32102/*
32103** Convert multibyte character string to UTF-8.  Space to hold the
32104** returned string is obtained from sqlite3_malloc().
32105*/
32106SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
32107  char *zFilenameUtf8;
32108  LPWSTR zTmpWide;
32109
32110  zTmpWide = mbcsToUnicode(zFilename);
32111  if( zTmpWide==0 ){
32112    return 0;
32113  }
32114  zFilenameUtf8 = unicodeToUtf8(zTmpWide);
32115  sqlite3_free(zTmpWide);
32116  return zFilenameUtf8;
32117}
32118
32119/*
32120** Convert UTF-8 to multibyte character string.  Space to hold the
32121** returned string is obtained from sqlite3_malloc().
32122*/
32123SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zFilename){
32124  char *zFilenameMbcs;
32125  LPWSTR zTmpWide;
32126
32127  zTmpWide = utf8ToUnicode(zFilename);
32128  if( zTmpWide==0 ){
32129    return 0;
32130  }
32131  zFilenameMbcs = unicodeToMbcs(zTmpWide);
32132  sqlite3_free(zTmpWide);
32133  return zFilenameMbcs;
32134}
32135
32136/*
32137** This function sets the data directory or the temporary directory based on
32138** the provided arguments.  The type argument must be 1 in order to set the
32139** data directory or 2 in order to set the temporary directory.  The zValue
32140** argument is the name of the directory to use.  The return value will be
32141** SQLITE_OK if successful.
32142*/
32143SQLITE_API int sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){
32144  char **ppDirectory = 0;
32145#ifndef SQLITE_OMIT_AUTOINIT
32146  int rc = sqlite3_initialize();
32147  if( rc ) return rc;
32148#endif
32149  if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
32150    ppDirectory = &sqlite3_data_directory;
32151  }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
32152    ppDirectory = &sqlite3_temp_directory;
32153  }
32154  assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
32155          || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
32156  );
32157  assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
32158  if( ppDirectory ){
32159    char *zValueUtf8 = 0;
32160    if( zValue && zValue[0] ){
32161      zValueUtf8 = unicodeToUtf8(zValue);
32162      if ( zValueUtf8==0 ){
32163        return SQLITE_NOMEM;
32164      }
32165    }
32166    sqlite3_free(*ppDirectory);
32167    *ppDirectory = zValueUtf8;
32168    return SQLITE_OK;
32169  }
32170  return SQLITE_ERROR;
32171}
32172
32173/*
32174** The return value of getLastErrorMsg
32175** is zero if the error message fits in the buffer, or non-zero
32176** otherwise (if the message was truncated).
32177*/
32178static int getLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
32179  /* FormatMessage returns 0 on failure.  Otherwise it
32180  ** returns the number of TCHARs written to the output
32181  ** buffer, excluding the terminating null char.
32182  */
32183  DWORD dwLen = 0;
32184  char *zOut = 0;
32185
32186  if( isNT() ){
32187#if SQLITE_OS_WINRT
32188    WCHAR zTempWide[MAX_PATH+1]; /* NOTE: Somewhat arbitrary. */
32189    dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
32190                             FORMAT_MESSAGE_IGNORE_INSERTS,
32191                             NULL,
32192                             lastErrno,
32193                             0,
32194                             zTempWide,
32195                             MAX_PATH,
32196                             0);
32197#else
32198    LPWSTR zTempWide = NULL;
32199    dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
32200                             FORMAT_MESSAGE_FROM_SYSTEM |
32201                             FORMAT_MESSAGE_IGNORE_INSERTS,
32202                             NULL,
32203                             lastErrno,
32204                             0,
32205                             (LPWSTR) &zTempWide,
32206                             0,
32207                             0);
32208#endif
32209    if( dwLen > 0 ){
32210      /* allocate a buffer and convert to UTF8 */
32211      sqlite3BeginBenignMalloc();
32212      zOut = unicodeToUtf8(zTempWide);
32213      sqlite3EndBenignMalloc();
32214#if !SQLITE_OS_WINRT
32215      /* free the system buffer allocated by FormatMessage */
32216      osLocalFree(zTempWide);
32217#endif
32218    }
32219  }
32220#ifdef SQLITE_WIN32_HAS_ANSI
32221  else{
32222    char *zTemp = NULL;
32223    dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
32224                             FORMAT_MESSAGE_FROM_SYSTEM |
32225                             FORMAT_MESSAGE_IGNORE_INSERTS,
32226                             NULL,
32227                             lastErrno,
32228                             0,
32229                             (LPSTR) &zTemp,
32230                             0,
32231                             0);
32232    if( dwLen > 0 ){
32233      /* allocate a buffer and convert to UTF8 */
32234      sqlite3BeginBenignMalloc();
32235      zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
32236      sqlite3EndBenignMalloc();
32237      /* free the system buffer allocated by FormatMessage */
32238      osLocalFree(zTemp);
32239    }
32240  }
32241#endif
32242  if( 0 == dwLen ){
32243    sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno);
32244  }else{
32245    /* copy a maximum of nBuf chars to output buffer */
32246    sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
32247    /* free the UTF8 buffer */
32248    sqlite3_free(zOut);
32249  }
32250  return 0;
32251}
32252
32253/*
32254**
32255** This function - winLogErrorAtLine() - is only ever called via the macro
32256** winLogError().
32257**
32258** This routine is invoked after an error occurs in an OS function.
32259** It logs a message using sqlite3_log() containing the current value of
32260** error code and, if possible, the human-readable equivalent from
32261** FormatMessage.
32262**
32263** The first argument passed to the macro should be the error code that
32264** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
32265** The two subsequent arguments should be the name of the OS function that
32266** failed and the associated file-system path, if any.
32267*/
32268#define winLogError(a,b,c,d)   winLogErrorAtLine(a,b,c,d,__LINE__)
32269static int winLogErrorAtLine(
32270  int errcode,                    /* SQLite error code */
32271  DWORD lastErrno,                /* Win32 last error */
32272  const char *zFunc,              /* Name of OS function that failed */
32273  const char *zPath,              /* File path associated with error */
32274  int iLine                       /* Source line number where error occurred */
32275){
32276  char zMsg[500];                 /* Human readable error text */
32277  int i;                          /* Loop counter */
32278
32279  zMsg[0] = 0;
32280  getLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
32281  assert( errcode!=SQLITE_OK );
32282  if( zPath==0 ) zPath = "";
32283  for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
32284  zMsg[i] = 0;
32285  sqlite3_log(errcode,
32286      "os_win.c:%d: (%lu) %s(%s) - %s",
32287      iLine, lastErrno, zFunc, zPath, zMsg
32288  );
32289
32290  return errcode;
32291}
32292
32293/*
32294** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
32295** will be retried following a locking error - probably caused by
32296** antivirus software.  Also the initial delay before the first retry.
32297** The delay increases linearly with each retry.
32298*/
32299#ifndef SQLITE_WIN32_IOERR_RETRY
32300# define SQLITE_WIN32_IOERR_RETRY 10
32301#endif
32302#ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
32303# define SQLITE_WIN32_IOERR_RETRY_DELAY 25
32304#endif
32305static int win32IoerrRetry = SQLITE_WIN32_IOERR_RETRY;
32306static int win32IoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
32307
32308/*
32309** If a ReadFile() or WriteFile() error occurs, invoke this routine
32310** to see if it should be retried.  Return TRUE to retry.  Return FALSE
32311** to give up with an error.
32312*/
32313static int retryIoerr(int *pnRetry, DWORD *pError){
32314  DWORD e = osGetLastError();
32315  if( *pnRetry>=win32IoerrRetry ){
32316    if( pError ){
32317      *pError = e;
32318    }
32319    return 0;
32320  }
32321  if( e==ERROR_ACCESS_DENIED ||
32322      e==ERROR_LOCK_VIOLATION ||
32323      e==ERROR_SHARING_VIOLATION ){
32324    sqlite3_win32_sleep(win32IoerrRetryDelay*(1+*pnRetry));
32325    ++*pnRetry;
32326    return 1;
32327  }
32328  if( pError ){
32329    *pError = e;
32330  }
32331  return 0;
32332}
32333
32334/*
32335** Log a I/O error retry episode.
32336*/
32337static void logIoerr(int nRetry){
32338  if( nRetry ){
32339    sqlite3_log(SQLITE_IOERR,
32340      "delayed %dms for lock/sharing conflict",
32341      win32IoerrRetryDelay*nRetry*(nRetry+1)/2
32342    );
32343  }
32344}
32345
32346#if SQLITE_OS_WINCE
32347/*************************************************************************
32348** This section contains code for WinCE only.
32349*/
32350#if !defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API
32351/*
32352** The MSVC CRT on Windows CE may not have a localtime() function.  So
32353** create a substitute.
32354*/
32355/* #include <time.h> */
32356struct tm *__cdecl localtime(const time_t *t)
32357{
32358  static struct tm y;
32359  FILETIME uTm, lTm;
32360  SYSTEMTIME pTm;
32361  sqlite3_int64 t64;
32362  t64 = *t;
32363  t64 = (t64 + 11644473600)*10000000;
32364  uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
32365  uTm.dwHighDateTime= (DWORD)(t64 >> 32);
32366  osFileTimeToLocalFileTime(&uTm,&lTm);
32367  osFileTimeToSystemTime(&lTm,&pTm);
32368  y.tm_year = pTm.wYear - 1900;
32369  y.tm_mon = pTm.wMonth - 1;
32370  y.tm_wday = pTm.wDayOfWeek;
32371  y.tm_mday = pTm.wDay;
32372  y.tm_hour = pTm.wHour;
32373  y.tm_min = pTm.wMinute;
32374  y.tm_sec = pTm.wSecond;
32375  return &y;
32376}
32377#endif
32378
32379#define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
32380
32381/*
32382** Acquire a lock on the handle h
32383*/
32384static void winceMutexAcquire(HANDLE h){
32385   DWORD dwErr;
32386   do {
32387     dwErr = osWaitForSingleObject(h, INFINITE);
32388   } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
32389}
32390/*
32391** Release a lock acquired by winceMutexAcquire()
32392*/
32393#define winceMutexRelease(h) ReleaseMutex(h)
32394
32395/*
32396** Create the mutex and shared memory used for locking in the file
32397** descriptor pFile
32398*/
32399static int winceCreateLock(const char *zFilename, winFile *pFile){
32400  LPWSTR zTok;
32401  LPWSTR zName;
32402  DWORD lastErrno;
32403  BOOL bLogged = FALSE;
32404  BOOL bInit = TRUE;
32405
32406  zName = utf8ToUnicode(zFilename);
32407  if( zName==0 ){
32408    /* out of memory */
32409    return SQLITE_IOERR_NOMEM;
32410  }
32411
32412  /* Initialize the local lockdata */
32413  memset(&pFile->local, 0, sizeof(pFile->local));
32414
32415  /* Replace the backslashes from the filename and lowercase it
32416  ** to derive a mutex name. */
32417  zTok = osCharLowerW(zName);
32418  for (;*zTok;zTok++){
32419    if (*zTok == '\\') *zTok = '_';
32420  }
32421
32422  /* Create/open the named mutex */
32423  pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
32424  if (!pFile->hMutex){
32425    pFile->lastErrno = osGetLastError();
32426    winLogError(SQLITE_IOERR, pFile->lastErrno,
32427                "winceCreateLock1", zFilename);
32428    sqlite3_free(zName);
32429    return SQLITE_IOERR;
32430  }
32431
32432  /* Acquire the mutex before continuing */
32433  winceMutexAcquire(pFile->hMutex);
32434
32435  /* Since the names of named mutexes, semaphores, file mappings etc are
32436  ** case-sensitive, take advantage of that by uppercasing the mutex name
32437  ** and using that as the shared filemapping name.
32438  */
32439  osCharUpperW(zName);
32440  pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
32441                                        PAGE_READWRITE, 0, sizeof(winceLock),
32442                                        zName);
32443
32444  /* Set a flag that indicates we're the first to create the memory so it
32445  ** must be zero-initialized */
32446  lastErrno = osGetLastError();
32447  if (lastErrno == ERROR_ALREADY_EXISTS){
32448    bInit = FALSE;
32449  }
32450
32451  sqlite3_free(zName);
32452
32453  /* If we succeeded in making the shared memory handle, map it. */
32454  if( pFile->hShared ){
32455    pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
32456             FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
32457    /* If mapping failed, close the shared memory handle and erase it */
32458    if( !pFile->shared ){
32459      pFile->lastErrno = osGetLastError();
32460      winLogError(SQLITE_IOERR, pFile->lastErrno,
32461                  "winceCreateLock2", zFilename);
32462      bLogged = TRUE;
32463      osCloseHandle(pFile->hShared);
32464      pFile->hShared = NULL;
32465    }
32466  }
32467
32468  /* If shared memory could not be created, then close the mutex and fail */
32469  if( pFile->hShared==NULL ){
32470    if( !bLogged ){
32471      pFile->lastErrno = lastErrno;
32472      winLogError(SQLITE_IOERR, pFile->lastErrno,
32473                  "winceCreateLock3", zFilename);
32474      bLogged = TRUE;
32475    }
32476    winceMutexRelease(pFile->hMutex);
32477    osCloseHandle(pFile->hMutex);
32478    pFile->hMutex = NULL;
32479    return SQLITE_IOERR;
32480  }
32481
32482  /* Initialize the shared memory if we're supposed to */
32483  if( bInit ){
32484    memset(pFile->shared, 0, sizeof(winceLock));
32485  }
32486
32487  winceMutexRelease(pFile->hMutex);
32488  return SQLITE_OK;
32489}
32490
32491/*
32492** Destroy the part of winFile that deals with wince locks
32493*/
32494static void winceDestroyLock(winFile *pFile){
32495  if (pFile->hMutex){
32496    /* Acquire the mutex */
32497    winceMutexAcquire(pFile->hMutex);
32498
32499    /* The following blocks should probably assert in debug mode, but they
32500       are to cleanup in case any locks remained open */
32501    if (pFile->local.nReaders){
32502      pFile->shared->nReaders --;
32503    }
32504    if (pFile->local.bReserved){
32505      pFile->shared->bReserved = FALSE;
32506    }
32507    if (pFile->local.bPending){
32508      pFile->shared->bPending = FALSE;
32509    }
32510    if (pFile->local.bExclusive){
32511      pFile->shared->bExclusive = FALSE;
32512    }
32513
32514    /* De-reference and close our copy of the shared memory handle */
32515    osUnmapViewOfFile(pFile->shared);
32516    osCloseHandle(pFile->hShared);
32517
32518    /* Done with the mutex */
32519    winceMutexRelease(pFile->hMutex);
32520    osCloseHandle(pFile->hMutex);
32521    pFile->hMutex = NULL;
32522  }
32523}
32524
32525/*
32526** An implementation of the LockFile() API of Windows for CE
32527*/
32528static BOOL winceLockFile(
32529  LPHANDLE phFile,
32530  DWORD dwFileOffsetLow,
32531  DWORD dwFileOffsetHigh,
32532  DWORD nNumberOfBytesToLockLow,
32533  DWORD nNumberOfBytesToLockHigh
32534){
32535  winFile *pFile = HANDLE_TO_WINFILE(phFile);
32536  BOOL bReturn = FALSE;
32537
32538  UNUSED_PARAMETER(dwFileOffsetHigh);
32539  UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
32540
32541  if (!pFile->hMutex) return TRUE;
32542  winceMutexAcquire(pFile->hMutex);
32543
32544  /* Wanting an exclusive lock? */
32545  if (dwFileOffsetLow == (DWORD)SHARED_FIRST
32546       && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
32547    if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
32548       pFile->shared->bExclusive = TRUE;
32549       pFile->local.bExclusive = TRUE;
32550       bReturn = TRUE;
32551    }
32552  }
32553
32554  /* Want a read-only lock? */
32555  else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
32556           nNumberOfBytesToLockLow == 1){
32557    if (pFile->shared->bExclusive == 0){
32558      pFile->local.nReaders ++;
32559      if (pFile->local.nReaders == 1){
32560        pFile->shared->nReaders ++;
32561      }
32562      bReturn = TRUE;
32563    }
32564  }
32565
32566  /* Want a pending lock? */
32567  else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
32568           && nNumberOfBytesToLockLow == 1){
32569    /* If no pending lock has been acquired, then acquire it */
32570    if (pFile->shared->bPending == 0) {
32571      pFile->shared->bPending = TRUE;
32572      pFile->local.bPending = TRUE;
32573      bReturn = TRUE;
32574    }
32575  }
32576
32577  /* Want a reserved lock? */
32578  else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
32579           && nNumberOfBytesToLockLow == 1){
32580    if (pFile->shared->bReserved == 0) {
32581      pFile->shared->bReserved = TRUE;
32582      pFile->local.bReserved = TRUE;
32583      bReturn = TRUE;
32584    }
32585  }
32586
32587  winceMutexRelease(pFile->hMutex);
32588  return bReturn;
32589}
32590
32591/*
32592** An implementation of the UnlockFile API of Windows for CE
32593*/
32594static BOOL winceUnlockFile(
32595  LPHANDLE phFile,
32596  DWORD dwFileOffsetLow,
32597  DWORD dwFileOffsetHigh,
32598  DWORD nNumberOfBytesToUnlockLow,
32599  DWORD nNumberOfBytesToUnlockHigh
32600){
32601  winFile *pFile = HANDLE_TO_WINFILE(phFile);
32602  BOOL bReturn = FALSE;
32603
32604  UNUSED_PARAMETER(dwFileOffsetHigh);
32605  UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
32606
32607  if (!pFile->hMutex) return TRUE;
32608  winceMutexAcquire(pFile->hMutex);
32609
32610  /* Releasing a reader lock or an exclusive lock */
32611  if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
32612    /* Did we have an exclusive lock? */
32613    if (pFile->local.bExclusive){
32614      assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
32615      pFile->local.bExclusive = FALSE;
32616      pFile->shared->bExclusive = FALSE;
32617      bReturn = TRUE;
32618    }
32619
32620    /* Did we just have a reader lock? */
32621    else if (pFile->local.nReaders){
32622      assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
32623             || nNumberOfBytesToUnlockLow == 1);
32624      pFile->local.nReaders --;
32625      if (pFile->local.nReaders == 0)
32626      {
32627        pFile->shared->nReaders --;
32628      }
32629      bReturn = TRUE;
32630    }
32631  }
32632
32633  /* Releasing a pending lock */
32634  else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
32635           && nNumberOfBytesToUnlockLow == 1){
32636    if (pFile->local.bPending){
32637      pFile->local.bPending = FALSE;
32638      pFile->shared->bPending = FALSE;
32639      bReturn = TRUE;
32640    }
32641  }
32642  /* Releasing a reserved lock */
32643  else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
32644           && nNumberOfBytesToUnlockLow == 1){
32645    if (pFile->local.bReserved) {
32646      pFile->local.bReserved = FALSE;
32647      pFile->shared->bReserved = FALSE;
32648      bReturn = TRUE;
32649    }
32650  }
32651
32652  winceMutexRelease(pFile->hMutex);
32653  return bReturn;
32654}
32655/*
32656** End of the special code for wince
32657*****************************************************************************/
32658#endif /* SQLITE_OS_WINCE */
32659
32660/*
32661** Lock a file region.
32662*/
32663static BOOL winLockFile(
32664  LPHANDLE phFile,
32665  DWORD flags,
32666  DWORD offsetLow,
32667  DWORD offsetHigh,
32668  DWORD numBytesLow,
32669  DWORD numBytesHigh
32670){
32671#if SQLITE_OS_WINCE
32672  /*
32673  ** NOTE: Windows CE is handled differently here due its lack of the Win32
32674  **       API LockFile.
32675  */
32676  return winceLockFile(phFile, offsetLow, offsetHigh,
32677                       numBytesLow, numBytesHigh);
32678#else
32679  if( isNT() ){
32680    OVERLAPPED ovlp;
32681    memset(&ovlp, 0, sizeof(OVERLAPPED));
32682    ovlp.Offset = offsetLow;
32683    ovlp.OffsetHigh = offsetHigh;
32684    return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
32685  }else{
32686    return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
32687                      numBytesHigh);
32688  }
32689#endif
32690}
32691
32692/*
32693** Unlock a file region.
32694 */
32695static BOOL winUnlockFile(
32696  LPHANDLE phFile,
32697  DWORD offsetLow,
32698  DWORD offsetHigh,
32699  DWORD numBytesLow,
32700  DWORD numBytesHigh
32701){
32702#if SQLITE_OS_WINCE
32703  /*
32704  ** NOTE: Windows CE is handled differently here due its lack of the Win32
32705  **       API UnlockFile.
32706  */
32707  return winceUnlockFile(phFile, offsetLow, offsetHigh,
32708                         numBytesLow, numBytesHigh);
32709#else
32710  if( isNT() ){
32711    OVERLAPPED ovlp;
32712    memset(&ovlp, 0, sizeof(OVERLAPPED));
32713    ovlp.Offset = offsetLow;
32714    ovlp.OffsetHigh = offsetHigh;
32715    return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
32716  }else{
32717    return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
32718                        numBytesHigh);
32719  }
32720#endif
32721}
32722
32723/*****************************************************************************
32724** The next group of routines implement the I/O methods specified
32725** by the sqlite3_io_methods object.
32726******************************************************************************/
32727
32728/*
32729** Some Microsoft compilers lack this definition.
32730*/
32731#ifndef INVALID_SET_FILE_POINTER
32732# define INVALID_SET_FILE_POINTER ((DWORD)-1)
32733#endif
32734
32735/*
32736** Move the current position of the file handle passed as the first
32737** argument to offset iOffset within the file. If successful, return 0.
32738** Otherwise, set pFile->lastErrno and return non-zero.
32739*/
32740static int seekWinFile(winFile *pFile, sqlite3_int64 iOffset){
32741#if !SQLITE_OS_WINRT
32742  LONG upperBits;                 /* Most sig. 32 bits of new offset */
32743  LONG lowerBits;                 /* Least sig. 32 bits of new offset */
32744  DWORD dwRet;                    /* Value returned by SetFilePointer() */
32745  DWORD lastErrno;                /* Value returned by GetLastError() */
32746
32747  OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
32748
32749  upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
32750  lowerBits = (LONG)(iOffset & 0xffffffff);
32751
32752  /* API oddity: If successful, SetFilePointer() returns a dword
32753  ** containing the lower 32-bits of the new file-offset. Or, if it fails,
32754  ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
32755  ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
32756  ** whether an error has actually occurred, it is also necessary to call
32757  ** GetLastError().
32758  */
32759  dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
32760
32761  if( (dwRet==INVALID_SET_FILE_POINTER
32762      && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
32763    pFile->lastErrno = lastErrno;
32764    winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
32765             "seekWinFile", pFile->zPath);
32766    OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
32767    return 1;
32768  }
32769
32770  OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
32771  return 0;
32772#else
32773  /*
32774  ** Same as above, except that this implementation works for WinRT.
32775  */
32776
32777  LARGE_INTEGER x;                /* The new offset */
32778  BOOL bRet;                      /* Value returned by SetFilePointerEx() */
32779
32780  x.QuadPart = iOffset;
32781  bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
32782
32783  if(!bRet){
32784    pFile->lastErrno = osGetLastError();
32785    winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
32786             "seekWinFile", pFile->zPath);
32787    OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
32788    return 1;
32789  }
32790
32791  OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
32792  return 0;
32793#endif
32794}
32795
32796#if SQLITE_MAX_MMAP_SIZE>0
32797/* Forward references to VFS methods */
32798static int winUnmapfile(winFile*);
32799#endif
32800
32801/*
32802** Close a file.
32803**
32804** It is reported that an attempt to close a handle might sometimes
32805** fail.  This is a very unreasonable result, but Windows is notorious
32806** for being unreasonable so I do not doubt that it might happen.  If
32807** the close fails, we pause for 100 milliseconds and try again.  As
32808** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
32809** giving up and returning an error.
32810*/
32811#define MX_CLOSE_ATTEMPT 3
32812static int winClose(sqlite3_file *id){
32813  int rc, cnt = 0;
32814  winFile *pFile = (winFile*)id;
32815
32816  assert( id!=0 );
32817#ifndef SQLITE_OMIT_WAL
32818  assert( pFile->pShm==0 );
32819#endif
32820  assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
32821  OSTRACE(("CLOSE file=%p\n", pFile->h));
32822
32823#if SQLITE_MAX_MMAP_SIZE>0
32824  rc = winUnmapfile(pFile);
32825  if( rc!=SQLITE_OK ) return rc;
32826#endif
32827
32828  do{
32829    rc = osCloseHandle(pFile->h);
32830    /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
32831  }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
32832#if SQLITE_OS_WINCE
32833#define WINCE_DELETION_ATTEMPTS 3
32834  winceDestroyLock(pFile);
32835  if( pFile->zDeleteOnClose ){
32836    int cnt = 0;
32837    while(
32838           osDeleteFileW(pFile->zDeleteOnClose)==0
32839        && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
32840        && cnt++ < WINCE_DELETION_ATTEMPTS
32841    ){
32842       sqlite3_win32_sleep(100);  /* Wait a little before trying again */
32843    }
32844    sqlite3_free(pFile->zDeleteOnClose);
32845  }
32846#endif
32847  if( rc ){
32848    pFile->h = NULL;
32849  }
32850  OpenCounter(-1);
32851  OSTRACE(("CLOSE file=%p, rc=%s\n", pFile->h, rc ? "ok" : "failed"));
32852  return rc ? SQLITE_OK
32853            : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
32854                          "winClose", pFile->zPath);
32855}
32856
32857/*
32858** Read data from a file into a buffer.  Return SQLITE_OK if all
32859** bytes were read successfully and SQLITE_IOERR if anything goes
32860** wrong.
32861*/
32862static int winRead(
32863  sqlite3_file *id,          /* File to read from */
32864  void *pBuf,                /* Write content into this buffer */
32865  int amt,                   /* Number of bytes to read */
32866  sqlite3_int64 offset       /* Begin reading at this offset */
32867){
32868#if !SQLITE_OS_WINCE
32869  OVERLAPPED overlapped;          /* The offset for ReadFile. */
32870#endif
32871  winFile *pFile = (winFile*)id;  /* file handle */
32872  DWORD nRead;                    /* Number of bytes actually read from file */
32873  int nRetry = 0;                 /* Number of retrys */
32874
32875  assert( id!=0 );
32876  assert( amt>0 );
32877  assert( offset>=0 );
32878  SimulateIOError(return SQLITE_IOERR_READ);
32879  OSTRACE(("READ file=%p, buffer=%p, amount=%d, offset=%lld, lock=%d\n",
32880           pFile->h, pBuf, amt, offset, pFile->locktype));
32881
32882#if SQLITE_MAX_MMAP_SIZE>0
32883  /* Deal with as much of this read request as possible by transfering
32884  ** data from the memory mapping using memcpy().  */
32885  if( offset<pFile->mmapSize ){
32886    if( offset+amt <= pFile->mmapSize ){
32887      memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
32888      OSTRACE(("READ-MMAP file=%p, rc=SQLITE_OK\n", pFile->h));
32889      return SQLITE_OK;
32890    }else{
32891      int nCopy = (int)(pFile->mmapSize - offset);
32892      memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
32893      pBuf = &((u8 *)pBuf)[nCopy];
32894      amt -= nCopy;
32895      offset += nCopy;
32896    }
32897  }
32898#endif
32899
32900#if SQLITE_OS_WINCE
32901  if( seekWinFile(pFile, offset) ){
32902    OSTRACE(("READ file=%p, rc=SQLITE_FULL\n", pFile->h));
32903    return SQLITE_FULL;
32904  }
32905  while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
32906#else
32907  memset(&overlapped, 0, sizeof(OVERLAPPED));
32908  overlapped.Offset = (LONG)(offset & 0xffffffff);
32909  overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
32910  while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
32911         osGetLastError()!=ERROR_HANDLE_EOF ){
32912#endif
32913    DWORD lastErrno;
32914    if( retryIoerr(&nRetry, &lastErrno) ) continue;
32915    pFile->lastErrno = lastErrno;
32916    OSTRACE(("READ file=%p, rc=SQLITE_IOERR_READ\n", pFile->h));
32917    return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
32918             "winRead", pFile->zPath);
32919  }
32920  logIoerr(nRetry);
32921  if( nRead<(DWORD)amt ){
32922    /* Unread parts of the buffer must be zero-filled */
32923    memset(&((char*)pBuf)[nRead], 0, amt-nRead);
32924    OSTRACE(("READ file=%p, rc=SQLITE_IOERR_SHORT_READ\n", pFile->h));
32925    return SQLITE_IOERR_SHORT_READ;
32926  }
32927
32928  OSTRACE(("READ file=%p, rc=SQLITE_OK\n", pFile->h));
32929  return SQLITE_OK;
32930}
32931
32932/*
32933** Write data from a buffer into a file.  Return SQLITE_OK on success
32934** or some other error code on failure.
32935*/
32936static int winWrite(
32937  sqlite3_file *id,               /* File to write into */
32938  const void *pBuf,               /* The bytes to be written */
32939  int amt,                        /* Number of bytes to write */
32940  sqlite3_int64 offset            /* Offset into the file to begin writing at */
32941){
32942  int rc = 0;                     /* True if error has occurred, else false */
32943  winFile *pFile = (winFile*)id;  /* File handle */
32944  int nRetry = 0;                 /* Number of retries */
32945
32946  assert( amt>0 );
32947  assert( pFile );
32948  SimulateIOError(return SQLITE_IOERR_WRITE);
32949  SimulateDiskfullError(return SQLITE_FULL);
32950
32951  OSTRACE(("WRITE file=%p, buffer=%p, amount=%d, offset=%lld, lock=%d\n",
32952           pFile->h, pBuf, amt, offset, pFile->locktype));
32953
32954#if SQLITE_MAX_MMAP_SIZE>0
32955  /* Deal with as much of this write request as possible by transfering
32956  ** data from the memory mapping using memcpy().  */
32957  if( offset<pFile->mmapSize ){
32958    if( offset+amt <= pFile->mmapSize ){
32959      memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
32960      OSTRACE(("WRITE-MMAP file=%p, rc=SQLITE_OK\n", pFile->h));
32961      return SQLITE_OK;
32962    }else{
32963      int nCopy = (int)(pFile->mmapSize - offset);
32964      memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
32965      pBuf = &((u8 *)pBuf)[nCopy];
32966      amt -= nCopy;
32967      offset += nCopy;
32968    }
32969  }
32970#endif
32971
32972#if SQLITE_OS_WINCE
32973  rc = seekWinFile(pFile, offset);
32974  if( rc==0 ){
32975#else
32976  {
32977#endif
32978#if !SQLITE_OS_WINCE
32979    OVERLAPPED overlapped;        /* The offset for WriteFile. */
32980#endif
32981    u8 *aRem = (u8 *)pBuf;        /* Data yet to be written */
32982    int nRem = amt;               /* Number of bytes yet to be written */
32983    DWORD nWrite;                 /* Bytes written by each WriteFile() call */
32984    DWORD lastErrno = NO_ERROR;   /* Value returned by GetLastError() */
32985
32986#if !SQLITE_OS_WINCE
32987    memset(&overlapped, 0, sizeof(OVERLAPPED));
32988    overlapped.Offset = (LONG)(offset & 0xffffffff);
32989    overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
32990#endif
32991
32992    while( nRem>0 ){
32993#if SQLITE_OS_WINCE
32994      if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
32995#else
32996      if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
32997#endif
32998        if( retryIoerr(&nRetry, &lastErrno) ) continue;
32999        break;
33000      }
33001      assert( nWrite==0 || nWrite<=(DWORD)nRem );
33002      if( nWrite==0 || nWrite>(DWORD)nRem ){
33003        lastErrno = osGetLastError();
33004        break;
33005      }
33006#if !SQLITE_OS_WINCE
33007      offset += nWrite;
33008      overlapped.Offset = (LONG)(offset & 0xffffffff);
33009      overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
33010#endif
33011      aRem += nWrite;
33012      nRem -= nWrite;
33013    }
33014    if( nRem>0 ){
33015      pFile->lastErrno = lastErrno;
33016      rc = 1;
33017    }
33018  }
33019
33020  if( rc ){
33021    if(   ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
33022       || ( pFile->lastErrno==ERROR_DISK_FULL )){
33023      OSTRACE(("WRITE file=%p, rc=SQLITE_FULL\n", pFile->h));
33024      return SQLITE_FULL;
33025    }
33026    OSTRACE(("WRITE file=%p, rc=SQLITE_IOERR_WRITE\n", pFile->h));
33027    return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
33028             "winWrite", pFile->zPath);
33029  }else{
33030    logIoerr(nRetry);
33031  }
33032  OSTRACE(("WRITE file=%p, rc=SQLITE_OK\n", pFile->h));
33033  return SQLITE_OK;
33034}
33035
33036/*
33037** Truncate an open file to a specified size
33038*/
33039static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
33040  winFile *pFile = (winFile*)id;  /* File handle object */
33041  int rc = SQLITE_OK;             /* Return code for this function */
33042  DWORD lastErrno;
33043
33044  assert( pFile );
33045  SimulateIOError(return SQLITE_IOERR_TRUNCATE);
33046  OSTRACE(("TRUNCATE file=%p, size=%lld, lock=%d\n",
33047           pFile->h, nByte, pFile->locktype));
33048
33049  /* If the user has configured a chunk-size for this file, truncate the
33050  ** file so that it consists of an integer number of chunks (i.e. the
33051  ** actual file size after the operation may be larger than the requested
33052  ** size).
33053  */
33054  if( pFile->szChunk>0 ){
33055    nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
33056  }
33057
33058  /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
33059  if( seekWinFile(pFile, nByte) ){
33060    rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
33061                     "winTruncate1", pFile->zPath);
33062  }else if( 0==osSetEndOfFile(pFile->h) &&
33063            ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
33064    pFile->lastErrno = lastErrno;
33065    rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
33066                     "winTruncate2", pFile->zPath);
33067  }
33068
33069#if SQLITE_MAX_MMAP_SIZE>0
33070  /* If the file was truncated to a size smaller than the currently
33071  ** mapped region, reduce the effective mapping size as well. SQLite will
33072  ** use read() and write() to access data beyond this point from now on.
33073  */
33074  if( pFile->pMapRegion && nByte<pFile->mmapSize ){
33075    pFile->mmapSize = nByte;
33076  }
33077#endif
33078
33079  OSTRACE(("TRUNCATE file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
33080  return rc;
33081}
33082
33083#ifdef SQLITE_TEST
33084/*
33085** Count the number of fullsyncs and normal syncs.  This is used to test
33086** that syncs and fullsyncs are occuring at the right times.
33087*/
33088SQLITE_API int sqlite3_sync_count = 0;
33089SQLITE_API int sqlite3_fullsync_count = 0;
33090#endif
33091
33092/*
33093** Make sure all writes to a particular file are committed to disk.
33094*/
33095static int winSync(sqlite3_file *id, int flags){
33096#ifndef SQLITE_NO_SYNC
33097  /*
33098  ** Used only when SQLITE_NO_SYNC is not defined.
33099   */
33100  BOOL rc;
33101#endif
33102#if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
33103    (defined(SQLITE_TEST) && defined(SQLITE_DEBUG))
33104  /*
33105  ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
33106  ** OSTRACE() macros.
33107   */
33108  winFile *pFile = (winFile*)id;
33109#else
33110  UNUSED_PARAMETER(id);
33111#endif
33112
33113  assert( pFile );
33114  /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
33115  assert((flags&0x0F)==SQLITE_SYNC_NORMAL
33116      || (flags&0x0F)==SQLITE_SYNC_FULL
33117  );
33118
33119  /* Unix cannot, but some systems may return SQLITE_FULL from here. This
33120  ** line is to test that doing so does not cause any problems.
33121  */
33122  SimulateDiskfullError( return SQLITE_FULL );
33123
33124  OSTRACE(("SYNC file=%p, flags=%x, lock=%d\n",
33125           pFile->h, flags, pFile->locktype));
33126
33127#ifndef SQLITE_TEST
33128  UNUSED_PARAMETER(flags);
33129#else
33130  if( (flags&0x0F)==SQLITE_SYNC_FULL ){
33131    sqlite3_fullsync_count++;
33132  }
33133  sqlite3_sync_count++;
33134#endif
33135
33136  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
33137  ** no-op
33138  */
33139#ifdef SQLITE_NO_SYNC
33140  return SQLITE_OK;
33141#else
33142  rc = osFlushFileBuffers(pFile->h);
33143  SimulateIOError( rc=FALSE );
33144  if( rc ){
33145    OSTRACE(("SYNC file=%p, rc=SQLITE_OK\n", pFile->h));
33146    return SQLITE_OK;
33147  }else{
33148    pFile->lastErrno = osGetLastError();
33149    OSTRACE(("SYNC file=%p, rc=SQLITE_IOERR_FSYNC\n", pFile->h));
33150    return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
33151             "winSync", pFile->zPath);
33152  }
33153#endif
33154}
33155
33156/*
33157** Determine the current size of a file in bytes
33158*/
33159static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
33160  winFile *pFile = (winFile*)id;
33161  int rc = SQLITE_OK;
33162
33163  assert( id!=0 );
33164  assert( pSize!=0 );
33165  SimulateIOError(return SQLITE_IOERR_FSTAT);
33166  OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
33167
33168#if SQLITE_OS_WINRT
33169  {
33170    FILE_STANDARD_INFO info;
33171    if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
33172                                     &info, sizeof(info)) ){
33173      *pSize = info.EndOfFile.QuadPart;
33174    }else{
33175      pFile->lastErrno = osGetLastError();
33176      rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
33177                       "winFileSize", pFile->zPath);
33178    }
33179  }
33180#else
33181  {
33182    DWORD upperBits;
33183    DWORD lowerBits;
33184    DWORD lastErrno;
33185
33186    lowerBits = osGetFileSize(pFile->h, &upperBits);
33187    *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
33188    if(   (lowerBits == INVALID_FILE_SIZE)
33189       && ((lastErrno = osGetLastError())!=NO_ERROR) ){
33190      pFile->lastErrno = lastErrno;
33191      rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
33192             "winFileSize", pFile->zPath);
33193    }
33194  }
33195#endif
33196  OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
33197           pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
33198  return rc;
33199}
33200
33201/*
33202** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
33203*/
33204#ifndef LOCKFILE_FAIL_IMMEDIATELY
33205# define LOCKFILE_FAIL_IMMEDIATELY 1
33206#endif
33207
33208#ifndef LOCKFILE_EXCLUSIVE_LOCK
33209# define LOCKFILE_EXCLUSIVE_LOCK 2
33210#endif
33211
33212/*
33213** Historically, SQLite has used both the LockFile and LockFileEx functions.
33214** When the LockFile function was used, it was always expected to fail
33215** immediately if the lock could not be obtained.  Also, it always expected to
33216** obtain an exclusive lock.  These flags are used with the LockFileEx function
33217** and reflect those expectations; therefore, they should not be changed.
33218*/
33219#ifndef SQLITE_LOCKFILE_FLAGS
33220# define SQLITE_LOCKFILE_FLAGS   (LOCKFILE_FAIL_IMMEDIATELY | \
33221                                  LOCKFILE_EXCLUSIVE_LOCK)
33222#endif
33223
33224/*
33225** Currently, SQLite never calls the LockFileEx function without wanting the
33226** call to fail immediately if the lock cannot be obtained.
33227*/
33228#ifndef SQLITE_LOCKFILEEX_FLAGS
33229# define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
33230#endif
33231
33232/*
33233** Acquire a reader lock.
33234** Different API routines are called depending on whether or not this
33235** is Win9x or WinNT.
33236*/
33237static int getReadLock(winFile *pFile){
33238  int res;
33239  OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
33240  if( isNT() ){
33241#if SQLITE_OS_WINCE
33242    /*
33243    ** NOTE: Windows CE is handled differently here due its lack of the Win32
33244    **       API LockFileEx.
33245    */
33246    res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
33247#else
33248    res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
33249                      SHARED_SIZE, 0);
33250#endif
33251  }
33252#ifdef SQLITE_WIN32_HAS_ANSI
33253  else{
33254    int lk;
33255    sqlite3_randomness(sizeof(lk), &lk);
33256    pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
33257    res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
33258                      SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
33259  }
33260#endif
33261  if( res == 0 ){
33262    pFile->lastErrno = osGetLastError();
33263    /* No need to log a failure to lock */
33264  }
33265  OSTRACE(("READ-LOCK file=%p, rc=%s\n", pFile->h, sqlite3ErrName(res)));
33266  return res;
33267}
33268
33269/*
33270** Undo a readlock
33271*/
33272static int unlockReadLock(winFile *pFile){
33273  int res;
33274  DWORD lastErrno;
33275  OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
33276  if( isNT() ){
33277    res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
33278  }
33279#ifdef SQLITE_WIN32_HAS_ANSI
33280  else{
33281    res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
33282  }
33283#endif
33284  if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
33285    pFile->lastErrno = lastErrno;
33286    winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
33287             "unlockReadLock", pFile->zPath);
33288  }
33289  OSTRACE(("READ-UNLOCK file=%p, rc=%s\n", pFile->h, sqlite3ErrName(res)));
33290  return res;
33291}
33292
33293/*
33294** Lock the file with the lock specified by parameter locktype - one
33295** of the following:
33296**
33297**     (1) SHARED_LOCK
33298**     (2) RESERVED_LOCK
33299**     (3) PENDING_LOCK
33300**     (4) EXCLUSIVE_LOCK
33301**
33302** Sometimes when requesting one lock state, additional lock states
33303** are inserted in between.  The locking might fail on one of the later
33304** transitions leaving the lock state different from what it started but
33305** still short of its goal.  The following chart shows the allowed
33306** transitions and the inserted intermediate states:
33307**
33308**    UNLOCKED -> SHARED
33309**    SHARED -> RESERVED
33310**    SHARED -> (PENDING) -> EXCLUSIVE
33311**    RESERVED -> (PENDING) -> EXCLUSIVE
33312**    PENDING -> EXCLUSIVE
33313**
33314** This routine will only increase a lock.  The winUnlock() routine
33315** erases all locks at once and returns us immediately to locking level 0.
33316** It is not possible to lower the locking level one step at a time.  You
33317** must go straight to locking level 0.
33318*/
33319static int winLock(sqlite3_file *id, int locktype){
33320  int rc = SQLITE_OK;    /* Return code from subroutines */
33321  int res = 1;           /* Result of a Windows lock call */
33322  int newLocktype;       /* Set pFile->locktype to this value before exiting */
33323  int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
33324  winFile *pFile = (winFile*)id;
33325  DWORD lastErrno = NO_ERROR;
33326
33327  assert( id!=0 );
33328  OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
33329           pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
33330
33331  /* If there is already a lock of this type or more restrictive on the
33332  ** OsFile, do nothing. Don't use the end_lock: exit path, as
33333  ** sqlite3OsEnterMutex() hasn't been called yet.
33334  */
33335  if( pFile->locktype>=locktype ){
33336    OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
33337    return SQLITE_OK;
33338  }
33339
33340  /* Make sure the locking sequence is correct
33341  */
33342  assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
33343  assert( locktype!=PENDING_LOCK );
33344  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
33345
33346  /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
33347  ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
33348  ** the PENDING_LOCK byte is temporary.
33349  */
33350  newLocktype = pFile->locktype;
33351  if(   (pFile->locktype==NO_LOCK)
33352     || (   (locktype==EXCLUSIVE_LOCK)
33353         && (pFile->locktype==RESERVED_LOCK))
33354  ){
33355    int cnt = 3;
33356    while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
33357                                         PENDING_BYTE, 0, 1, 0))==0 ){
33358      /* Try 3 times to get the pending lock.  This is needed to work
33359      ** around problems caused by indexing and/or anti-virus software on
33360      ** Windows systems.
33361      ** If you are using this code as a model for alternative VFSes, do not
33362      ** copy this retry logic.  It is a hack intended for Windows only.
33363      */
33364      OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, rc=%s\n",
33365               pFile->h, cnt, sqlite3ErrName(res)));
33366      if( cnt ) sqlite3_win32_sleep(1);
33367    }
33368    gotPendingLock = res;
33369    if( !res ){
33370      lastErrno = osGetLastError();
33371    }
33372  }
33373
33374  /* Acquire a shared lock
33375  */
33376  if( locktype==SHARED_LOCK && res ){
33377    assert( pFile->locktype==NO_LOCK );
33378    res = getReadLock(pFile);
33379    if( res ){
33380      newLocktype = SHARED_LOCK;
33381    }else{
33382      lastErrno = osGetLastError();
33383    }
33384  }
33385
33386  /* Acquire a RESERVED lock
33387  */
33388  if( locktype==RESERVED_LOCK && res ){
33389    assert( pFile->locktype==SHARED_LOCK );
33390    res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
33391    if( res ){
33392      newLocktype = RESERVED_LOCK;
33393    }else{
33394      lastErrno = osGetLastError();
33395    }
33396  }
33397
33398  /* Acquire a PENDING lock
33399  */
33400  if( locktype==EXCLUSIVE_LOCK && res ){
33401    newLocktype = PENDING_LOCK;
33402    gotPendingLock = 0;
33403  }
33404
33405  /* Acquire an EXCLUSIVE lock
33406  */
33407  if( locktype==EXCLUSIVE_LOCK && res ){
33408    assert( pFile->locktype>=SHARED_LOCK );
33409    res = unlockReadLock(pFile);
33410    res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
33411                      SHARED_SIZE, 0);
33412    if( res ){
33413      newLocktype = EXCLUSIVE_LOCK;
33414    }else{
33415      lastErrno = osGetLastError();
33416      getReadLock(pFile);
33417    }
33418  }
33419
33420  /* If we are holding a PENDING lock that ought to be released, then
33421  ** release it now.
33422  */
33423  if( gotPendingLock && locktype==SHARED_LOCK ){
33424    winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
33425  }
33426
33427  /* Update the state of the lock has held in the file descriptor then
33428  ** return the appropriate result code.
33429  */
33430  if( res ){
33431    rc = SQLITE_OK;
33432  }else{
33433    OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
33434             pFile->h, locktype, newLocktype));
33435    pFile->lastErrno = lastErrno;
33436    rc = SQLITE_BUSY;
33437  }
33438  pFile->locktype = (u8)newLocktype;
33439  OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
33440           pFile->h, pFile->locktype, sqlite3ErrName(rc)));
33441  return rc;
33442}
33443
33444/*
33445** This routine checks if there is a RESERVED lock held on the specified
33446** file by this or any other process. If such a lock is held, return
33447** non-zero, otherwise zero.
33448*/
33449static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
33450  int rc;
33451  winFile *pFile = (winFile*)id;
33452
33453  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
33454  OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
33455
33456  assert( id!=0 );
33457  if( pFile->locktype>=RESERVED_LOCK ){
33458    rc = 1;
33459    OSTRACE(("TEST-WR-LOCK file=%p, rc=%d (local)\n", pFile->h, rc));
33460  }else{
33461    rc = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE, 0, 1, 0);
33462    if( rc ){
33463      winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
33464    }
33465    rc = !rc;
33466    OSTRACE(("TEST-WR-LOCK file=%p, rc=%d (remote)\n", pFile->h, rc));
33467  }
33468  *pResOut = rc;
33469  OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
33470           pFile->h, pResOut, *pResOut));
33471  return SQLITE_OK;
33472}
33473
33474/*
33475** Lower the locking level on file descriptor id to locktype.  locktype
33476** must be either NO_LOCK or SHARED_LOCK.
33477**
33478** If the locking level of the file descriptor is already at or below
33479** the requested locking level, this routine is a no-op.
33480**
33481** It is not possible for this routine to fail if the second argument
33482** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
33483** might return SQLITE_IOERR;
33484*/
33485static int winUnlock(sqlite3_file *id, int locktype){
33486  int type;
33487  winFile *pFile = (winFile*)id;
33488  int rc = SQLITE_OK;
33489  assert( pFile!=0 );
33490  assert( locktype<=SHARED_LOCK );
33491  OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
33492           pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
33493  type = pFile->locktype;
33494  if( type>=EXCLUSIVE_LOCK ){
33495    winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
33496    if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
33497      /* This should never happen.  We should always be able to
33498      ** reacquire the read lock */
33499      rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
33500               "winUnlock", pFile->zPath);
33501    }
33502  }
33503  if( type>=RESERVED_LOCK ){
33504    winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
33505  }
33506  if( locktype==NO_LOCK && type>=SHARED_LOCK ){
33507    unlockReadLock(pFile);
33508  }
33509  if( type>=PENDING_LOCK ){
33510    winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
33511  }
33512  pFile->locktype = (u8)locktype;
33513  OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
33514           pFile->h, pFile->locktype, sqlite3ErrName(rc)));
33515  return rc;
33516}
33517
33518/*
33519** If *pArg is inititially negative then this is a query.  Set *pArg to
33520** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
33521**
33522** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
33523*/
33524static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
33525  if( *pArg<0 ){
33526    *pArg = (pFile->ctrlFlags & mask)!=0;
33527  }else if( (*pArg)==0 ){
33528    pFile->ctrlFlags &= ~mask;
33529  }else{
33530    pFile->ctrlFlags |= mask;
33531  }
33532}
33533
33534/* Forward declaration */
33535static int getTempname(int nBuf, char *zBuf);
33536
33537/*
33538** Control and query of the open file handle.
33539*/
33540static int winFileControl(sqlite3_file *id, int op, void *pArg){
33541  winFile *pFile = (winFile*)id;
33542  OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
33543  switch( op ){
33544    case SQLITE_FCNTL_LOCKSTATE: {
33545      *(int*)pArg = pFile->locktype;
33546      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
33547      return SQLITE_OK;
33548    }
33549    case SQLITE_LAST_ERRNO: {
33550      *(int*)pArg = (int)pFile->lastErrno;
33551      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
33552      return SQLITE_OK;
33553    }
33554    case SQLITE_FCNTL_CHUNK_SIZE: {
33555      pFile->szChunk = *(int *)pArg;
33556      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
33557      return SQLITE_OK;
33558    }
33559    case SQLITE_FCNTL_SIZE_HINT: {
33560      if( pFile->szChunk>0 ){
33561        sqlite3_int64 oldSz;
33562        int rc = winFileSize(id, &oldSz);
33563        if( rc==SQLITE_OK ){
33564          sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
33565          if( newSz>oldSz ){
33566            SimulateIOErrorBenign(1);
33567            rc = winTruncate(id, newSz);
33568            SimulateIOErrorBenign(0);
33569          }
33570        }
33571        OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
33572        return rc;
33573      }
33574      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
33575      return SQLITE_OK;
33576    }
33577    case SQLITE_FCNTL_PERSIST_WAL: {
33578      winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
33579      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
33580      return SQLITE_OK;
33581    }
33582    case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
33583      winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
33584      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
33585      return SQLITE_OK;
33586    }
33587    case SQLITE_FCNTL_VFSNAME: {
33588      *(char**)pArg = sqlite3_mprintf("win32");
33589      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
33590      return SQLITE_OK;
33591    }
33592    case SQLITE_FCNTL_WIN32_AV_RETRY: {
33593      int *a = (int*)pArg;
33594      if( a[0]>0 ){
33595        win32IoerrRetry = a[0];
33596      }else{
33597        a[0] = win32IoerrRetry;
33598      }
33599      if( a[1]>0 ){
33600        win32IoerrRetryDelay = a[1];
33601      }else{
33602        a[1] = win32IoerrRetryDelay;
33603      }
33604      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
33605      return SQLITE_OK;
33606    }
33607    case SQLITE_FCNTL_TEMPFILENAME: {
33608      char *zTFile = sqlite3MallocZero( pFile->pVfs->mxPathname );
33609      if( zTFile ){
33610        getTempname(pFile->pVfs->mxPathname, zTFile);
33611        *(char**)pArg = zTFile;
33612      }
33613      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
33614      return SQLITE_OK;
33615    }
33616#if SQLITE_MAX_MMAP_SIZE>0
33617    case SQLITE_FCNTL_MMAP_SIZE: {
33618      i64 newLimit = *(i64*)pArg;
33619      if( newLimit>sqlite3GlobalConfig.mxMmap ){
33620        newLimit = sqlite3GlobalConfig.mxMmap;
33621      }
33622      *(i64*)pArg = pFile->mmapSizeMax;
33623      if( newLimit>=0 ) pFile->mmapSizeMax = newLimit;
33624      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
33625      return SQLITE_OK;
33626    }
33627#endif
33628  }
33629  OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
33630  return SQLITE_NOTFOUND;
33631}
33632
33633/*
33634** Return the sector size in bytes of the underlying block device for
33635** the specified file. This is almost always 512 bytes, but may be
33636** larger for some devices.
33637**
33638** SQLite code assumes this function cannot fail. It also assumes that
33639** if two files are created in the same file-system directory (i.e.
33640** a database and its journal file) that the sector size will be the
33641** same for both.
33642*/
33643static int winSectorSize(sqlite3_file *id){
33644  (void)id;
33645  return SQLITE_DEFAULT_SECTOR_SIZE;
33646}
33647
33648/*
33649** Return a vector of device characteristics.
33650*/
33651static int winDeviceCharacteristics(sqlite3_file *id){
33652  winFile *p = (winFile*)id;
33653  return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
33654         ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
33655}
33656
33657/*
33658** Windows will only let you create file view mappings
33659** on allocation size granularity boundaries.
33660** During sqlite3_os_init() we do a GetSystemInfo()
33661** to get the granularity size.
33662*/
33663SYSTEM_INFO winSysInfo;
33664
33665#ifndef SQLITE_OMIT_WAL
33666
33667/*
33668** Helper functions to obtain and relinquish the global mutex. The
33669** global mutex is used to protect the winLockInfo objects used by
33670** this file, all of which may be shared by multiple threads.
33671**
33672** Function winShmMutexHeld() is used to assert() that the global mutex
33673** is held when required. This function is only used as part of assert()
33674** statements. e.g.
33675**
33676**   winShmEnterMutex()
33677**     assert( winShmMutexHeld() );
33678**   winShmLeaveMutex()
33679*/
33680static void winShmEnterMutex(void){
33681  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
33682}
33683static void winShmLeaveMutex(void){
33684  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
33685}
33686#ifdef SQLITE_DEBUG
33687static int winShmMutexHeld(void) {
33688  return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
33689}
33690#endif
33691
33692/*
33693** Object used to represent a single file opened and mmapped to provide
33694** shared memory.  When multiple threads all reference the same
33695** log-summary, each thread has its own winFile object, but they all
33696** point to a single instance of this object.  In other words, each
33697** log-summary is opened only once per process.
33698**
33699** winShmMutexHeld() must be true when creating or destroying
33700** this object or while reading or writing the following fields:
33701**
33702**      nRef
33703**      pNext
33704**
33705** The following fields are read-only after the object is created:
33706**
33707**      fid
33708**      zFilename
33709**
33710** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
33711** winShmMutexHeld() is true when reading or writing any other field
33712** in this structure.
33713**
33714*/
33715struct winShmNode {
33716  sqlite3_mutex *mutex;      /* Mutex to access this object */
33717  char *zFilename;           /* Name of the file */
33718  winFile hFile;             /* File handle from winOpen */
33719
33720  int szRegion;              /* Size of shared-memory regions */
33721  int nRegion;               /* Size of array apRegion */
33722  struct ShmRegion {
33723    HANDLE hMap;             /* File handle from CreateFileMapping */
33724    void *pMap;
33725  } *aRegion;
33726  DWORD lastErrno;           /* The Windows errno from the last I/O error */
33727
33728  int nRef;                  /* Number of winShm objects pointing to this */
33729  winShm *pFirst;            /* All winShm objects pointing to this */
33730  winShmNode *pNext;         /* Next in list of all winShmNode objects */
33731#ifdef SQLITE_DEBUG
33732  u8 nextShmId;              /* Next available winShm.id value */
33733#endif
33734};
33735
33736/*
33737** A global array of all winShmNode objects.
33738**
33739** The winShmMutexHeld() must be true while reading or writing this list.
33740*/
33741static winShmNode *winShmNodeList = 0;
33742
33743/*
33744** Structure used internally by this VFS to record the state of an
33745** open shared memory connection.
33746**
33747** The following fields are initialized when this object is created and
33748** are read-only thereafter:
33749**
33750**    winShm.pShmNode
33751**    winShm.id
33752**
33753** All other fields are read/write.  The winShm.pShmNode->mutex must be held
33754** while accessing any read/write fields.
33755*/
33756struct winShm {
33757  winShmNode *pShmNode;      /* The underlying winShmNode object */
33758  winShm *pNext;             /* Next winShm with the same winShmNode */
33759  u8 hasMutex;               /* True if holding the winShmNode mutex */
33760  u16 sharedMask;            /* Mask of shared locks held */
33761  u16 exclMask;              /* Mask of exclusive locks held */
33762#ifdef SQLITE_DEBUG
33763  u8 id;                     /* Id of this connection with its winShmNode */
33764#endif
33765};
33766
33767/*
33768** Constants used for locking
33769*/
33770#define WIN_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
33771#define WIN_SHM_DMS    (WIN_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
33772
33773/*
33774** Apply advisory locks for all n bytes beginning at ofst.
33775*/
33776#define _SHM_UNLCK  1
33777#define _SHM_RDLCK  2
33778#define _SHM_WRLCK  3
33779static int winShmSystemLock(
33780  winShmNode *pFile,    /* Apply locks to this open shared-memory segment */
33781  int lockType,         /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
33782  int ofst,             /* Offset to first byte to be locked/unlocked */
33783  int nByte             /* Number of bytes to lock or unlock */
33784){
33785  int rc = 0;           /* Result code form Lock/UnlockFileEx() */
33786
33787  /* Access to the winShmNode object is serialized by the caller */
33788  assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
33789
33790  OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
33791           pFile->hFile.h, lockType, ofst, nByte));
33792
33793  /* Release/Acquire the system-level lock */
33794  if( lockType==_SHM_UNLCK ){
33795    rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
33796  }else{
33797    /* Initialize the locking parameters */
33798    DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
33799    if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
33800    rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
33801  }
33802
33803  if( rc!= 0 ){
33804    rc = SQLITE_OK;
33805  }else{
33806    pFile->lastErrno =  osGetLastError();
33807    rc = SQLITE_BUSY;
33808  }
33809
33810  OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
33811           pFile->hFile.h, (lockType == _SHM_UNLCK) ? "winUnlockFile" :
33812           "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
33813
33814  return rc;
33815}
33816
33817/* Forward references to VFS methods */
33818static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
33819static int winDelete(sqlite3_vfs *,const char*,int);
33820
33821/*
33822** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
33823**
33824** This is not a VFS shared-memory method; it is a utility function called
33825** by VFS shared-memory methods.
33826*/
33827static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
33828  winShmNode **pp;
33829  winShmNode *p;
33830  BOOL bRc;
33831  assert( winShmMutexHeld() );
33832  OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
33833           osGetCurrentProcessId(), deleteFlag));
33834  pp = &winShmNodeList;
33835  while( (p = *pp)!=0 ){
33836    if( p->nRef==0 ){
33837      int i;
33838      if( p->mutex ) sqlite3_mutex_free(p->mutex);
33839      for(i=0; i<p->nRegion; i++){
33840        bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
33841        OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
33842                 osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
33843        bRc = osCloseHandle(p->aRegion[i].hMap);
33844        OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
33845                 osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
33846      }
33847      if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
33848        SimulateIOErrorBenign(1);
33849        winClose((sqlite3_file *)&p->hFile);
33850        SimulateIOErrorBenign(0);
33851      }
33852      if( deleteFlag ){
33853        SimulateIOErrorBenign(1);
33854        sqlite3BeginBenignMalloc();
33855        winDelete(pVfs, p->zFilename, 0);
33856        sqlite3EndBenignMalloc();
33857        SimulateIOErrorBenign(0);
33858      }
33859      *pp = p->pNext;
33860      sqlite3_free(p->aRegion);
33861      sqlite3_free(p);
33862    }else{
33863      pp = &p->pNext;
33864    }
33865  }
33866}
33867
33868/*
33869** Open the shared-memory area associated with database file pDbFd.
33870**
33871** When opening a new shared-memory file, if no other instances of that
33872** file are currently open, in this process or in other processes, then
33873** the file must be truncated to zero length or have its header cleared.
33874*/
33875static int winOpenSharedMemory(winFile *pDbFd){
33876  struct winShm *p;                  /* The connection to be opened */
33877  struct winShmNode *pShmNode = 0;   /* The underlying mmapped file */
33878  int rc;                            /* Result code */
33879  struct winShmNode *pNew;           /* Newly allocated winShmNode */
33880  int nName;                         /* Size of zName in bytes */
33881
33882  assert( pDbFd->pShm==0 );    /* Not previously opened */
33883
33884  /* Allocate space for the new sqlite3_shm object.  Also speculatively
33885  ** allocate space for a new winShmNode and filename.
33886  */
33887  p = sqlite3MallocZero( sizeof(*p) );
33888  if( p==0 ) return SQLITE_IOERR_NOMEM;
33889  nName = sqlite3Strlen30(pDbFd->zPath);
33890  pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
33891  if( pNew==0 ){
33892    sqlite3_free(p);
33893    return SQLITE_IOERR_NOMEM;
33894  }
33895  pNew->zFilename = (char*)&pNew[1];
33896  sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
33897  sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
33898
33899  /* Look to see if there is an existing winShmNode that can be used.
33900  ** If no matching winShmNode currently exists, create a new one.
33901  */
33902  winShmEnterMutex();
33903  for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
33904    /* TBD need to come up with better match here.  Perhaps
33905    ** use FILE_ID_BOTH_DIR_INFO Structure.
33906    */
33907    if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
33908  }
33909  if( pShmNode ){
33910    sqlite3_free(pNew);
33911  }else{
33912    pShmNode = pNew;
33913    pNew = 0;
33914    ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
33915    pShmNode->pNext = winShmNodeList;
33916    winShmNodeList = pShmNode;
33917
33918    pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
33919    if( pShmNode->mutex==0 ){
33920      rc = SQLITE_IOERR_NOMEM;
33921      goto shm_open_err;
33922    }
33923
33924    rc = winOpen(pDbFd->pVfs,
33925                 pShmNode->zFilename,             /* Name of the file (UTF-8) */
33926                 (sqlite3_file*)&pShmNode->hFile,  /* File handle here */
33927                 SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
33928                 0);
33929    if( SQLITE_OK!=rc ){
33930      goto shm_open_err;
33931    }
33932
33933    /* Check to see if another process is holding the dead-man switch.
33934    ** If not, truncate the file to zero length.
33935    */
33936    if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
33937      rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
33938      if( rc!=SQLITE_OK ){
33939        rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
33940                 "winOpenShm", pDbFd->zPath);
33941      }
33942    }
33943    if( rc==SQLITE_OK ){
33944      winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
33945      rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
33946    }
33947    if( rc ) goto shm_open_err;
33948  }
33949
33950  /* Make the new connection a child of the winShmNode */
33951  p->pShmNode = pShmNode;
33952#ifdef SQLITE_DEBUG
33953  p->id = pShmNode->nextShmId++;
33954#endif
33955  pShmNode->nRef++;
33956  pDbFd->pShm = p;
33957  winShmLeaveMutex();
33958
33959  /* The reference count on pShmNode has already been incremented under
33960  ** the cover of the winShmEnterMutex() mutex and the pointer from the
33961  ** new (struct winShm) object to the pShmNode has been set. All that is
33962  ** left to do is to link the new object into the linked list starting
33963  ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
33964  ** mutex.
33965  */
33966  sqlite3_mutex_enter(pShmNode->mutex);
33967  p->pNext = pShmNode->pFirst;
33968  pShmNode->pFirst = p;
33969  sqlite3_mutex_leave(pShmNode->mutex);
33970  return SQLITE_OK;
33971
33972  /* Jump here on any error */
33973shm_open_err:
33974  winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
33975  winShmPurge(pDbFd->pVfs, 0);      /* This call frees pShmNode if required */
33976  sqlite3_free(p);
33977  sqlite3_free(pNew);
33978  winShmLeaveMutex();
33979  return rc;
33980}
33981
33982/*
33983** Close a connection to shared-memory.  Delete the underlying
33984** storage if deleteFlag is true.
33985*/
33986static int winShmUnmap(
33987  sqlite3_file *fd,          /* Database holding shared memory */
33988  int deleteFlag             /* Delete after closing if true */
33989){
33990  winFile *pDbFd;       /* Database holding shared-memory */
33991  winShm *p;            /* The connection to be closed */
33992  winShmNode *pShmNode; /* The underlying shared-memory file */
33993  winShm **pp;          /* For looping over sibling connections */
33994
33995  pDbFd = (winFile*)fd;
33996  p = pDbFd->pShm;
33997  if( p==0 ) return SQLITE_OK;
33998  pShmNode = p->pShmNode;
33999
34000  /* Remove connection p from the set of connections associated
34001  ** with pShmNode */
34002  sqlite3_mutex_enter(pShmNode->mutex);
34003  for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
34004  *pp = p->pNext;
34005
34006  /* Free the connection p */
34007  sqlite3_free(p);
34008  pDbFd->pShm = 0;
34009  sqlite3_mutex_leave(pShmNode->mutex);
34010
34011  /* If pShmNode->nRef has reached 0, then close the underlying
34012  ** shared-memory file, too */
34013  winShmEnterMutex();
34014  assert( pShmNode->nRef>0 );
34015  pShmNode->nRef--;
34016  if( pShmNode->nRef==0 ){
34017    winShmPurge(pDbFd->pVfs, deleteFlag);
34018  }
34019  winShmLeaveMutex();
34020
34021  return SQLITE_OK;
34022}
34023
34024/*
34025** Change the lock state for a shared-memory segment.
34026*/
34027static int winShmLock(
34028  sqlite3_file *fd,          /* Database file holding the shared memory */
34029  int ofst,                  /* First lock to acquire or release */
34030  int n,                     /* Number of locks to acquire or release */
34031  int flags                  /* What to do with the lock */
34032){
34033  winFile *pDbFd = (winFile*)fd;        /* Connection holding shared memory */
34034  winShm *p = pDbFd->pShm;              /* The shared memory being locked */
34035  winShm *pX;                           /* For looping over all siblings */
34036  winShmNode *pShmNode = p->pShmNode;
34037  int rc = SQLITE_OK;                   /* Result code */
34038  u16 mask;                             /* Mask of locks to take or release */
34039
34040  assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
34041  assert( n>=1 );
34042  assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
34043       || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
34044       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
34045       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
34046  assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
34047
34048  mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
34049  assert( n>1 || mask==(1<<ofst) );
34050  sqlite3_mutex_enter(pShmNode->mutex);
34051  if( flags & SQLITE_SHM_UNLOCK ){
34052    u16 allMask = 0; /* Mask of locks held by siblings */
34053
34054    /* See if any siblings hold this same lock */
34055    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
34056      if( pX==p ) continue;
34057      assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
34058      allMask |= pX->sharedMask;
34059    }
34060
34061    /* Unlock the system-level locks */
34062    if( (mask & allMask)==0 ){
34063      rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
34064    }else{
34065      rc = SQLITE_OK;
34066    }
34067
34068    /* Undo the local locks */
34069    if( rc==SQLITE_OK ){
34070      p->exclMask &= ~mask;
34071      p->sharedMask &= ~mask;
34072    }
34073  }else if( flags & SQLITE_SHM_SHARED ){
34074    u16 allShared = 0;  /* Union of locks held by connections other than "p" */
34075
34076    /* Find out which shared locks are already held by sibling connections.
34077    ** If any sibling already holds an exclusive lock, go ahead and return
34078    ** SQLITE_BUSY.
34079    */
34080    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
34081      if( (pX->exclMask & mask)!=0 ){
34082        rc = SQLITE_BUSY;
34083        break;
34084      }
34085      allShared |= pX->sharedMask;
34086    }
34087
34088    /* Get shared locks at the system level, if necessary */
34089    if( rc==SQLITE_OK ){
34090      if( (allShared & mask)==0 ){
34091        rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
34092      }else{
34093        rc = SQLITE_OK;
34094      }
34095    }
34096
34097    /* Get the local shared locks */
34098    if( rc==SQLITE_OK ){
34099      p->sharedMask |= mask;
34100    }
34101  }else{
34102    /* Make sure no sibling connections hold locks that will block this
34103    ** lock.  If any do, return SQLITE_BUSY right away.
34104    */
34105    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
34106      if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
34107        rc = SQLITE_BUSY;
34108        break;
34109      }
34110    }
34111
34112    /* Get the exclusive locks at the system level.  Then if successful
34113    ** also mark the local connection as being locked.
34114    */
34115    if( rc==SQLITE_OK ){
34116      rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
34117      if( rc==SQLITE_OK ){
34118        assert( (p->sharedMask & mask)==0 );
34119        p->exclMask |= mask;
34120      }
34121    }
34122  }
34123  sqlite3_mutex_leave(pShmNode->mutex);
34124  OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
34125           osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
34126           sqlite3ErrName(rc)));
34127  return rc;
34128}
34129
34130/*
34131** Implement a memory barrier or memory fence on shared memory.
34132**
34133** All loads and stores begun before the barrier must complete before
34134** any load or store begun after the barrier.
34135*/
34136static void winShmBarrier(
34137  sqlite3_file *fd          /* Database holding the shared memory */
34138){
34139  UNUSED_PARAMETER(fd);
34140  /* MemoryBarrier(); // does not work -- do not know why not */
34141  winShmEnterMutex();
34142  winShmLeaveMutex();
34143}
34144
34145/*
34146** This function is called to obtain a pointer to region iRegion of the
34147** shared-memory associated with the database file fd. Shared-memory regions
34148** are numbered starting from zero. Each shared-memory region is szRegion
34149** bytes in size.
34150**
34151** If an error occurs, an error code is returned and *pp is set to NULL.
34152**
34153** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
34154** region has not been allocated (by any client, including one running in a
34155** separate process), then *pp is set to NULL and SQLITE_OK returned. If
34156** isWrite is non-zero and the requested shared-memory region has not yet
34157** been allocated, it is allocated by this function.
34158**
34159** If the shared-memory region has already been allocated or is allocated by
34160** this call as described above, then it is mapped into this processes
34161** address space (if it is not already), *pp is set to point to the mapped
34162** memory and SQLITE_OK returned.
34163*/
34164static int winShmMap(
34165  sqlite3_file *fd,               /* Handle open on database file */
34166  int iRegion,                    /* Region to retrieve */
34167  int szRegion,                   /* Size of regions */
34168  int isWrite,                    /* True to extend file if necessary */
34169  void volatile **pp              /* OUT: Mapped memory */
34170){
34171  winFile *pDbFd = (winFile*)fd;
34172  winShm *p = pDbFd->pShm;
34173  winShmNode *pShmNode;
34174  int rc = SQLITE_OK;
34175
34176  if( !p ){
34177    rc = winOpenSharedMemory(pDbFd);
34178    if( rc!=SQLITE_OK ) return rc;
34179    p = pDbFd->pShm;
34180  }
34181  pShmNode = p->pShmNode;
34182
34183  sqlite3_mutex_enter(pShmNode->mutex);
34184  assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
34185
34186  if( pShmNode->nRegion<=iRegion ){
34187    struct ShmRegion *apNew;           /* New aRegion[] array */
34188    int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
34189    sqlite3_int64 sz;                  /* Current size of wal-index file */
34190
34191    pShmNode->szRegion = szRegion;
34192
34193    /* The requested region is not mapped into this processes address space.
34194    ** Check to see if it has been allocated (i.e. if the wal-index file is
34195    ** large enough to contain the requested region).
34196    */
34197    rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
34198    if( rc!=SQLITE_OK ){
34199      rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
34200               "winShmMap1", pDbFd->zPath);
34201      goto shmpage_out;
34202    }
34203
34204    if( sz<nByte ){
34205      /* The requested memory region does not exist. If isWrite is set to
34206      ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
34207      **
34208      ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
34209      ** the requested memory region.
34210      */
34211      if( !isWrite ) goto shmpage_out;
34212      rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
34213      if( rc!=SQLITE_OK ){
34214        rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
34215                 "winShmMap2", pDbFd->zPath);
34216        goto shmpage_out;
34217      }
34218    }
34219
34220    /* Map the requested memory region into this processes address space. */
34221    apNew = (struct ShmRegion *)sqlite3_realloc(
34222        pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
34223    );
34224    if( !apNew ){
34225      rc = SQLITE_IOERR_NOMEM;
34226      goto shmpage_out;
34227    }
34228    pShmNode->aRegion = apNew;
34229
34230    while( pShmNode->nRegion<=iRegion ){
34231      HANDLE hMap = NULL;         /* file-mapping handle */
34232      void *pMap = 0;             /* Mapped memory region */
34233
34234#if SQLITE_OS_WINRT
34235      hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
34236          NULL, PAGE_READWRITE, nByte, NULL
34237      );
34238#elif defined(SQLITE_WIN32_HAS_WIDE)
34239      hMap = osCreateFileMappingW(pShmNode->hFile.h,
34240          NULL, PAGE_READWRITE, 0, nByte, NULL
34241      );
34242#elif defined(SQLITE_WIN32_HAS_ANSI)
34243      hMap = osCreateFileMappingA(pShmNode->hFile.h,
34244          NULL, PAGE_READWRITE, 0, nByte, NULL
34245      );
34246#endif
34247      OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
34248               osGetCurrentProcessId(), pShmNode->nRegion, nByte,
34249               hMap ? "ok" : "failed"));
34250      if( hMap ){
34251        int iOffset = pShmNode->nRegion*szRegion;
34252        int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
34253#if SQLITE_OS_WINRT
34254        pMap = osMapViewOfFileFromApp(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
34255            iOffset - iOffsetShift, szRegion + iOffsetShift
34256        );
34257#else
34258        pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
34259            0, iOffset - iOffsetShift, szRegion + iOffsetShift
34260        );
34261#endif
34262        OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
34263                 osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
34264                 szRegion, pMap ? "ok" : "failed"));
34265      }
34266      if( !pMap ){
34267        pShmNode->lastErrno = osGetLastError();
34268        rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
34269                 "winShmMap3", pDbFd->zPath);
34270        if( hMap ) osCloseHandle(hMap);
34271        goto shmpage_out;
34272      }
34273
34274      pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
34275      pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
34276      pShmNode->nRegion++;
34277    }
34278  }
34279
34280shmpage_out:
34281  if( pShmNode->nRegion>iRegion ){
34282    int iOffset = iRegion*szRegion;
34283    int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
34284    char *p = (char *)pShmNode->aRegion[iRegion].pMap;
34285    *pp = (void *)&p[iOffsetShift];
34286  }else{
34287    *pp = 0;
34288  }
34289  sqlite3_mutex_leave(pShmNode->mutex);
34290  return rc;
34291}
34292
34293#else
34294# define winShmMap     0
34295# define winShmLock    0
34296# define winShmBarrier 0
34297# define winShmUnmap   0
34298#endif /* #ifndef SQLITE_OMIT_WAL */
34299
34300/*
34301** Cleans up the mapped region of the specified file, if any.
34302*/
34303#if SQLITE_MAX_MMAP_SIZE>0
34304static int winUnmapfile(winFile *pFile){
34305  assert( pFile!=0 );
34306  OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
34307           "mmapSize=%lld, mmapSizeActual=%lld, mmapSizeMax=%lld\n",
34308           osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
34309           pFile->mmapSize, pFile->mmapSizeActual, pFile->mmapSizeMax));
34310  if( pFile->pMapRegion ){
34311    if( !osUnmapViewOfFile(pFile->pMapRegion) ){
34312      pFile->lastErrno = osGetLastError();
34313      OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
34314               "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
34315               pFile->pMapRegion));
34316      return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
34317                         "winUnmap1", pFile->zPath);
34318    }
34319    pFile->pMapRegion = 0;
34320    pFile->mmapSize = 0;
34321    pFile->mmapSizeActual = 0;
34322  }
34323  if( pFile->hMap!=NULL ){
34324    if( !osCloseHandle(pFile->hMap) ){
34325      pFile->lastErrno = osGetLastError();
34326      OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
34327               osGetCurrentProcessId(), pFile, pFile->hMap));
34328      return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
34329                         "winUnmap2", pFile->zPath);
34330    }
34331    pFile->hMap = NULL;
34332  }
34333  OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
34334           osGetCurrentProcessId(), pFile));
34335  return SQLITE_OK;
34336}
34337
34338/*
34339** Memory map or remap the file opened by file-descriptor pFd (if the file
34340** is already mapped, the existing mapping is replaced by the new). Or, if
34341** there already exists a mapping for this file, and there are still
34342** outstanding xFetch() references to it, this function is a no-op.
34343**
34344** If parameter nByte is non-negative, then it is the requested size of
34345** the mapping to create. Otherwise, if nByte is less than zero, then the
34346** requested size is the size of the file on disk. The actual size of the
34347** created mapping is either the requested size or the value configured
34348** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
34349**
34350** SQLITE_OK is returned if no error occurs (even if the mapping is not
34351** recreated as a result of outstanding references) or an SQLite error
34352** code otherwise.
34353*/
34354static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
34355  sqlite3_int64 nMap = nByte;
34356  int rc;
34357
34358  assert( nMap>=0 || pFd->nFetchOut==0 );
34359  OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
34360           osGetCurrentProcessId(), pFd, nByte));
34361
34362  if( pFd->nFetchOut>0 ) return SQLITE_OK;
34363
34364  if( nMap<0 ){
34365    rc = winFileSize((sqlite3_file*)pFd, &nMap);
34366    if( rc ){
34367      OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
34368               osGetCurrentProcessId(), pFd));
34369      return SQLITE_IOERR_FSTAT;
34370    }
34371  }
34372  if( nMap>pFd->mmapSizeMax ){
34373    nMap = pFd->mmapSizeMax;
34374  }
34375  nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
34376
34377  if( nMap==0 && pFd->mmapSize>0 ){
34378    winUnmapfile(pFd);
34379  }
34380  if( nMap!=pFd->mmapSize ){
34381    void *pNew = 0;
34382    DWORD protect = PAGE_READONLY;
34383    DWORD flags = FILE_MAP_READ;
34384
34385    winUnmapfile(pFd);
34386    if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
34387      protect = PAGE_READWRITE;
34388      flags |= FILE_MAP_WRITE;
34389    }
34390#if SQLITE_OS_WINRT
34391    pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
34392#elif defined(SQLITE_WIN32_HAS_WIDE)
34393    pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
34394                                (DWORD)((nMap>>32) & 0xffffffff),
34395                                (DWORD)(nMap & 0xffffffff), NULL);
34396#elif defined(SQLITE_WIN32_HAS_ANSI)
34397    pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
34398                                (DWORD)((nMap>>32) & 0xffffffff),
34399                                (DWORD)(nMap & 0xffffffff), NULL);
34400#endif
34401    if( pFd->hMap==NULL ){
34402      pFd->lastErrno = osGetLastError();
34403      rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
34404                       "winMapfile", pFd->zPath);
34405      /* Log the error, but continue normal operation using xRead/xWrite */
34406      OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=SQLITE_IOERR_MMAP\n",
34407               osGetCurrentProcessId(), pFd));
34408      return SQLITE_OK;
34409    }
34410    assert( (nMap % winSysInfo.dwPageSize)==0 );
34411#if SQLITE_OS_WINRT
34412    pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, nMap);
34413#else
34414    assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
34415    pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
34416#endif
34417    if( pNew==NULL ){
34418      osCloseHandle(pFd->hMap);
34419      pFd->hMap = NULL;
34420      pFd->lastErrno = osGetLastError();
34421      winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
34422                  "winMapfile", pFd->zPath);
34423      OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=SQLITE_IOERR_MMAP\n",
34424               osGetCurrentProcessId(), pFd));
34425      return SQLITE_OK;
34426    }
34427    pFd->pMapRegion = pNew;
34428    pFd->mmapSize = nMap;
34429    pFd->mmapSizeActual = nMap;
34430  }
34431
34432  OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
34433           osGetCurrentProcessId(), pFd));
34434  return SQLITE_OK;
34435}
34436#endif /* SQLITE_MAX_MMAP_SIZE>0 */
34437
34438/*
34439** If possible, return a pointer to a mapping of file fd starting at offset
34440** iOff. The mapping must be valid for at least nAmt bytes.
34441**
34442** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
34443** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
34444** Finally, if an error does occur, return an SQLite error code. The final
34445** value of *pp is undefined in this case.
34446**
34447** If this function does return a pointer, the caller must eventually
34448** release the reference by calling winUnfetch().
34449*/
34450static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
34451#if SQLITE_MAX_MMAP_SIZE>0
34452  winFile *pFd = (winFile*)fd;   /* The underlying database file */
34453#endif
34454  *pp = 0;
34455
34456  OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
34457           osGetCurrentProcessId(), fd, iOff, nAmt, pp));
34458
34459#if SQLITE_MAX_MMAP_SIZE>0
34460  if( pFd->mmapSizeMax>0 ){
34461    if( pFd->pMapRegion==0 ){
34462      int rc = winMapfile(pFd, -1);
34463      if( rc!=SQLITE_OK ){
34464        OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
34465                 osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
34466        return rc;
34467      }
34468    }
34469    if( pFd->mmapSize >= iOff+nAmt ){
34470      *pp = &((u8 *)pFd->pMapRegion)[iOff];
34471      pFd->nFetchOut++;
34472    }
34473  }
34474#endif
34475
34476  OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
34477           osGetCurrentProcessId(), fd, pp, *pp));
34478  return SQLITE_OK;
34479}
34480
34481/*
34482** If the third argument is non-NULL, then this function releases a
34483** reference obtained by an earlier call to winFetch(). The second
34484** argument passed to this function must be the same as the corresponding
34485** argument that was passed to the winFetch() invocation.
34486**
34487** Or, if the third argument is NULL, then this function is being called
34488** to inform the VFS layer that, according to POSIX, any existing mapping
34489** may now be invalid and should be unmapped.
34490*/
34491static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
34492#if SQLITE_MAX_MMAP_SIZE>0
34493  winFile *pFd = (winFile*)fd;   /* The underlying database file */
34494
34495  /* If p==0 (unmap the entire file) then there must be no outstanding
34496  ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
34497  ** then there must be at least one outstanding.  */
34498  assert( (p==0)==(pFd->nFetchOut==0) );
34499
34500  /* If p!=0, it must match the iOff value. */
34501  assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
34502
34503  OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
34504           osGetCurrentProcessId(), pFd, iOff, p));
34505
34506  if( p ){
34507    pFd->nFetchOut--;
34508  }else{
34509    /* FIXME:  If Windows truly always prevents truncating or deleting a
34510    ** file while a mapping is held, then the following winUnmapfile() call
34511    ** is unnecessary can can be omitted - potentially improving
34512    ** performance.  */
34513    winUnmapfile(pFd);
34514  }
34515
34516  assert( pFd->nFetchOut>=0 );
34517#endif
34518
34519  OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
34520           osGetCurrentProcessId(), fd));
34521  return SQLITE_OK;
34522}
34523
34524/*
34525** Here ends the implementation of all sqlite3_file methods.
34526**
34527********************** End sqlite3_file Methods *******************************
34528******************************************************************************/
34529
34530/*
34531** This vector defines all the methods that can operate on an
34532** sqlite3_file for win32.
34533*/
34534static const sqlite3_io_methods winIoMethod = {
34535  3,                              /* iVersion */
34536  winClose,                       /* xClose */
34537  winRead,                        /* xRead */
34538  winWrite,                       /* xWrite */
34539  winTruncate,                    /* xTruncate */
34540  winSync,                        /* xSync */
34541  winFileSize,                    /* xFileSize */
34542  winLock,                        /* xLock */
34543  winUnlock,                      /* xUnlock */
34544  winCheckReservedLock,           /* xCheckReservedLock */
34545  winFileControl,                 /* xFileControl */
34546  winSectorSize,                  /* xSectorSize */
34547  winDeviceCharacteristics,       /* xDeviceCharacteristics */
34548  winShmMap,                      /* xShmMap */
34549  winShmLock,                     /* xShmLock */
34550  winShmBarrier,                  /* xShmBarrier */
34551  winShmUnmap,                    /* xShmUnmap */
34552  winFetch,                       /* xFetch */
34553  winUnfetch                      /* xUnfetch */
34554};
34555
34556/****************************************************************************
34557**************************** sqlite3_vfs methods ****************************
34558**
34559** This division contains the implementation of methods on the
34560** sqlite3_vfs object.
34561*/
34562
34563/*
34564** Convert a UTF-8 filename into whatever form the underlying
34565** operating system wants filenames in.  Space to hold the result
34566** is obtained from malloc and must be freed by the calling
34567** function.
34568*/
34569static void *convertUtf8Filename(const char *zFilename){
34570  void *zConverted = 0;
34571  if( isNT() ){
34572    zConverted = utf8ToUnicode(zFilename);
34573  }
34574#ifdef SQLITE_WIN32_HAS_ANSI
34575  else{
34576    zConverted = sqlite3_win32_utf8_to_mbcs(zFilename);
34577  }
34578#endif
34579  /* caller will handle out of memory */
34580  return zConverted;
34581}
34582
34583/*
34584** Create a temporary file name in zBuf.  zBuf must be big enough to
34585** hold at pVfs->mxPathname characters.
34586*/
34587static int getTempname(int nBuf, char *zBuf){
34588  static char zChars[] =
34589    "abcdefghijklmnopqrstuvwxyz"
34590    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
34591    "0123456789";
34592  size_t i, j;
34593  int nTempPath;
34594  char zTempPath[MAX_PATH+2];
34595
34596  /* It's odd to simulate an io-error here, but really this is just
34597  ** using the io-error infrastructure to test that SQLite handles this
34598  ** function failing.
34599  */
34600  SimulateIOError( return SQLITE_IOERR );
34601
34602  memset(zTempPath, 0, MAX_PATH+2);
34603
34604  if( sqlite3_temp_directory ){
34605    sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
34606  }
34607#if !SQLITE_OS_WINRT
34608  else if( isNT() ){
34609    char *zMulti;
34610    WCHAR zWidePath[MAX_PATH];
34611    osGetTempPathW(MAX_PATH-30, zWidePath);
34612    zMulti = unicodeToUtf8(zWidePath);
34613    if( zMulti ){
34614      sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
34615      sqlite3_free(zMulti);
34616    }else{
34617      OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
34618      return SQLITE_IOERR_NOMEM;
34619    }
34620  }
34621#ifdef SQLITE_WIN32_HAS_ANSI
34622  else{
34623    char *zUtf8;
34624    char zMbcsPath[MAX_PATH];
34625    osGetTempPathA(MAX_PATH-30, zMbcsPath);
34626    zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
34627    if( zUtf8 ){
34628      sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
34629      sqlite3_free(zUtf8);
34630    }else{
34631      OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
34632      return SQLITE_IOERR_NOMEM;
34633    }
34634  }
34635#endif
34636#endif
34637
34638  /* Check that the output buffer is large enough for the temporary file
34639  ** name. If it is not, return SQLITE_ERROR.
34640  */
34641  nTempPath = sqlite3Strlen30(zTempPath);
34642
34643  if( (nTempPath + sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX) + 18) >= nBuf ){
34644    OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
34645    return SQLITE_ERROR;
34646  }
34647
34648  for(i=nTempPath; i>0 && zTempPath[i-1]=='\\'; i--){}
34649  zTempPath[i] = 0;
34650
34651  sqlite3_snprintf(nBuf-18, zBuf, (nTempPath > 0) ?
34652                       "%s\\"SQLITE_TEMP_FILE_PREFIX : SQLITE_TEMP_FILE_PREFIX,
34653                   zTempPath);
34654  j = sqlite3Strlen30(zBuf);
34655  sqlite3_randomness(15, &zBuf[j]);
34656  for(i=0; i<15; i++, j++){
34657    zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
34658  }
34659  zBuf[j] = 0;
34660  zBuf[j+1] = 0;
34661
34662  OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
34663  return SQLITE_OK;
34664}
34665
34666/*
34667** Return TRUE if the named file is really a directory.  Return false if
34668** it is something other than a directory, or if there is any kind of memory
34669** allocation failure.
34670*/
34671static int winIsDir(const void *zConverted){
34672  DWORD attr;
34673  int rc = 0;
34674  DWORD lastErrno;
34675
34676  if( isNT() ){
34677    int cnt = 0;
34678    WIN32_FILE_ATTRIBUTE_DATA sAttrData;
34679    memset(&sAttrData, 0, sizeof(sAttrData));
34680    while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
34681                             GetFileExInfoStandard,
34682                             &sAttrData)) && retryIoerr(&cnt, &lastErrno) ){}
34683    if( !rc ){
34684      return 0; /* Invalid name? */
34685    }
34686    attr = sAttrData.dwFileAttributes;
34687#if SQLITE_OS_WINCE==0
34688  }else{
34689    attr = osGetFileAttributesA((char*)zConverted);
34690#endif
34691  }
34692  return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
34693}
34694
34695/*
34696** Open a file.
34697*/
34698static int winOpen(
34699  sqlite3_vfs *pVfs,        /* Not used */
34700  const char *zName,        /* Name of the file (UTF-8) */
34701  sqlite3_file *id,         /* Write the SQLite file handle here */
34702  int flags,                /* Open mode flags */
34703  int *pOutFlags            /* Status return flags */
34704){
34705  HANDLE h;
34706  DWORD lastErrno;
34707  DWORD dwDesiredAccess;
34708  DWORD dwShareMode;
34709  DWORD dwCreationDisposition;
34710  DWORD dwFlagsAndAttributes = 0;
34711#if SQLITE_OS_WINCE
34712  int isTemp = 0;
34713#endif
34714  winFile *pFile = (winFile*)id;
34715  void *zConverted;              /* Filename in OS encoding */
34716  const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
34717  int cnt = 0;
34718
34719  /* If argument zPath is a NULL pointer, this function is required to open
34720  ** a temporary file. Use this buffer to store the file name in.
34721  */
34722  char zTmpname[MAX_PATH+2];     /* Buffer used to create temp filename */
34723
34724  int rc = SQLITE_OK;            /* Function Return Code */
34725#if !defined(NDEBUG) || SQLITE_OS_WINCE
34726  int eType = flags&0xFFFFFF00;  /* Type of file to open */
34727#endif
34728
34729  int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
34730  int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
34731  int isCreate     = (flags & SQLITE_OPEN_CREATE);
34732  int isReadonly   = (flags & SQLITE_OPEN_READONLY);
34733  int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
34734
34735#ifndef NDEBUG
34736  int isOpenJournal = (isCreate && (
34737        eType==SQLITE_OPEN_MASTER_JOURNAL
34738     || eType==SQLITE_OPEN_MAIN_JOURNAL
34739     || eType==SQLITE_OPEN_WAL
34740  ));
34741#endif
34742
34743  OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
34744           zUtf8Name, id, flags, pOutFlags));
34745
34746  /* Check the following statements are true:
34747  **
34748  **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
34749  **   (b) if CREATE is set, then READWRITE must also be set, and
34750  **   (c) if EXCLUSIVE is set, then CREATE must also be set.
34751  **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
34752  */
34753  assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
34754  assert(isCreate==0 || isReadWrite);
34755  assert(isExclusive==0 || isCreate);
34756  assert(isDelete==0 || isCreate);
34757
34758  /* The main DB, main journal, WAL file and master journal are never
34759  ** automatically deleted. Nor are they ever temporary files.  */
34760  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
34761  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
34762  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
34763  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
34764
34765  /* Assert that the upper layer has set one of the "file-type" flags. */
34766  assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
34767       || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
34768       || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
34769       || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
34770  );
34771
34772  assert( pFile!=0 );
34773  memset(pFile, 0, sizeof(winFile));
34774  pFile->h = INVALID_HANDLE_VALUE;
34775
34776#if SQLITE_OS_WINRT
34777  if( !sqlite3_temp_directory ){
34778    sqlite3_log(SQLITE_ERROR,
34779        "sqlite3_temp_directory variable should be set for WinRT");
34780  }
34781#endif
34782
34783  /* If the second argument to this function is NULL, generate a
34784  ** temporary file name to use
34785  */
34786  if( !zUtf8Name ){
34787    assert(isDelete && !isOpenJournal);
34788    memset(zTmpname, 0, MAX_PATH+2);
34789    rc = getTempname(MAX_PATH+2, zTmpname);
34790    if( rc!=SQLITE_OK ){
34791      OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
34792      return rc;
34793    }
34794    zUtf8Name = zTmpname;
34795  }
34796
34797  /* Database filenames are double-zero terminated if they are not
34798  ** URIs with parameters.  Hence, they can always be passed into
34799  ** sqlite3_uri_parameter().
34800  */
34801  assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
34802        zUtf8Name[strlen(zUtf8Name)+1]==0 );
34803
34804  /* Convert the filename to the system encoding. */
34805  zConverted = convertUtf8Filename(zUtf8Name);
34806  if( zConverted==0 ){
34807    OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
34808    return SQLITE_IOERR_NOMEM;
34809  }
34810
34811  if( winIsDir(zConverted) ){
34812    sqlite3_free(zConverted);
34813    OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
34814    return SQLITE_CANTOPEN_ISDIR;
34815  }
34816
34817  if( isReadWrite ){
34818    dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
34819  }else{
34820    dwDesiredAccess = GENERIC_READ;
34821  }
34822
34823  /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
34824  ** created. SQLite doesn't use it to indicate "exclusive access"
34825  ** as it is usually understood.
34826  */
34827  if( isExclusive ){
34828    /* Creates a new file, only if it does not already exist. */
34829    /* If the file exists, it fails. */
34830    dwCreationDisposition = CREATE_NEW;
34831  }else if( isCreate ){
34832    /* Open existing file, or create if it doesn't exist */
34833    dwCreationDisposition = OPEN_ALWAYS;
34834  }else{
34835    /* Opens a file, only if it exists. */
34836    dwCreationDisposition = OPEN_EXISTING;
34837  }
34838
34839  dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
34840
34841  if( isDelete ){
34842#if SQLITE_OS_WINCE
34843    dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
34844    isTemp = 1;
34845#else
34846    dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
34847                               | FILE_ATTRIBUTE_HIDDEN
34848                               | FILE_FLAG_DELETE_ON_CLOSE;
34849#endif
34850  }else{
34851    dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
34852  }
34853  /* Reports from the internet are that performance is always
34854  ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
34855#if SQLITE_OS_WINCE
34856  dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
34857#endif
34858
34859  if( isNT() ){
34860#if SQLITE_OS_WINRT
34861    CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
34862    extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
34863    extendedParameters.dwFileAttributes =
34864            dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
34865    extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
34866    extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
34867    extendedParameters.lpSecurityAttributes = NULL;
34868    extendedParameters.hTemplateFile = NULL;
34869    while( (h = osCreateFile2((LPCWSTR)zConverted,
34870                              dwDesiredAccess,
34871                              dwShareMode,
34872                              dwCreationDisposition,
34873                              &extendedParameters))==INVALID_HANDLE_VALUE &&
34874                              retryIoerr(&cnt, &lastErrno) ){
34875               /* Noop */
34876    }
34877#else
34878    while( (h = osCreateFileW((LPCWSTR)zConverted,
34879                              dwDesiredAccess,
34880                              dwShareMode, NULL,
34881                              dwCreationDisposition,
34882                              dwFlagsAndAttributes,
34883                              NULL))==INVALID_HANDLE_VALUE &&
34884                              retryIoerr(&cnt, &lastErrno) ){
34885               /* Noop */
34886    }
34887#endif
34888  }
34889#ifdef SQLITE_WIN32_HAS_ANSI
34890  else{
34891    while( (h = osCreateFileA((LPCSTR)zConverted,
34892                              dwDesiredAccess,
34893                              dwShareMode, NULL,
34894                              dwCreationDisposition,
34895                              dwFlagsAndAttributes,
34896                              NULL))==INVALID_HANDLE_VALUE &&
34897                              retryIoerr(&cnt, &lastErrno) ){
34898               /* Noop */
34899    }
34900  }
34901#endif
34902  logIoerr(cnt);
34903
34904  OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name,
34905           dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
34906
34907  if( h==INVALID_HANDLE_VALUE ){
34908    pFile->lastErrno = lastErrno;
34909    winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
34910    sqlite3_free(zConverted);
34911    if( isReadWrite && !isExclusive ){
34912      return winOpen(pVfs, zName, id,
34913         ((flags|SQLITE_OPEN_READONLY) &
34914                     ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
34915         pOutFlags);
34916    }else{
34917      return SQLITE_CANTOPEN_BKPT;
34918    }
34919  }
34920
34921  if( pOutFlags ){
34922    if( isReadWrite ){
34923      *pOutFlags = SQLITE_OPEN_READWRITE;
34924    }else{
34925      *pOutFlags = SQLITE_OPEN_READONLY;
34926    }
34927  }
34928
34929  OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
34930           "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?
34931           *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
34932
34933#if SQLITE_OS_WINCE
34934  if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
34935       && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
34936  ){
34937    osCloseHandle(h);
34938    sqlite3_free(zConverted);
34939    OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
34940    return rc;
34941  }
34942  if( isTemp ){
34943    pFile->zDeleteOnClose = zConverted;
34944  }else
34945#endif
34946  {
34947    sqlite3_free(zConverted);
34948  }
34949
34950  pFile->pMethod = &winIoMethod;
34951  pFile->pVfs = pVfs;
34952  pFile->h = h;
34953  if( isReadonly ){
34954    pFile->ctrlFlags |= WINFILE_RDONLY;
34955  }
34956  if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
34957    pFile->ctrlFlags |= WINFILE_PSOW;
34958  }
34959  pFile->lastErrno = NO_ERROR;
34960  pFile->zPath = zName;
34961#if SQLITE_MAX_MMAP_SIZE>0
34962  pFile->hMap = NULL;
34963  pFile->pMapRegion = 0;
34964  pFile->mmapSize = 0;
34965  pFile->mmapSizeActual = 0;
34966  pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
34967#endif
34968
34969  OpenCounter(+1);
34970  return rc;
34971}
34972
34973/*
34974** Delete the named file.
34975**
34976** Note that Windows does not allow a file to be deleted if some other
34977** process has it open.  Sometimes a virus scanner or indexing program
34978** will open a journal file shortly after it is created in order to do
34979** whatever it does.  While this other process is holding the
34980** file open, we will be unable to delete it.  To work around this
34981** problem, we delay 100 milliseconds and try to delete again.  Up
34982** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
34983** up and returning an error.
34984*/
34985static int winDelete(
34986  sqlite3_vfs *pVfs,          /* Not used on win32 */
34987  const char *zFilename,      /* Name of file to delete */
34988  int syncDir                 /* Not used on win32 */
34989){
34990  int cnt = 0;
34991  int rc;
34992  DWORD attr;
34993  DWORD lastErrno;
34994  void *zConverted;
34995  UNUSED_PARAMETER(pVfs);
34996  UNUSED_PARAMETER(syncDir);
34997
34998  SimulateIOError(return SQLITE_IOERR_DELETE);
34999  OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
35000
35001  zConverted = convertUtf8Filename(zFilename);
35002  if( zConverted==0 ){
35003    return SQLITE_IOERR_NOMEM;
35004  }
35005  if( isNT() ){
35006    do {
35007#if SQLITE_OS_WINRT
35008      WIN32_FILE_ATTRIBUTE_DATA sAttrData;
35009      memset(&sAttrData, 0, sizeof(sAttrData));
35010      if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
35011                                  &sAttrData) ){
35012        attr = sAttrData.dwFileAttributes;
35013      }else{
35014        lastErrno = osGetLastError();
35015        if( lastErrno==ERROR_FILE_NOT_FOUND
35016         || lastErrno==ERROR_PATH_NOT_FOUND ){
35017          rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
35018        }else{
35019          rc = SQLITE_ERROR;
35020        }
35021        break;
35022      }
35023#else
35024      attr = osGetFileAttributesW(zConverted);
35025#endif
35026      if ( attr==INVALID_FILE_ATTRIBUTES ){
35027        lastErrno = osGetLastError();
35028        if( lastErrno==ERROR_FILE_NOT_FOUND
35029         || lastErrno==ERROR_PATH_NOT_FOUND ){
35030          rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
35031        }else{
35032          rc = SQLITE_ERROR;
35033        }
35034        break;
35035      }
35036      if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
35037        rc = SQLITE_ERROR; /* Files only. */
35038        break;
35039      }
35040      if ( osDeleteFileW(zConverted) ){
35041        rc = SQLITE_OK; /* Deleted OK. */
35042        break;
35043      }
35044      if ( !retryIoerr(&cnt, &lastErrno) ){
35045        rc = SQLITE_ERROR; /* No more retries. */
35046        break;
35047      }
35048    } while(1);
35049  }
35050#ifdef SQLITE_WIN32_HAS_ANSI
35051  else{
35052    do {
35053      attr = osGetFileAttributesA(zConverted);
35054      if ( attr==INVALID_FILE_ATTRIBUTES ){
35055        lastErrno = osGetLastError();
35056        if( lastErrno==ERROR_FILE_NOT_FOUND
35057         || lastErrno==ERROR_PATH_NOT_FOUND ){
35058          rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
35059        }else{
35060          rc = SQLITE_ERROR;
35061        }
35062        break;
35063      }
35064      if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
35065        rc = SQLITE_ERROR; /* Files only. */
35066        break;
35067      }
35068      if ( osDeleteFileA(zConverted) ){
35069        rc = SQLITE_OK; /* Deleted OK. */
35070        break;
35071      }
35072      if ( !retryIoerr(&cnt, &lastErrno) ){
35073        rc = SQLITE_ERROR; /* No more retries. */
35074        break;
35075      }
35076    } while(1);
35077  }
35078#endif
35079  if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
35080    rc = winLogError(SQLITE_IOERR_DELETE, lastErrno,
35081             "winDelete", zFilename);
35082  }else{
35083    logIoerr(cnt);
35084  }
35085  sqlite3_free(zConverted);
35086  OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc)));
35087  return rc;
35088}
35089
35090/*
35091** Check the existence and status of a file.
35092*/
35093static int winAccess(
35094  sqlite3_vfs *pVfs,         /* Not used on win32 */
35095  const char *zFilename,     /* Name of file to check */
35096  int flags,                 /* Type of test to make on this file */
35097  int *pResOut               /* OUT: Result */
35098){
35099  DWORD attr;
35100  int rc = 0;
35101  DWORD lastErrno;
35102  void *zConverted;
35103  UNUSED_PARAMETER(pVfs);
35104
35105  SimulateIOError( return SQLITE_IOERR_ACCESS; );
35106  OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
35107           zFilename, flags, pResOut));
35108
35109  zConverted = convertUtf8Filename(zFilename);
35110  if( zConverted==0 ){
35111    OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
35112    return SQLITE_IOERR_NOMEM;
35113  }
35114  if( isNT() ){
35115    int cnt = 0;
35116    WIN32_FILE_ATTRIBUTE_DATA sAttrData;
35117    memset(&sAttrData, 0, sizeof(sAttrData));
35118    while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
35119                             GetFileExInfoStandard,
35120                             &sAttrData)) && retryIoerr(&cnt, &lastErrno) ){}
35121    if( rc ){
35122      /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
35123      ** as if it does not exist.
35124      */
35125      if(    flags==SQLITE_ACCESS_EXISTS
35126          && sAttrData.nFileSizeHigh==0
35127          && sAttrData.nFileSizeLow==0 ){
35128        attr = INVALID_FILE_ATTRIBUTES;
35129      }else{
35130        attr = sAttrData.dwFileAttributes;
35131      }
35132    }else{
35133      logIoerr(cnt);
35134      if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
35135        winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess", zFilename);
35136        sqlite3_free(zConverted);
35137        return SQLITE_IOERR_ACCESS;
35138      }else{
35139        attr = INVALID_FILE_ATTRIBUTES;
35140      }
35141    }
35142  }
35143#ifdef SQLITE_WIN32_HAS_ANSI
35144  else{
35145    attr = osGetFileAttributesA((char*)zConverted);
35146  }
35147#endif
35148  sqlite3_free(zConverted);
35149  switch( flags ){
35150    case SQLITE_ACCESS_READ:
35151    case SQLITE_ACCESS_EXISTS:
35152      rc = attr!=INVALID_FILE_ATTRIBUTES;
35153      break;
35154    case SQLITE_ACCESS_READWRITE:
35155      rc = attr!=INVALID_FILE_ATTRIBUTES &&
35156             (attr & FILE_ATTRIBUTE_READONLY)==0;
35157      break;
35158    default:
35159      assert(!"Invalid flags argument");
35160  }
35161  *pResOut = rc;
35162  OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
35163           zFilename, pResOut, *pResOut));
35164  return SQLITE_OK;
35165}
35166
35167
35168/*
35169** Returns non-zero if the specified path name should be used verbatim.  If
35170** non-zero is returned from this function, the calling function must simply
35171** use the provided path name verbatim -OR- resolve it into a full path name
35172** using the GetFullPathName Win32 API function (if available).
35173*/
35174static BOOL winIsVerbatimPathname(
35175  const char *zPathname
35176){
35177  /*
35178  ** If the path name starts with a forward slash or a backslash, it is either
35179  ** a legal UNC name, a volume relative path, or an absolute path name in the
35180  ** "Unix" format on Windows.  There is no easy way to differentiate between
35181  ** the final two cases; therefore, we return the safer return value of TRUE
35182  ** so that callers of this function will simply use it verbatim.
35183  */
35184  if ( zPathname[0]=='/' || zPathname[0]=='\\' ){
35185    return TRUE;
35186  }
35187
35188  /*
35189  ** If the path name starts with a letter and a colon it is either a volume
35190  ** relative path or an absolute path.  Callers of this function must not
35191  ** attempt to treat it as a relative path name (i.e. they should simply use
35192  ** it verbatim).
35193  */
35194  if ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' ){
35195    return TRUE;
35196  }
35197
35198  /*
35199  ** If we get to this point, the path name should almost certainly be a purely
35200  ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
35201  */
35202  return FALSE;
35203}
35204
35205/*
35206** Turn a relative pathname into a full pathname.  Write the full
35207** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
35208** bytes in size.
35209*/
35210static int winFullPathname(
35211  sqlite3_vfs *pVfs,            /* Pointer to vfs object */
35212  const char *zRelative,        /* Possibly relative input path */
35213  int nFull,                    /* Size of output buffer in bytes */
35214  char *zFull                   /* Output buffer */
35215){
35216
35217#if defined(__CYGWIN__)
35218  SimulateIOError( return SQLITE_ERROR );
35219  UNUSED_PARAMETER(nFull);
35220  assert( pVfs->mxPathname>=MAX_PATH );
35221  assert( nFull>=pVfs->mxPathname );
35222  if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
35223    /*
35224    ** NOTE: We are dealing with a relative path name and the data
35225    **       directory has been set.  Therefore, use it as the basis
35226    **       for converting the relative path name to an absolute
35227    **       one by prepending the data directory and a slash.
35228    */
35229    char zOut[MAX_PATH+1];
35230    memset(zOut, 0, MAX_PATH+1);
35231    cygwin_conv_path(CCP_POSIX_TO_WIN_A|CCP_RELATIVE, zRelative, zOut,
35232                     MAX_PATH+1);
35233    sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s\\%s",
35234                     sqlite3_data_directory, zOut);
35235  }else{
35236    cygwin_conv_path(CCP_POSIX_TO_WIN_A, zRelative, zFull, nFull);
35237  }
35238  return SQLITE_OK;
35239#endif
35240
35241#if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
35242  SimulateIOError( return SQLITE_ERROR );
35243  /* WinCE has no concept of a relative pathname, or so I am told. */
35244  /* WinRT has no way to convert a relative path to an absolute one. */
35245  if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
35246    /*
35247    ** NOTE: We are dealing with a relative path name and the data
35248    **       directory has been set.  Therefore, use it as the basis
35249    **       for converting the relative path name to an absolute
35250    **       one by prepending the data directory and a backslash.
35251    */
35252    sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s\\%s",
35253                     sqlite3_data_directory, zRelative);
35254  }else{
35255    sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
35256  }
35257  return SQLITE_OK;
35258#endif
35259
35260#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
35261  DWORD nByte;
35262  void *zConverted;
35263  char *zOut;
35264
35265  /* If this path name begins with "/X:", where "X" is any alphabetic
35266  ** character, discard the initial "/" from the pathname.
35267  */
35268  if( zRelative[0]=='/' && sqlite3Isalpha(zRelative[1]) && zRelative[2]==':' ){
35269    zRelative++;
35270  }
35271
35272  /* It's odd to simulate an io-error here, but really this is just
35273  ** using the io-error infrastructure to test that SQLite handles this
35274  ** function failing. This function could fail if, for example, the
35275  ** current working directory has been unlinked.
35276  */
35277  SimulateIOError( return SQLITE_ERROR );
35278  if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
35279    /*
35280    ** NOTE: We are dealing with a relative path name and the data
35281    **       directory has been set.  Therefore, use it as the basis
35282    **       for converting the relative path name to an absolute
35283    **       one by prepending the data directory and a backslash.
35284    */
35285    sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s\\%s",
35286                     sqlite3_data_directory, zRelative);
35287    return SQLITE_OK;
35288  }
35289  zConverted = convertUtf8Filename(zRelative);
35290  if( zConverted==0 ){
35291    return SQLITE_IOERR_NOMEM;
35292  }
35293  if( isNT() ){
35294    LPWSTR zTemp;
35295    nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
35296    if( nByte==0 ){
35297      winLogError(SQLITE_ERROR, osGetLastError(),
35298                  "GetFullPathNameW1", zConverted);
35299      sqlite3_free(zConverted);
35300      return SQLITE_CANTOPEN_FULLPATH;
35301    }
35302    nByte += 3;
35303    zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
35304    if( zTemp==0 ){
35305      sqlite3_free(zConverted);
35306      return SQLITE_IOERR_NOMEM;
35307    }
35308    nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
35309    if( nByte==0 ){
35310      winLogError(SQLITE_ERROR, osGetLastError(),
35311                  "GetFullPathNameW2", zConverted);
35312      sqlite3_free(zConverted);
35313      sqlite3_free(zTemp);
35314      return SQLITE_CANTOPEN_FULLPATH;
35315    }
35316    sqlite3_free(zConverted);
35317    zOut = unicodeToUtf8(zTemp);
35318    sqlite3_free(zTemp);
35319  }
35320#ifdef SQLITE_WIN32_HAS_ANSI
35321  else{
35322    char *zTemp;
35323    nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
35324    if( nByte==0 ){
35325      winLogError(SQLITE_ERROR, osGetLastError(),
35326                  "GetFullPathNameA1", zConverted);
35327      sqlite3_free(zConverted);
35328      return SQLITE_CANTOPEN_FULLPATH;
35329    }
35330    nByte += 3;
35331    zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
35332    if( zTemp==0 ){
35333      sqlite3_free(zConverted);
35334      return SQLITE_IOERR_NOMEM;
35335    }
35336    nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
35337    if( nByte==0 ){
35338      winLogError(SQLITE_ERROR, osGetLastError(),
35339                  "GetFullPathNameA2", zConverted);
35340      sqlite3_free(zConverted);
35341      sqlite3_free(zTemp);
35342      return SQLITE_CANTOPEN_FULLPATH;
35343    }
35344    sqlite3_free(zConverted);
35345    zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
35346    sqlite3_free(zTemp);
35347  }
35348#endif
35349  if( zOut ){
35350    sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
35351    sqlite3_free(zOut);
35352    return SQLITE_OK;
35353  }else{
35354    return SQLITE_IOERR_NOMEM;
35355  }
35356#endif
35357}
35358
35359#ifndef SQLITE_OMIT_LOAD_EXTENSION
35360/*
35361** Interfaces for opening a shared library, finding entry points
35362** within the shared library, and closing the shared library.
35363*/
35364/*
35365** Interfaces for opening a shared library, finding entry points
35366** within the shared library, and closing the shared library.
35367*/
35368static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
35369  HANDLE h;
35370  void *zConverted = convertUtf8Filename(zFilename);
35371  UNUSED_PARAMETER(pVfs);
35372  if( zConverted==0 ){
35373    return 0;
35374  }
35375  if( isNT() ){
35376#if SQLITE_OS_WINRT
35377    h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
35378#else
35379    h = osLoadLibraryW((LPCWSTR)zConverted);
35380#endif
35381  }
35382#ifdef SQLITE_WIN32_HAS_ANSI
35383  else{
35384    h = osLoadLibraryA((char*)zConverted);
35385  }
35386#endif
35387  sqlite3_free(zConverted);
35388  return (void*)h;
35389}
35390static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
35391  UNUSED_PARAMETER(pVfs);
35392  getLastErrorMsg(osGetLastError(), nBuf, zBufOut);
35393}
35394static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
35395  UNUSED_PARAMETER(pVfs);
35396  return (void(*)(void))osGetProcAddressA((HANDLE)pH, zSym);
35397}
35398static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
35399  UNUSED_PARAMETER(pVfs);
35400  osFreeLibrary((HANDLE)pHandle);
35401}
35402#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
35403  #define winDlOpen  0
35404  #define winDlError 0
35405  #define winDlSym   0
35406  #define winDlClose 0
35407#endif
35408
35409
35410/*
35411** Write up to nBuf bytes of randomness into zBuf.
35412*/
35413static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
35414  int n = 0;
35415  UNUSED_PARAMETER(pVfs);
35416#if defined(SQLITE_TEST)
35417  n = nBuf;
35418  memset(zBuf, 0, nBuf);
35419#else
35420  if( sizeof(SYSTEMTIME)<=nBuf-n ){
35421    SYSTEMTIME x;
35422    osGetSystemTime(&x);
35423    memcpy(&zBuf[n], &x, sizeof(x));
35424    n += sizeof(x);
35425  }
35426  if( sizeof(DWORD)<=nBuf-n ){
35427    DWORD pid = osGetCurrentProcessId();
35428    memcpy(&zBuf[n], &pid, sizeof(pid));
35429    n += sizeof(pid);
35430  }
35431#if SQLITE_OS_WINRT
35432  if( sizeof(ULONGLONG)<=nBuf-n ){
35433    ULONGLONG cnt = osGetTickCount64();
35434    memcpy(&zBuf[n], &cnt, sizeof(cnt));
35435    n += sizeof(cnt);
35436  }
35437#else
35438  if( sizeof(DWORD)<=nBuf-n ){
35439    DWORD cnt = osGetTickCount();
35440    memcpy(&zBuf[n], &cnt, sizeof(cnt));
35441    n += sizeof(cnt);
35442  }
35443#endif
35444  if( sizeof(LARGE_INTEGER)<=nBuf-n ){
35445    LARGE_INTEGER i;
35446    osQueryPerformanceCounter(&i);
35447    memcpy(&zBuf[n], &i, sizeof(i));
35448    n += sizeof(i);
35449  }
35450#endif
35451  return n;
35452}
35453
35454
35455/*
35456** Sleep for a little while.  Return the amount of time slept.
35457*/
35458static int winSleep(sqlite3_vfs *pVfs, int microsec){
35459  sqlite3_win32_sleep((microsec+999)/1000);
35460  UNUSED_PARAMETER(pVfs);
35461  return ((microsec+999)/1000)*1000;
35462}
35463
35464/*
35465** The following variable, if set to a non-zero value, is interpreted as
35466** the number of seconds since 1970 and is used to set the result of
35467** sqlite3OsCurrentTime() during testing.
35468*/
35469#ifdef SQLITE_TEST
35470SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
35471#endif
35472
35473/*
35474** Find the current time (in Universal Coordinated Time).  Write into *piNow
35475** the current time and date as a Julian Day number times 86_400_000.  In
35476** other words, write into *piNow the number of milliseconds since the Julian
35477** epoch of noon in Greenwich on November 24, 4714 B.C according to the
35478** proleptic Gregorian calendar.
35479**
35480** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date
35481** cannot be found.
35482*/
35483static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
35484  /* FILETIME structure is a 64-bit value representing the number of
35485     100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
35486  */
35487  FILETIME ft;
35488  static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
35489#ifdef SQLITE_TEST
35490  static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
35491#endif
35492  /* 2^32 - to avoid use of LL and warnings in gcc */
35493  static const sqlite3_int64 max32BitValue =
35494      (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
35495      (sqlite3_int64)294967296;
35496
35497#if SQLITE_OS_WINCE
35498  SYSTEMTIME time;
35499  osGetSystemTime(&time);
35500  /* if SystemTimeToFileTime() fails, it returns zero. */
35501  if (!osSystemTimeToFileTime(&time,&ft)){
35502    return SQLITE_ERROR;
35503  }
35504#else
35505  osGetSystemTimeAsFileTime( &ft );
35506#endif
35507
35508  *piNow = winFiletimeEpoch +
35509            ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
35510               (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
35511
35512#ifdef SQLITE_TEST
35513  if( sqlite3_current_time ){
35514    *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
35515  }
35516#endif
35517  UNUSED_PARAMETER(pVfs);
35518  return SQLITE_OK;
35519}
35520
35521/*
35522** Find the current time (in Universal Coordinated Time).  Write the
35523** current time and date as a Julian Day number into *prNow and
35524** return 0.  Return 1 if the time and date cannot be found.
35525*/
35526static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
35527  int rc;
35528  sqlite3_int64 i;
35529  rc = winCurrentTimeInt64(pVfs, &i);
35530  if( !rc ){
35531    *prNow = i/86400000.0;
35532  }
35533  return rc;
35534}
35535
35536/*
35537** The idea is that this function works like a combination of
35538** GetLastError() and FormatMessage() on Windows (or errno and
35539** strerror_r() on Unix). After an error is returned by an OS
35540** function, SQLite calls this function with zBuf pointing to
35541** a buffer of nBuf bytes. The OS layer should populate the
35542** buffer with a nul-terminated UTF-8 encoded error message
35543** describing the last IO error to have occurred within the calling
35544** thread.
35545**
35546** If the error message is too large for the supplied buffer,
35547** it should be truncated. The return value of xGetLastError
35548** is zero if the error message fits in the buffer, or non-zero
35549** otherwise (if the message was truncated). If non-zero is returned,
35550** then it is not necessary to include the nul-terminator character
35551** in the output buffer.
35552**
35553** Not supplying an error message will have no adverse effect
35554** on SQLite. It is fine to have an implementation that never
35555** returns an error message:
35556**
35557**   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
35558**     assert(zBuf[0]=='\0');
35559**     return 0;
35560**   }
35561**
35562** However if an error message is supplied, it will be incorporated
35563** by sqlite into the error message available to the user using
35564** sqlite3_errmsg(), possibly making IO errors easier to debug.
35565*/
35566static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
35567  UNUSED_PARAMETER(pVfs);
35568  return getLastErrorMsg(osGetLastError(), nBuf, zBuf);
35569}
35570
35571/*
35572** Initialize and deinitialize the operating system interface.
35573*/
35574SQLITE_API int sqlite3_os_init(void){
35575  static sqlite3_vfs winVfs = {
35576    3,                   /* iVersion */
35577    sizeof(winFile),     /* szOsFile */
35578    MAX_PATH,            /* mxPathname */
35579    0,                   /* pNext */
35580    "win32",             /* zName */
35581    0,                   /* pAppData */
35582    winOpen,             /* xOpen */
35583    winDelete,           /* xDelete */
35584    winAccess,           /* xAccess */
35585    winFullPathname,     /* xFullPathname */
35586    winDlOpen,           /* xDlOpen */
35587    winDlError,          /* xDlError */
35588    winDlSym,            /* xDlSym */
35589    winDlClose,          /* xDlClose */
35590    winRandomness,       /* xRandomness */
35591    winSleep,            /* xSleep */
35592    winCurrentTime,      /* xCurrentTime */
35593    winGetLastError,     /* xGetLastError */
35594    winCurrentTimeInt64, /* xCurrentTimeInt64 */
35595    winSetSystemCall,    /* xSetSystemCall */
35596    winGetSystemCall,    /* xGetSystemCall */
35597    winNextSystemCall,   /* xNextSystemCall */
35598  };
35599
35600  /* Double-check that the aSyscall[] array has been constructed
35601  ** correctly.  See ticket [bb3a86e890c8e96ab] */
35602  assert( ArraySize(aSyscall)==74 );
35603
35604  /* get memory map allocation granularity */
35605  memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
35606#if SQLITE_OS_WINRT
35607  osGetNativeSystemInfo(&winSysInfo);
35608#else
35609  osGetSystemInfo(&winSysInfo);
35610#endif
35611  assert( winSysInfo.dwAllocationGranularity>0 );
35612  assert( winSysInfo.dwPageSize>0 );
35613
35614  sqlite3_vfs_register(&winVfs, 1);
35615  return SQLITE_OK;
35616}
35617
35618SQLITE_API int sqlite3_os_end(void){
35619#if SQLITE_OS_WINRT
35620  if( sleepObj!=NULL ){
35621    osCloseHandle(sleepObj);
35622    sleepObj = NULL;
35623  }
35624#endif
35625  return SQLITE_OK;
35626}
35627
35628#endif /* SQLITE_OS_WIN */
35629
35630/************** End of os_win.c **********************************************/
35631/************** Begin file bitvec.c ******************************************/
35632/*
35633** 2008 February 16
35634**
35635** The author disclaims copyright to this source code.  In place of
35636** a legal notice, here is a blessing:
35637**
35638**    May you do good and not evil.
35639**    May you find forgiveness for yourself and forgive others.
35640**    May you share freely, never taking more than you give.
35641**
35642*************************************************************************
35643** This file implements an object that represents a fixed-length
35644** bitmap.  Bits are numbered starting with 1.
35645**
35646** A bitmap is used to record which pages of a database file have been
35647** journalled during a transaction, or which pages have the "dont-write"
35648** property.  Usually only a few pages are meet either condition.
35649** So the bitmap is usually sparse and has low cardinality.
35650** But sometimes (for example when during a DROP of a large table) most
35651** or all of the pages in a database can get journalled.  In those cases,
35652** the bitmap becomes dense with high cardinality.  The algorithm needs
35653** to handle both cases well.
35654**
35655** The size of the bitmap is fixed when the object is created.
35656**
35657** All bits are clear when the bitmap is created.  Individual bits
35658** may be set or cleared one at a time.
35659**
35660** Test operations are about 100 times more common that set operations.
35661** Clear operations are exceedingly rare.  There are usually between
35662** 5 and 500 set operations per Bitvec object, though the number of sets can
35663** sometimes grow into tens of thousands or larger.  The size of the
35664** Bitvec object is the number of pages in the database file at the
35665** start of a transaction, and is thus usually less than a few thousand,
35666** but can be as large as 2 billion for a really big database.
35667*/
35668
35669/* Size of the Bitvec structure in bytes. */
35670#define BITVEC_SZ        512
35671
35672/* Round the union size down to the nearest pointer boundary, since that's how
35673** it will be aligned within the Bitvec struct. */
35674#define BITVEC_USIZE     (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
35675
35676/* Type of the array "element" for the bitmap representation.
35677** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
35678** Setting this to the "natural word" size of your CPU may improve
35679** performance. */
35680#define BITVEC_TELEM     u8
35681/* Size, in bits, of the bitmap element. */
35682#define BITVEC_SZELEM    8
35683/* Number of elements in a bitmap array. */
35684#define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
35685/* Number of bits in the bitmap array. */
35686#define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)
35687
35688/* Number of u32 values in hash table. */
35689#define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
35690/* Maximum number of entries in hash table before
35691** sub-dividing and re-hashing. */
35692#define BITVEC_MXHASH    (BITVEC_NINT/2)
35693/* Hashing function for the aHash representation.
35694** Empirical testing showed that the *37 multiplier
35695** (an arbitrary prime)in the hash function provided
35696** no fewer collisions than the no-op *1. */
35697#define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
35698
35699#define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
35700
35701
35702/*
35703** A bitmap is an instance of the following structure.
35704**
35705** This bitmap records the existence of zero or more bits
35706** with values between 1 and iSize, inclusive.
35707**
35708** There are three possible representations of the bitmap.
35709** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
35710** bitmap.  The least significant bit is bit 1.
35711**
35712** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
35713** a hash table that will hold up to BITVEC_MXHASH distinct values.
35714**
35715** Otherwise, the value i is redirected into one of BITVEC_NPTR
35716** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
35717** handles up to iDivisor separate values of i.  apSub[0] holds
35718** values between 1 and iDivisor.  apSub[1] holds values between
35719** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
35720** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
35721** to hold deal with values between 1 and iDivisor.
35722*/
35723struct Bitvec {
35724  u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
35725  u32 nSet;       /* Number of bits that are set - only valid for aHash
35726                  ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,
35727                  ** this would be 125. */
35728  u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
35729                  /* Should >=0 for apSub element. */
35730                  /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
35731                  /* For a BITVEC_SZ of 512, this would be 34,359,739. */
35732  union {
35733    BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
35734    u32 aHash[BITVEC_NINT];      /* Hash table representation */
35735    Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
35736  } u;
35737};
35738
35739/*
35740** Create a new bitmap object able to handle bits between 0 and iSize,
35741** inclusive.  Return a pointer to the new object.  Return NULL if
35742** malloc fails.
35743*/
35744SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
35745  Bitvec *p;
35746  assert( sizeof(*p)==BITVEC_SZ );
35747  p = sqlite3MallocZero( sizeof(*p) );
35748  if( p ){
35749    p->iSize = iSize;
35750  }
35751  return p;
35752}
35753
35754/*
35755** Check to see if the i-th bit is set.  Return true or false.
35756** If p is NULL (if the bitmap has not been created) or if
35757** i is out of range, then return false.
35758*/
35759SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
35760  if( p==0 ) return 0;
35761  if( i>p->iSize || i==0 ) return 0;
35762  i--;
35763  while( p->iDivisor ){
35764    u32 bin = i/p->iDivisor;
35765    i = i%p->iDivisor;
35766    p = p->u.apSub[bin];
35767    if (!p) {
35768      return 0;
35769    }
35770  }
35771  if( p->iSize<=BITVEC_NBIT ){
35772    return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
35773  } else{
35774    u32 h = BITVEC_HASH(i++);
35775    while( p->u.aHash[h] ){
35776      if( p->u.aHash[h]==i ) return 1;
35777      h = (h+1) % BITVEC_NINT;
35778    }
35779    return 0;
35780  }
35781}
35782
35783/*
35784** Set the i-th bit.  Return 0 on success and an error code if
35785** anything goes wrong.
35786**
35787** This routine might cause sub-bitmaps to be allocated.  Failing
35788** to get the memory needed to hold the sub-bitmap is the only
35789** that can go wrong with an insert, assuming p and i are valid.
35790**
35791** The calling function must ensure that p is a valid Bitvec object
35792** and that the value for "i" is within range of the Bitvec object.
35793** Otherwise the behavior is undefined.
35794*/
35795SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
35796  u32 h;
35797  if( p==0 ) return SQLITE_OK;
35798  assert( i>0 );
35799  assert( i<=p->iSize );
35800  i--;
35801  while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
35802    u32 bin = i/p->iDivisor;
35803    i = i%p->iDivisor;
35804    if( p->u.apSub[bin]==0 ){
35805      p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
35806      if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
35807    }
35808    p = p->u.apSub[bin];
35809  }
35810  if( p->iSize<=BITVEC_NBIT ){
35811    p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
35812    return SQLITE_OK;
35813  }
35814  h = BITVEC_HASH(i++);
35815  /* if there wasn't a hash collision, and this doesn't */
35816  /* completely fill the hash, then just add it without */
35817  /* worring about sub-dividing and re-hashing. */
35818  if( !p->u.aHash[h] ){
35819    if (p->nSet<(BITVEC_NINT-1)) {
35820      goto bitvec_set_end;
35821    } else {
35822      goto bitvec_set_rehash;
35823    }
35824  }
35825  /* there was a collision, check to see if it's already */
35826  /* in hash, if not, try to find a spot for it */
35827  do {
35828    if( p->u.aHash[h]==i ) return SQLITE_OK;
35829    h++;
35830    if( h>=BITVEC_NINT ) h = 0;
35831  } while( p->u.aHash[h] );
35832  /* we didn't find it in the hash.  h points to the first */
35833  /* available free spot. check to see if this is going to */
35834  /* make our hash too "full".  */
35835bitvec_set_rehash:
35836  if( p->nSet>=BITVEC_MXHASH ){
35837    unsigned int j;
35838    int rc;
35839    u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
35840    if( aiValues==0 ){
35841      return SQLITE_NOMEM;
35842    }else{
35843      memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
35844      memset(p->u.apSub, 0, sizeof(p->u.apSub));
35845      p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
35846      rc = sqlite3BitvecSet(p, i);
35847      for(j=0; j<BITVEC_NINT; j++){
35848        if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
35849      }
35850      sqlite3StackFree(0, aiValues);
35851      return rc;
35852    }
35853  }
35854bitvec_set_end:
35855  p->nSet++;
35856  p->u.aHash[h] = i;
35857  return SQLITE_OK;
35858}
35859
35860/*
35861** Clear the i-th bit.
35862**
35863** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
35864** that BitvecClear can use to rebuilt its hash table.
35865*/
35866SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
35867  if( p==0 ) return;
35868  assert( i>0 );
35869  i--;
35870  while( p->iDivisor ){
35871    u32 bin = i/p->iDivisor;
35872    i = i%p->iDivisor;
35873    p = p->u.apSub[bin];
35874    if (!p) {
35875      return;
35876    }
35877  }
35878  if( p->iSize<=BITVEC_NBIT ){
35879    p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
35880  }else{
35881    unsigned int j;
35882    u32 *aiValues = pBuf;
35883    memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
35884    memset(p->u.aHash, 0, sizeof(p->u.aHash));
35885    p->nSet = 0;
35886    for(j=0; j<BITVEC_NINT; j++){
35887      if( aiValues[j] && aiValues[j]!=(i+1) ){
35888        u32 h = BITVEC_HASH(aiValues[j]-1);
35889        p->nSet++;
35890        while( p->u.aHash[h] ){
35891          h++;
35892          if( h>=BITVEC_NINT ) h = 0;
35893        }
35894        p->u.aHash[h] = aiValues[j];
35895      }
35896    }
35897  }
35898}
35899
35900/*
35901** Destroy a bitmap object.  Reclaim all memory used.
35902*/
35903SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
35904  if( p==0 ) return;
35905  if( p->iDivisor ){
35906    unsigned int i;
35907    for(i=0; i<BITVEC_NPTR; i++){
35908      sqlite3BitvecDestroy(p->u.apSub[i]);
35909    }
35910  }
35911  sqlite3_free(p);
35912}
35913
35914/*
35915** Return the value of the iSize parameter specified when Bitvec *p
35916** was created.
35917*/
35918SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
35919  return p->iSize;
35920}
35921
35922#ifndef SQLITE_OMIT_BUILTIN_TEST
35923/*
35924** Let V[] be an array of unsigned characters sufficient to hold
35925** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
35926** Then the following macros can be used to set, clear, or test
35927** individual bits within V.
35928*/
35929#define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
35930#define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
35931#define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
35932
35933/*
35934** This routine runs an extensive test of the Bitvec code.
35935**
35936** The input is an array of integers that acts as a program
35937** to test the Bitvec.  The integers are opcodes followed
35938** by 0, 1, or 3 operands, depending on the opcode.  Another
35939** opcode follows immediately after the last operand.
35940**
35941** There are 6 opcodes numbered from 0 through 5.  0 is the
35942** "halt" opcode and causes the test to end.
35943**
35944**    0          Halt and return the number of errors
35945**    1 N S X    Set N bits beginning with S and incrementing by X
35946**    2 N S X    Clear N bits beginning with S and incrementing by X
35947**    3 N        Set N randomly chosen bits
35948**    4 N        Clear N randomly chosen bits
35949**    5 N S X    Set N bits from S increment X in array only, not in bitvec
35950**
35951** The opcodes 1 through 4 perform set and clear operations are performed
35952** on both a Bitvec object and on a linear array of bits obtained from malloc.
35953** Opcode 5 works on the linear array only, not on the Bitvec.
35954** Opcode 5 is used to deliberately induce a fault in order to
35955** confirm that error detection works.
35956**
35957** At the conclusion of the test the linear array is compared
35958** against the Bitvec object.  If there are any differences,
35959** an error is returned.  If they are the same, zero is returned.
35960**
35961** If a memory allocation error occurs, return -1.
35962*/
35963SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
35964  Bitvec *pBitvec = 0;
35965  unsigned char *pV = 0;
35966  int rc = -1;
35967  int i, nx, pc, op;
35968  void *pTmpSpace;
35969
35970  /* Allocate the Bitvec to be tested and a linear array of
35971  ** bits to act as the reference */
35972  pBitvec = sqlite3BitvecCreate( sz );
35973  pV = sqlite3MallocZero( (sz+7)/8 + 1 );
35974  pTmpSpace = sqlite3_malloc(BITVEC_SZ);
35975  if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;
35976
35977  /* NULL pBitvec tests */
35978  sqlite3BitvecSet(0, 1);
35979  sqlite3BitvecClear(0, 1, pTmpSpace);
35980
35981  /* Run the program */
35982  pc = 0;
35983  while( (op = aOp[pc])!=0 ){
35984    switch( op ){
35985      case 1:
35986      case 2:
35987      case 5: {
35988        nx = 4;
35989        i = aOp[pc+2] - 1;
35990        aOp[pc+2] += aOp[pc+3];
35991        break;
35992      }
35993      case 3:
35994      case 4:
35995      default: {
35996        nx = 2;
35997        sqlite3_randomness(sizeof(i), &i);
35998        break;
35999      }
36000    }
36001    if( (--aOp[pc+1]) > 0 ) nx = 0;
36002    pc += nx;
36003    i = (i & 0x7fffffff)%sz;
36004    if( (op & 1)!=0 ){
36005      SETBIT(pV, (i+1));
36006      if( op!=5 ){
36007        if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
36008      }
36009    }else{
36010      CLEARBIT(pV, (i+1));
36011      sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
36012    }
36013  }
36014
36015  /* Test to make sure the linear array exactly matches the
36016  ** Bitvec object.  Start with the assumption that they do
36017  ** match (rc==0).  Change rc to non-zero if a discrepancy
36018  ** is found.
36019  */
36020  rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
36021          + sqlite3BitvecTest(pBitvec, 0)
36022          + (sqlite3BitvecSize(pBitvec) - sz);
36023  for(i=1; i<=sz; i++){
36024    if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
36025      rc = i;
36026      break;
36027    }
36028  }
36029
36030  /* Free allocated structure */
36031bitvec_end:
36032  sqlite3_free(pTmpSpace);
36033  sqlite3_free(pV);
36034  sqlite3BitvecDestroy(pBitvec);
36035  return rc;
36036}
36037#endif /* SQLITE_OMIT_BUILTIN_TEST */
36038
36039/************** End of bitvec.c **********************************************/
36040/************** Begin file pcache.c ******************************************/
36041/*
36042** 2008 August 05
36043**
36044** The author disclaims copyright to this source code.  In place of
36045** a legal notice, here is a blessing:
36046**
36047**    May you do good and not evil.
36048**    May you find forgiveness for yourself and forgive others.
36049**    May you share freely, never taking more than you give.
36050**
36051*************************************************************************
36052** This file implements that page cache.
36053*/
36054
36055/*
36056** A complete page cache is an instance of this structure.
36057*/
36058struct PCache {
36059  PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
36060  PgHdr *pSynced;                     /* Last synced page in dirty page list */
36061  int nRef;                           /* Number of referenced pages */
36062  int szCache;                        /* Configured cache size */
36063  int szPage;                         /* Size of every page in this cache */
36064  int szExtra;                        /* Size of extra space for each page */
36065  int bPurgeable;                     /* True if pages are on backing store */
36066  int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
36067  void *pStress;                      /* Argument to xStress */
36068  sqlite3_pcache *pCache;             /* Pluggable cache module */
36069  PgHdr *pPage1;                      /* Reference to page 1 */
36070};
36071
36072/*
36073** Some of the assert() macros in this code are too expensive to run
36074** even during normal debugging.  Use them only rarely on long-running
36075** tests.  Enable the expensive asserts using the
36076** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
36077*/
36078#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
36079# define expensive_assert(X)  assert(X)
36080#else
36081# define expensive_assert(X)
36082#endif
36083
36084/********************************** Linked List Management ********************/
36085
36086#if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
36087/*
36088** Check that the pCache->pSynced variable is set correctly. If it
36089** is not, either fail an assert or return zero. Otherwise, return
36090** non-zero. This is only used in debugging builds, as follows:
36091**
36092**   expensive_assert( pcacheCheckSynced(pCache) );
36093*/
36094static int pcacheCheckSynced(PCache *pCache){
36095  PgHdr *p;
36096  for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
36097    assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
36098  }
36099  return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
36100}
36101#endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
36102
36103/*
36104** Remove page pPage from the list of dirty pages.
36105*/
36106static void pcacheRemoveFromDirtyList(PgHdr *pPage){
36107  PCache *p = pPage->pCache;
36108
36109  assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
36110  assert( pPage->pDirtyPrev || pPage==p->pDirty );
36111
36112  /* Update the PCache1.pSynced variable if necessary. */
36113  if( p->pSynced==pPage ){
36114    PgHdr *pSynced = pPage->pDirtyPrev;
36115    while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
36116      pSynced = pSynced->pDirtyPrev;
36117    }
36118    p->pSynced = pSynced;
36119  }
36120
36121  if( pPage->pDirtyNext ){
36122    pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
36123  }else{
36124    assert( pPage==p->pDirtyTail );
36125    p->pDirtyTail = pPage->pDirtyPrev;
36126  }
36127  if( pPage->pDirtyPrev ){
36128    pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
36129  }else{
36130    assert( pPage==p->pDirty );
36131    p->pDirty = pPage->pDirtyNext;
36132  }
36133  pPage->pDirtyNext = 0;
36134  pPage->pDirtyPrev = 0;
36135
36136  expensive_assert( pcacheCheckSynced(p) );
36137}
36138
36139/*
36140** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
36141** pPage).
36142*/
36143static void pcacheAddToDirtyList(PgHdr *pPage){
36144  PCache *p = pPage->pCache;
36145
36146  assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
36147
36148  pPage->pDirtyNext = p->pDirty;
36149  if( pPage->pDirtyNext ){
36150    assert( pPage->pDirtyNext->pDirtyPrev==0 );
36151    pPage->pDirtyNext->pDirtyPrev = pPage;
36152  }
36153  p->pDirty = pPage;
36154  if( !p->pDirtyTail ){
36155    p->pDirtyTail = pPage;
36156  }
36157  if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
36158    p->pSynced = pPage;
36159  }
36160  expensive_assert( pcacheCheckSynced(p) );
36161}
36162
36163/*
36164** Wrapper around the pluggable caches xUnpin method. If the cache is
36165** being used for an in-memory database, this function is a no-op.
36166*/
36167static void pcacheUnpin(PgHdr *p){
36168  PCache *pCache = p->pCache;
36169  if( pCache->bPurgeable ){
36170    if( p->pgno==1 ){
36171      pCache->pPage1 = 0;
36172    }
36173    sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 0);
36174  }
36175}
36176
36177/*************************************************** General Interfaces ******
36178**
36179** Initialize and shutdown the page cache subsystem. Neither of these
36180** functions are threadsafe.
36181*/
36182SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
36183  if( sqlite3GlobalConfig.pcache2.xInit==0 ){
36184    /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
36185    ** built-in default page cache is used instead of the application defined
36186    ** page cache. */
36187    sqlite3PCacheSetDefault();
36188  }
36189  return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
36190}
36191SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
36192  if( sqlite3GlobalConfig.pcache2.xShutdown ){
36193    /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
36194    sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
36195  }
36196}
36197
36198/*
36199** Return the size in bytes of a PCache object.
36200*/
36201SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
36202
36203/*
36204** Create a new PCache object. Storage space to hold the object
36205** has already been allocated and is passed in as the p pointer.
36206** The caller discovers how much space needs to be allocated by
36207** calling sqlite3PcacheSize().
36208*/
36209SQLITE_PRIVATE void sqlite3PcacheOpen(
36210  int szPage,                  /* Size of every page */
36211  int szExtra,                 /* Extra space associated with each page */
36212  int bPurgeable,              /* True if pages are on backing store */
36213  int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
36214  void *pStress,               /* Argument to xStress */
36215  PCache *p                    /* Preallocated space for the PCache */
36216){
36217  memset(p, 0, sizeof(PCache));
36218  p->szPage = szPage;
36219  p->szExtra = szExtra;
36220  p->bPurgeable = bPurgeable;
36221  p->xStress = xStress;
36222  p->pStress = pStress;
36223  p->szCache = 100;
36224}
36225
36226/*
36227** Change the page size for PCache object. The caller must ensure that there
36228** are no outstanding page references when this function is called.
36229*/
36230SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
36231  assert( pCache->nRef==0 && pCache->pDirty==0 );
36232  if( pCache->pCache ){
36233    sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
36234    pCache->pCache = 0;
36235    pCache->pPage1 = 0;
36236  }
36237  pCache->szPage = szPage;
36238}
36239
36240/*
36241** Compute the number of pages of cache requested.
36242*/
36243static int numberOfCachePages(PCache *p){
36244  if( p->szCache>=0 ){
36245    return p->szCache;
36246  }else{
36247    return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
36248  }
36249}
36250
36251/*
36252** Try to obtain a page from the cache.
36253*/
36254SQLITE_PRIVATE int sqlite3PcacheFetch(
36255  PCache *pCache,       /* Obtain the page from this cache */
36256  Pgno pgno,            /* Page number to obtain */
36257  int createFlag,       /* If true, create page if it does not exist already */
36258  PgHdr **ppPage        /* Write the page here */
36259){
36260  sqlite3_pcache_page *pPage = 0;
36261  PgHdr *pPgHdr = 0;
36262  int eCreate;
36263
36264  assert( pCache!=0 );
36265  assert( createFlag==1 || createFlag==0 );
36266  assert( pgno>0 );
36267
36268  /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
36269  ** allocate it now.
36270  */
36271  if( !pCache->pCache && createFlag ){
36272    sqlite3_pcache *p;
36273    p = sqlite3GlobalConfig.pcache2.xCreate(
36274        pCache->szPage, pCache->szExtra + sizeof(PgHdr), pCache->bPurgeable
36275    );
36276    if( !p ){
36277      return SQLITE_NOMEM;
36278    }
36279    sqlite3GlobalConfig.pcache2.xCachesize(p, numberOfCachePages(pCache));
36280    pCache->pCache = p;
36281  }
36282
36283  eCreate = createFlag * (1 + (!pCache->bPurgeable || !pCache->pDirty));
36284  if( pCache->pCache ){
36285    pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
36286  }
36287
36288  if( !pPage && eCreate==1 ){
36289    PgHdr *pPg;
36290
36291    /* Find a dirty page to write-out and recycle. First try to find a
36292    ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
36293    ** cleared), but if that is not possible settle for any other
36294    ** unreferenced dirty page.
36295    */
36296    expensive_assert( pcacheCheckSynced(pCache) );
36297    for(pPg=pCache->pSynced;
36298        pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
36299        pPg=pPg->pDirtyPrev
36300    );
36301    pCache->pSynced = pPg;
36302    if( !pPg ){
36303      for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
36304    }
36305    if( pPg ){
36306      int rc;
36307#ifdef SQLITE_LOG_CACHE_SPILL
36308      sqlite3_log(SQLITE_FULL,
36309                  "spill page %d making room for %d - cache used: %d/%d",
36310                  pPg->pgno, pgno,
36311                  sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
36312                  numberOfCachePages(pCache));
36313#endif
36314      rc = pCache->xStress(pCache->pStress, pPg);
36315      if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
36316        return rc;
36317      }
36318    }
36319
36320    pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
36321  }
36322
36323  if( pPage ){
36324    pPgHdr = (PgHdr *)pPage->pExtra;
36325
36326    if( !pPgHdr->pPage ){
36327      memset(pPgHdr, 0, sizeof(PgHdr));
36328      pPgHdr->pPage = pPage;
36329      pPgHdr->pData = pPage->pBuf;
36330      pPgHdr->pExtra = (void *)&pPgHdr[1];
36331      memset(pPgHdr->pExtra, 0, pCache->szExtra);
36332      pPgHdr->pCache = pCache;
36333      pPgHdr->pgno = pgno;
36334    }
36335    assert( pPgHdr->pCache==pCache );
36336    assert( pPgHdr->pgno==pgno );
36337    assert( pPgHdr->pData==pPage->pBuf );
36338    assert( pPgHdr->pExtra==(void *)&pPgHdr[1] );
36339
36340    if( 0==pPgHdr->nRef ){
36341      pCache->nRef++;
36342    }
36343    pPgHdr->nRef++;
36344    if( pgno==1 ){
36345      pCache->pPage1 = pPgHdr;
36346    }
36347  }
36348  *ppPage = pPgHdr;
36349  return (pPgHdr==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
36350}
36351
36352/*
36353** Decrement the reference count on a page. If the page is clean and the
36354** reference count drops to 0, then it is made elible for recycling.
36355*/
36356SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
36357  assert( p->nRef>0 );
36358  p->nRef--;
36359  if( p->nRef==0 ){
36360    PCache *pCache = p->pCache;
36361    pCache->nRef--;
36362    if( (p->flags&PGHDR_DIRTY)==0 ){
36363      pcacheUnpin(p);
36364    }else{
36365      /* Move the page to the head of the dirty list. */
36366      pcacheRemoveFromDirtyList(p);
36367      pcacheAddToDirtyList(p);
36368    }
36369  }
36370}
36371
36372/*
36373** Increase the reference count of a supplied page by 1.
36374*/
36375SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
36376  assert(p->nRef>0);
36377  p->nRef++;
36378}
36379
36380/*
36381** Drop a page from the cache. There must be exactly one reference to the
36382** page. This function deletes that reference, so after it returns the
36383** page pointed to by p is invalid.
36384*/
36385SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
36386  PCache *pCache;
36387  assert( p->nRef==1 );
36388  if( p->flags&PGHDR_DIRTY ){
36389    pcacheRemoveFromDirtyList(p);
36390  }
36391  pCache = p->pCache;
36392  pCache->nRef--;
36393  if( p->pgno==1 ){
36394    pCache->pPage1 = 0;
36395  }
36396  sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 1);
36397}
36398
36399/*
36400** Make sure the page is marked as dirty. If it isn't dirty already,
36401** make it so.
36402*/
36403SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
36404  p->flags &= ~PGHDR_DONT_WRITE;
36405  assert( p->nRef>0 );
36406  if( 0==(p->flags & PGHDR_DIRTY) ){
36407    p->flags |= PGHDR_DIRTY;
36408    pcacheAddToDirtyList( p);
36409  }
36410}
36411
36412/*
36413** Make sure the page is marked as clean. If it isn't clean already,
36414** make it so.
36415*/
36416SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
36417  if( (p->flags & PGHDR_DIRTY) ){
36418    pcacheRemoveFromDirtyList(p);
36419    p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
36420    if( p->nRef==0 ){
36421      pcacheUnpin(p);
36422    }
36423  }
36424}
36425
36426/*
36427** Make every page in the cache clean.
36428*/
36429SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
36430  PgHdr *p;
36431  while( (p = pCache->pDirty)!=0 ){
36432    sqlite3PcacheMakeClean(p);
36433  }
36434}
36435
36436/*
36437** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
36438*/
36439SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
36440  PgHdr *p;
36441  for(p=pCache->pDirty; p; p=p->pDirtyNext){
36442    p->flags &= ~PGHDR_NEED_SYNC;
36443  }
36444  pCache->pSynced = pCache->pDirtyTail;
36445}
36446
36447/*
36448** Change the page number of page p to newPgno.
36449*/
36450SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
36451  PCache *pCache = p->pCache;
36452  assert( p->nRef>0 );
36453  assert( newPgno>0 );
36454  sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
36455  p->pgno = newPgno;
36456  if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
36457    pcacheRemoveFromDirtyList(p);
36458    pcacheAddToDirtyList(p);
36459  }
36460}
36461
36462/*
36463** Drop every cache entry whose page number is greater than "pgno". The
36464** caller must ensure that there are no outstanding references to any pages
36465** other than page 1 with a page number greater than pgno.
36466**
36467** If there is a reference to page 1 and the pgno parameter passed to this
36468** function is 0, then the data area associated with page 1 is zeroed, but
36469** the page object is not dropped.
36470*/
36471SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
36472  if( pCache->pCache ){
36473    PgHdr *p;
36474    PgHdr *pNext;
36475    for(p=pCache->pDirty; p; p=pNext){
36476      pNext = p->pDirtyNext;
36477      /* This routine never gets call with a positive pgno except right
36478      ** after sqlite3PcacheCleanAll().  So if there are dirty pages,
36479      ** it must be that pgno==0.
36480      */
36481      assert( p->pgno>0 );
36482      if( ALWAYS(p->pgno>pgno) ){
36483        assert( p->flags&PGHDR_DIRTY );
36484        sqlite3PcacheMakeClean(p);
36485      }
36486    }
36487    if( pgno==0 && pCache->pPage1 ){
36488      memset(pCache->pPage1->pData, 0, pCache->szPage);
36489      pgno = 1;
36490    }
36491    sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
36492  }
36493}
36494
36495/*
36496** Close a cache.
36497*/
36498SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
36499  if( pCache->pCache ){
36500    sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
36501  }
36502}
36503
36504/*
36505** Discard the contents of the cache.
36506*/
36507SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
36508  sqlite3PcacheTruncate(pCache, 0);
36509}
36510
36511/*
36512** Merge two lists of pages connected by pDirty and in pgno order.
36513** Do not both fixing the pDirtyPrev pointers.
36514*/
36515static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
36516  PgHdr result, *pTail;
36517  pTail = &result;
36518  while( pA && pB ){
36519    if( pA->pgno<pB->pgno ){
36520      pTail->pDirty = pA;
36521      pTail = pA;
36522      pA = pA->pDirty;
36523    }else{
36524      pTail->pDirty = pB;
36525      pTail = pB;
36526      pB = pB->pDirty;
36527    }
36528  }
36529  if( pA ){
36530    pTail->pDirty = pA;
36531  }else if( pB ){
36532    pTail->pDirty = pB;
36533  }else{
36534    pTail->pDirty = 0;
36535  }
36536  return result.pDirty;
36537}
36538
36539/*
36540** Sort the list of pages in accending order by pgno.  Pages are
36541** connected by pDirty pointers.  The pDirtyPrev pointers are
36542** corrupted by this sort.
36543**
36544** Since there cannot be more than 2^31 distinct pages in a database,
36545** there cannot be more than 31 buckets required by the merge sorter.
36546** One extra bucket is added to catch overflow in case something
36547** ever changes to make the previous sentence incorrect.
36548*/
36549#define N_SORT_BUCKET  32
36550static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
36551  PgHdr *a[N_SORT_BUCKET], *p;
36552  int i;
36553  memset(a, 0, sizeof(a));
36554  while( pIn ){
36555    p = pIn;
36556    pIn = p->pDirty;
36557    p->pDirty = 0;
36558    for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
36559      if( a[i]==0 ){
36560        a[i] = p;
36561        break;
36562      }else{
36563        p = pcacheMergeDirtyList(a[i], p);
36564        a[i] = 0;
36565      }
36566    }
36567    if( NEVER(i==N_SORT_BUCKET-1) ){
36568      /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
36569      ** the input list.  But that is impossible.
36570      */
36571      a[i] = pcacheMergeDirtyList(a[i], p);
36572    }
36573  }
36574  p = a[0];
36575  for(i=1; i<N_SORT_BUCKET; i++){
36576    p = pcacheMergeDirtyList(p, a[i]);
36577  }
36578  return p;
36579}
36580
36581/*
36582** Return a list of all dirty pages in the cache, sorted by page number.
36583*/
36584SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
36585  PgHdr *p;
36586  for(p=pCache->pDirty; p; p=p->pDirtyNext){
36587    p->pDirty = p->pDirtyNext;
36588  }
36589  return pcacheSortDirtyList(pCache->pDirty);
36590}
36591
36592/*
36593** Return the total number of referenced pages held by the cache.
36594*/
36595SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
36596  return pCache->nRef;
36597}
36598
36599/*
36600** Return the number of references to the page supplied as an argument.
36601*/
36602SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
36603  return p->nRef;
36604}
36605
36606/*
36607** Return the total number of pages in the cache.
36608*/
36609SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
36610  int nPage = 0;
36611  if( pCache->pCache ){
36612    nPage = sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
36613  }
36614  return nPage;
36615}
36616
36617#ifdef SQLITE_TEST
36618/*
36619** Get the suggested cache-size value.
36620*/
36621SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
36622  return numberOfCachePages(pCache);
36623}
36624#endif
36625
36626/*
36627** Set the suggested cache-size value.
36628*/
36629SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
36630  pCache->szCache = mxPage;
36631  if( pCache->pCache ){
36632    sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
36633                                           numberOfCachePages(pCache));
36634  }
36635}
36636
36637/*
36638** Free up as much memory as possible from the page cache.
36639*/
36640SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
36641  if( pCache->pCache ){
36642    sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
36643  }
36644}
36645
36646#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
36647/*
36648** For all dirty pages currently in the cache, invoke the specified
36649** callback. This is only used if the SQLITE_CHECK_PAGES macro is
36650** defined.
36651*/
36652SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
36653  PgHdr *pDirty;
36654  for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
36655    xIter(pDirty);
36656  }
36657}
36658#endif
36659
36660/************** End of pcache.c **********************************************/
36661/************** Begin file pcache1.c *****************************************/
36662/*
36663** 2008 November 05
36664**
36665** The author disclaims copyright to this source code.  In place of
36666** a legal notice, here is a blessing:
36667**
36668**    May you do good and not evil.
36669**    May you find forgiveness for yourself and forgive others.
36670**    May you share freely, never taking more than you give.
36671**
36672*************************************************************************
36673**
36674** This file implements the default page cache implementation (the
36675** sqlite3_pcache interface). It also contains part of the implementation
36676** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
36677** If the default page cache implementation is overriden, then neither of
36678** these two features are available.
36679*/
36680
36681
36682typedef struct PCache1 PCache1;
36683typedef struct PgHdr1 PgHdr1;
36684typedef struct PgFreeslot PgFreeslot;
36685typedef struct PGroup PGroup;
36686
36687/* Each page cache (or PCache) belongs to a PGroup.  A PGroup is a set
36688** of one or more PCaches that are able to recycle each others unpinned
36689** pages when they are under memory pressure.  A PGroup is an instance of
36690** the following object.
36691**
36692** This page cache implementation works in one of two modes:
36693**
36694**   (1)  Every PCache is the sole member of its own PGroup.  There is
36695**        one PGroup per PCache.
36696**
36697**   (2)  There is a single global PGroup that all PCaches are a member
36698**        of.
36699**
36700** Mode 1 uses more memory (since PCache instances are not able to rob
36701** unused pages from other PCaches) but it also operates without a mutex,
36702** and is therefore often faster.  Mode 2 requires a mutex in order to be
36703** threadsafe, but recycles pages more efficiently.
36704**
36705** For mode (1), PGroup.mutex is NULL.  For mode (2) there is only a single
36706** PGroup which is the pcache1.grp global variable and its mutex is
36707** SQLITE_MUTEX_STATIC_LRU.
36708*/
36709struct PGroup {
36710  sqlite3_mutex *mutex;          /* MUTEX_STATIC_LRU or NULL */
36711  unsigned int nMaxPage;         /* Sum of nMax for purgeable caches */
36712  unsigned int nMinPage;         /* Sum of nMin for purgeable caches */
36713  unsigned int mxPinned;         /* nMaxpage + 10 - nMinPage */
36714  unsigned int nCurrentPage;     /* Number of purgeable pages allocated */
36715  PgHdr1 *pLruHead, *pLruTail;   /* LRU list of unpinned pages */
36716};
36717
36718/* Each page cache is an instance of the following object.  Every
36719** open database file (including each in-memory database and each
36720** temporary or transient database) has a single page cache which
36721** is an instance of this object.
36722**
36723** Pointers to structures of this type are cast and returned as
36724** opaque sqlite3_pcache* handles.
36725*/
36726struct PCache1 {
36727  /* Cache configuration parameters. Page size (szPage) and the purgeable
36728  ** flag (bPurgeable) are set when the cache is created. nMax may be
36729  ** modified at any time by a call to the pcache1Cachesize() method.
36730  ** The PGroup mutex must be held when accessing nMax.
36731  */
36732  PGroup *pGroup;                     /* PGroup this cache belongs to */
36733  int szPage;                         /* Size of allocated pages in bytes */
36734  int szExtra;                        /* Size of extra space in bytes */
36735  int bPurgeable;                     /* True if cache is purgeable */
36736  unsigned int nMin;                  /* Minimum number of pages reserved */
36737  unsigned int nMax;                  /* Configured "cache_size" value */
36738  unsigned int n90pct;                /* nMax*9/10 */
36739  unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
36740
36741  /* Hash table of all pages. The following variables may only be accessed
36742  ** when the accessor is holding the PGroup mutex.
36743  */
36744  unsigned int nRecyclable;           /* Number of pages in the LRU list */
36745  unsigned int nPage;                 /* Total number of pages in apHash */
36746  unsigned int nHash;                 /* Number of slots in apHash[] */
36747  PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
36748};
36749
36750/*
36751** Each cache entry is represented by an instance of the following
36752** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
36753** PgHdr1.pCache->szPage bytes is allocated directly before this structure
36754** in memory.
36755*/
36756struct PgHdr1 {
36757  sqlite3_pcache_page page;
36758  unsigned int iKey;             /* Key value (page number) */
36759  PgHdr1 *pNext;                 /* Next in hash table chain */
36760  PCache1 *pCache;               /* Cache that currently owns this page */
36761  PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
36762  PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
36763};
36764
36765/*
36766** Free slots in the allocator used to divide up the buffer provided using
36767** the SQLITE_CONFIG_PAGECACHE mechanism.
36768*/
36769struct PgFreeslot {
36770  PgFreeslot *pNext;  /* Next free slot */
36771};
36772
36773/*
36774** Global data used by this cache.
36775*/
36776static SQLITE_WSD struct PCacheGlobal {
36777  PGroup grp;                    /* The global PGroup for mode (2) */
36778
36779  /* Variables related to SQLITE_CONFIG_PAGECACHE settings.  The
36780  ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
36781  ** fixed at sqlite3_initialize() time and do not require mutex protection.
36782  ** The nFreeSlot and pFree values do require mutex protection.
36783  */
36784  int isInit;                    /* True if initialized */
36785  int szSlot;                    /* Size of each free slot */
36786  int nSlot;                     /* The number of pcache slots */
36787  int nReserve;                  /* Try to keep nFreeSlot above this */
36788  void *pStart, *pEnd;           /* Bounds of pagecache malloc range */
36789  /* Above requires no mutex.  Use mutex below for variable that follow. */
36790  sqlite3_mutex *mutex;          /* Mutex for accessing the following: */
36791  PgFreeslot *pFree;             /* Free page blocks */
36792  int nFreeSlot;                 /* Number of unused pcache slots */
36793  /* The following value requires a mutex to change.  We skip the mutex on
36794  ** reading because (1) most platforms read a 32-bit integer atomically and
36795  ** (2) even if an incorrect value is read, no great harm is done since this
36796  ** is really just an optimization. */
36797  int bUnderPressure;            /* True if low on PAGECACHE memory */
36798} pcache1_g;
36799
36800/*
36801** All code in this file should access the global structure above via the
36802** alias "pcache1". This ensures that the WSD emulation is used when
36803** compiling for systems that do not support real WSD.
36804*/
36805#define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
36806
36807/*
36808** Macros to enter and leave the PCache LRU mutex.
36809*/
36810#define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
36811#define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
36812
36813/******************************************************************************/
36814/******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
36815
36816/*
36817** This function is called during initialization if a static buffer is
36818** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
36819** verb to sqlite3_config(). Parameter pBuf points to an allocation large
36820** enough to contain 'n' buffers of 'sz' bytes each.
36821**
36822** This routine is called from sqlite3_initialize() and so it is guaranteed
36823** to be serialized already.  There is no need for further mutexing.
36824*/
36825SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
36826  if( pcache1.isInit ){
36827    PgFreeslot *p;
36828    sz = ROUNDDOWN8(sz);
36829    pcache1.szSlot = sz;
36830    pcache1.nSlot = pcache1.nFreeSlot = n;
36831    pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
36832    pcache1.pStart = pBuf;
36833    pcache1.pFree = 0;
36834    pcache1.bUnderPressure = 0;
36835    while( n-- ){
36836      p = (PgFreeslot*)pBuf;
36837      p->pNext = pcache1.pFree;
36838      pcache1.pFree = p;
36839      pBuf = (void*)&((char*)pBuf)[sz];
36840    }
36841    pcache1.pEnd = pBuf;
36842  }
36843}
36844
36845/*
36846** Malloc function used within this file to allocate space from the buffer
36847** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
36848** such buffer exists or there is no space left in it, this function falls
36849** back to sqlite3Malloc().
36850**
36851** Multiple threads can run this routine at the same time.  Global variables
36852** in pcache1 need to be protected via mutex.
36853*/
36854static void *pcache1Alloc(int nByte){
36855  void *p = 0;
36856  assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
36857  sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
36858  if( nByte<=pcache1.szSlot ){
36859    sqlite3_mutex_enter(pcache1.mutex);
36860    p = (PgHdr1 *)pcache1.pFree;
36861    if( p ){
36862      pcache1.pFree = pcache1.pFree->pNext;
36863      pcache1.nFreeSlot--;
36864      pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
36865      assert( pcache1.nFreeSlot>=0 );
36866      sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
36867    }
36868    sqlite3_mutex_leave(pcache1.mutex);
36869  }
36870  if( p==0 ){
36871    /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool.  Get
36872    ** it from sqlite3Malloc instead.
36873    */
36874    p = sqlite3Malloc(nByte);
36875#ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
36876    if( p ){
36877      int sz = sqlite3MallocSize(p);
36878      sqlite3_mutex_enter(pcache1.mutex);
36879      sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
36880      sqlite3_mutex_leave(pcache1.mutex);
36881    }
36882#endif
36883    sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
36884  }
36885  return p;
36886}
36887
36888/*
36889** Free an allocated buffer obtained from pcache1Alloc().
36890*/
36891static int pcache1Free(void *p){
36892  int nFreed = 0;
36893  if( p==0 ) return 0;
36894  if( p>=pcache1.pStart && p<pcache1.pEnd ){
36895    PgFreeslot *pSlot;
36896    sqlite3_mutex_enter(pcache1.mutex);
36897    sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
36898    pSlot = (PgFreeslot*)p;
36899    pSlot->pNext = pcache1.pFree;
36900    pcache1.pFree = pSlot;
36901    pcache1.nFreeSlot++;
36902    pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
36903    assert( pcache1.nFreeSlot<=pcache1.nSlot );
36904    sqlite3_mutex_leave(pcache1.mutex);
36905  }else{
36906    assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
36907    sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
36908    nFreed = sqlite3MallocSize(p);
36909#ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
36910    sqlite3_mutex_enter(pcache1.mutex);
36911    sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -nFreed);
36912    sqlite3_mutex_leave(pcache1.mutex);
36913#endif
36914    sqlite3_free(p);
36915  }
36916  return nFreed;
36917}
36918
36919#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
36920/*
36921** Return the size of a pcache allocation
36922*/
36923static int pcache1MemSize(void *p){
36924  if( p>=pcache1.pStart && p<pcache1.pEnd ){
36925    return pcache1.szSlot;
36926  }else{
36927    int iSize;
36928    assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
36929    sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
36930    iSize = sqlite3MallocSize(p);
36931    sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
36932    return iSize;
36933  }
36934}
36935#endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
36936
36937/*
36938** Allocate a new page object initially associated with cache pCache.
36939*/
36940static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
36941  PgHdr1 *p = 0;
36942  void *pPg;
36943
36944  /* The group mutex must be released before pcache1Alloc() is called. This
36945  ** is because it may call sqlite3_release_memory(), which assumes that
36946  ** this mutex is not held. */
36947  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
36948  pcache1LeaveMutex(pCache->pGroup);
36949#ifdef SQLITE_PCACHE_SEPARATE_HEADER
36950  pPg = pcache1Alloc(pCache->szPage);
36951  p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
36952  if( !pPg || !p ){
36953    pcache1Free(pPg);
36954    sqlite3_free(p);
36955    pPg = 0;
36956  }
36957#else
36958  pPg = pcache1Alloc(sizeof(PgHdr1) + pCache->szPage + pCache->szExtra);
36959  p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
36960#endif
36961  pcache1EnterMutex(pCache->pGroup);
36962
36963  if( pPg ){
36964    p->page.pBuf = pPg;
36965    p->page.pExtra = &p[1];
36966    if( pCache->bPurgeable ){
36967      pCache->pGroup->nCurrentPage++;
36968    }
36969    return p;
36970  }
36971  return 0;
36972}
36973
36974/*
36975** Free a page object allocated by pcache1AllocPage().
36976**
36977** The pointer is allowed to be NULL, which is prudent.  But it turns out
36978** that the current implementation happens to never call this routine
36979** with a NULL pointer, so we mark the NULL test with ALWAYS().
36980*/
36981static void pcache1FreePage(PgHdr1 *p){
36982  if( ALWAYS(p) ){
36983    PCache1 *pCache = p->pCache;
36984    assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
36985    pcache1Free(p->page.pBuf);
36986#ifdef SQLITE_PCACHE_SEPARATE_HEADER
36987    sqlite3_free(p);
36988#endif
36989    if( pCache->bPurgeable ){
36990      pCache->pGroup->nCurrentPage--;
36991    }
36992  }
36993}
36994
36995/*
36996** Malloc function used by SQLite to obtain space from the buffer configured
36997** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
36998** exists, this function falls back to sqlite3Malloc().
36999*/
37000SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
37001  return pcache1Alloc(sz);
37002}
37003
37004/*
37005** Free an allocated buffer obtained from sqlite3PageMalloc().
37006*/
37007SQLITE_PRIVATE void sqlite3PageFree(void *p){
37008  pcache1Free(p);
37009}
37010
37011
37012/*
37013** Return true if it desirable to avoid allocating a new page cache
37014** entry.
37015**
37016** If memory was allocated specifically to the page cache using
37017** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
37018** it is desirable to avoid allocating a new page cache entry because
37019** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
37020** for all page cache needs and we should not need to spill the
37021** allocation onto the heap.
37022**
37023** Or, the heap is used for all page cache memory but the heap is
37024** under memory pressure, then again it is desirable to avoid
37025** allocating a new page cache entry in order to avoid stressing
37026** the heap even further.
37027*/
37028static int pcache1UnderMemoryPressure(PCache1 *pCache){
37029  if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
37030    return pcache1.bUnderPressure;
37031  }else{
37032    return sqlite3HeapNearlyFull();
37033  }
37034}
37035
37036/******************************************************************************/
37037/******** General Implementation Functions ************************************/
37038
37039/*
37040** This function is used to resize the hash table used by the cache passed
37041** as the first argument.
37042**
37043** The PCache mutex must be held when this function is called.
37044*/
37045static int pcache1ResizeHash(PCache1 *p){
37046  PgHdr1 **apNew;
37047  unsigned int nNew;
37048  unsigned int i;
37049
37050  assert( sqlite3_mutex_held(p->pGroup->mutex) );
37051
37052  nNew = p->nHash*2;
37053  if( nNew<256 ){
37054    nNew = 256;
37055  }
37056
37057  pcache1LeaveMutex(p->pGroup);
37058  if( p->nHash ){ sqlite3BeginBenignMalloc(); }
37059  apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
37060  if( p->nHash ){ sqlite3EndBenignMalloc(); }
37061  pcache1EnterMutex(p->pGroup);
37062  if( apNew ){
37063    for(i=0; i<p->nHash; i++){
37064      PgHdr1 *pPage;
37065      PgHdr1 *pNext = p->apHash[i];
37066      while( (pPage = pNext)!=0 ){
37067        unsigned int h = pPage->iKey % nNew;
37068        pNext = pPage->pNext;
37069        pPage->pNext = apNew[h];
37070        apNew[h] = pPage;
37071      }
37072    }
37073    sqlite3_free(p->apHash);
37074    p->apHash = apNew;
37075    p->nHash = nNew;
37076  }
37077
37078  return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
37079}
37080
37081/*
37082** This function is used internally to remove the page pPage from the
37083** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
37084** LRU list, then this function is a no-op.
37085**
37086** The PGroup mutex must be held when this function is called.
37087**
37088** If pPage is NULL then this routine is a no-op.
37089*/
37090static void pcache1PinPage(PgHdr1 *pPage){
37091  PCache1 *pCache;
37092  PGroup *pGroup;
37093
37094  if( pPage==0 ) return;
37095  pCache = pPage->pCache;
37096  pGroup = pCache->pGroup;
37097  assert( sqlite3_mutex_held(pGroup->mutex) );
37098  if( pPage->pLruNext || pPage==pGroup->pLruTail ){
37099    if( pPage->pLruPrev ){
37100      pPage->pLruPrev->pLruNext = pPage->pLruNext;
37101    }
37102    if( pPage->pLruNext ){
37103      pPage->pLruNext->pLruPrev = pPage->pLruPrev;
37104    }
37105    if( pGroup->pLruHead==pPage ){
37106      pGroup->pLruHead = pPage->pLruNext;
37107    }
37108    if( pGroup->pLruTail==pPage ){
37109      pGroup->pLruTail = pPage->pLruPrev;
37110    }
37111    pPage->pLruNext = 0;
37112    pPage->pLruPrev = 0;
37113    pPage->pCache->nRecyclable--;
37114  }
37115}
37116
37117
37118/*
37119** Remove the page supplied as an argument from the hash table
37120** (PCache1.apHash structure) that it is currently stored in.
37121**
37122** The PGroup mutex must be held when this function is called.
37123*/
37124static void pcache1RemoveFromHash(PgHdr1 *pPage){
37125  unsigned int h;
37126  PCache1 *pCache = pPage->pCache;
37127  PgHdr1 **pp;
37128
37129  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
37130  h = pPage->iKey % pCache->nHash;
37131  for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
37132  *pp = (*pp)->pNext;
37133
37134  pCache->nPage--;
37135}
37136
37137/*
37138** If there are currently more than nMaxPage pages allocated, try
37139** to recycle pages to reduce the number allocated to nMaxPage.
37140*/
37141static void pcache1EnforceMaxPage(PGroup *pGroup){
37142  assert( sqlite3_mutex_held(pGroup->mutex) );
37143  while( pGroup->nCurrentPage>pGroup->nMaxPage && pGroup->pLruTail ){
37144    PgHdr1 *p = pGroup->pLruTail;
37145    assert( p->pCache->pGroup==pGroup );
37146    pcache1PinPage(p);
37147    pcache1RemoveFromHash(p);
37148    pcache1FreePage(p);
37149  }
37150}
37151
37152/*
37153** Discard all pages from cache pCache with a page number (key value)
37154** greater than or equal to iLimit. Any pinned pages that meet this
37155** criteria are unpinned before they are discarded.
37156**
37157** The PCache mutex must be held when this function is called.
37158*/
37159static void pcache1TruncateUnsafe(
37160  PCache1 *pCache,             /* The cache to truncate */
37161  unsigned int iLimit          /* Drop pages with this pgno or larger */
37162){
37163  TESTONLY( unsigned int nPage = 0; )  /* To assert pCache->nPage is correct */
37164  unsigned int h;
37165  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
37166  for(h=0; h<pCache->nHash; h++){
37167    PgHdr1 **pp = &pCache->apHash[h];
37168    PgHdr1 *pPage;
37169    while( (pPage = *pp)!=0 ){
37170      if( pPage->iKey>=iLimit ){
37171        pCache->nPage--;
37172        *pp = pPage->pNext;
37173        pcache1PinPage(pPage);
37174        pcache1FreePage(pPage);
37175      }else{
37176        pp = &pPage->pNext;
37177        TESTONLY( nPage++; )
37178      }
37179    }
37180  }
37181  assert( pCache->nPage==nPage );
37182}
37183
37184/******************************************************************************/
37185/******** sqlite3_pcache Methods **********************************************/
37186
37187/*
37188** Implementation of the sqlite3_pcache.xInit method.
37189*/
37190static int pcache1Init(void *NotUsed){
37191  UNUSED_PARAMETER(NotUsed);
37192  assert( pcache1.isInit==0 );
37193  memset(&pcache1, 0, sizeof(pcache1));
37194  if( sqlite3GlobalConfig.bCoreMutex ){
37195    pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
37196    pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM);
37197  }
37198  pcache1.grp.mxPinned = 10;
37199  pcache1.isInit = 1;
37200  return SQLITE_OK;
37201}
37202
37203/*
37204** Implementation of the sqlite3_pcache.xShutdown method.
37205** Note that the static mutex allocated in xInit does
37206** not need to be freed.
37207*/
37208static void pcache1Shutdown(void *NotUsed){
37209  UNUSED_PARAMETER(NotUsed);
37210  assert( pcache1.isInit!=0 );
37211  memset(&pcache1, 0, sizeof(pcache1));
37212}
37213
37214/*
37215** Implementation of the sqlite3_pcache.xCreate method.
37216**
37217** Allocate a new cache.
37218*/
37219static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
37220  PCache1 *pCache;      /* The newly created page cache */
37221  PGroup *pGroup;       /* The group the new page cache will belong to */
37222  int sz;               /* Bytes of memory required to allocate the new cache */
37223
37224  /*
37225  ** The seperateCache variable is true if each PCache has its own private
37226  ** PGroup.  In other words, separateCache is true for mode (1) where no
37227  ** mutexing is required.
37228  **
37229  **   *  Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
37230  **
37231  **   *  Always use a unified cache in single-threaded applications
37232  **
37233  **   *  Otherwise (if multi-threaded and ENABLE_MEMORY_MANAGEMENT is off)
37234  **      use separate caches (mode-1)
37235  */
37236#if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
37237  const int separateCache = 0;
37238#else
37239  int separateCache = sqlite3GlobalConfig.bCoreMutex>0;
37240#endif
37241
37242  assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
37243  assert( szExtra < 300 );
37244
37245  sz = sizeof(PCache1) + sizeof(PGroup)*separateCache;
37246  pCache = (PCache1 *)sqlite3MallocZero(sz);
37247  if( pCache ){
37248    if( separateCache ){
37249      pGroup = (PGroup*)&pCache[1];
37250      pGroup->mxPinned = 10;
37251    }else{
37252      pGroup = &pcache1.grp;
37253    }
37254    pCache->pGroup = pGroup;
37255    pCache->szPage = szPage;
37256    pCache->szExtra = szExtra;
37257    pCache->bPurgeable = (bPurgeable ? 1 : 0);
37258    if( bPurgeable ){
37259      pCache->nMin = 10;
37260      pcache1EnterMutex(pGroup);
37261      pGroup->nMinPage += pCache->nMin;
37262      pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
37263      pcache1LeaveMutex(pGroup);
37264    }
37265  }
37266  return (sqlite3_pcache *)pCache;
37267}
37268
37269/*
37270** Implementation of the sqlite3_pcache.xCachesize method.
37271**
37272** Configure the cache_size limit for a cache.
37273*/
37274static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
37275  PCache1 *pCache = (PCache1 *)p;
37276  if( pCache->bPurgeable ){
37277    PGroup *pGroup = pCache->pGroup;
37278    pcache1EnterMutex(pGroup);
37279    pGroup->nMaxPage += (nMax - pCache->nMax);
37280    pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
37281    pCache->nMax = nMax;
37282    pCache->n90pct = pCache->nMax*9/10;
37283    pcache1EnforceMaxPage(pGroup);
37284    pcache1LeaveMutex(pGroup);
37285  }
37286}
37287
37288/*
37289** Implementation of the sqlite3_pcache.xShrink method.
37290**
37291** Free up as much memory as possible.
37292*/
37293static void pcache1Shrink(sqlite3_pcache *p){
37294  PCache1 *pCache = (PCache1*)p;
37295  if( pCache->bPurgeable ){
37296    PGroup *pGroup = pCache->pGroup;
37297    int savedMaxPage;
37298    pcache1EnterMutex(pGroup);
37299    savedMaxPage = pGroup->nMaxPage;
37300    pGroup->nMaxPage = 0;
37301    pcache1EnforceMaxPage(pGroup);
37302    pGroup->nMaxPage = savedMaxPage;
37303    pcache1LeaveMutex(pGroup);
37304  }
37305}
37306
37307/*
37308** Implementation of the sqlite3_pcache.xPagecount method.
37309*/
37310static int pcache1Pagecount(sqlite3_pcache *p){
37311  int n;
37312  PCache1 *pCache = (PCache1*)p;
37313  pcache1EnterMutex(pCache->pGroup);
37314  n = pCache->nPage;
37315  pcache1LeaveMutex(pCache->pGroup);
37316  return n;
37317}
37318
37319/*
37320** Implementation of the sqlite3_pcache.xFetch method.
37321**
37322** Fetch a page by key value.
37323**
37324** Whether or not a new page may be allocated by this function depends on
37325** the value of the createFlag argument.  0 means do not allocate a new
37326** page.  1 means allocate a new page if space is easily available.  2
37327** means to try really hard to allocate a new page.
37328**
37329** For a non-purgeable cache (a cache used as the storage for an in-memory
37330** database) there is really no difference between createFlag 1 and 2.  So
37331** the calling function (pcache.c) will never have a createFlag of 1 on
37332** a non-purgeable cache.
37333**
37334** There are three different approaches to obtaining space for a page,
37335** depending on the value of parameter createFlag (which may be 0, 1 or 2).
37336**
37337**   1. Regardless of the value of createFlag, the cache is searched for a
37338**      copy of the requested page. If one is found, it is returned.
37339**
37340**   2. If createFlag==0 and the page is not already in the cache, NULL is
37341**      returned.
37342**
37343**   3. If createFlag is 1, and the page is not already in the cache, then
37344**      return NULL (do not allocate a new page) if any of the following
37345**      conditions are true:
37346**
37347**       (a) the number of pages pinned by the cache is greater than
37348**           PCache1.nMax, or
37349**
37350**       (b) the number of pages pinned by the cache is greater than
37351**           the sum of nMax for all purgeable caches, less the sum of
37352**           nMin for all other purgeable caches, or
37353**
37354**   4. If none of the first three conditions apply and the cache is marked
37355**      as purgeable, and if one of the following is true:
37356**
37357**       (a) The number of pages allocated for the cache is already
37358**           PCache1.nMax, or
37359**
37360**       (b) The number of pages allocated for all purgeable caches is
37361**           already equal to or greater than the sum of nMax for all
37362**           purgeable caches,
37363**
37364**       (c) The system is under memory pressure and wants to avoid
37365**           unnecessary pages cache entry allocations
37366**
37367**      then attempt to recycle a page from the LRU list. If it is the right
37368**      size, return the recycled buffer. Otherwise, free the buffer and
37369**      proceed to step 5.
37370**
37371**   5. Otherwise, allocate and return a new page buffer.
37372*/
37373static sqlite3_pcache_page *pcache1Fetch(
37374  sqlite3_pcache *p,
37375  unsigned int iKey,
37376  int createFlag
37377){
37378  unsigned int nPinned;
37379  PCache1 *pCache = (PCache1 *)p;
37380  PGroup *pGroup;
37381  PgHdr1 *pPage = 0;
37382
37383  assert( pCache->bPurgeable || createFlag!=1 );
37384  assert( pCache->bPurgeable || pCache->nMin==0 );
37385  assert( pCache->bPurgeable==0 || pCache->nMin==10 );
37386  assert( pCache->nMin==0 || pCache->bPurgeable );
37387  pcache1EnterMutex(pGroup = pCache->pGroup);
37388
37389  /* Step 1: Search the hash table for an existing entry. */
37390  if( pCache->nHash>0 ){
37391    unsigned int h = iKey % pCache->nHash;
37392    for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
37393  }
37394
37395  /* Step 2: Abort if no existing page is found and createFlag is 0 */
37396  if( pPage || createFlag==0 ){
37397    pcache1PinPage(pPage);
37398    goto fetch_out;
37399  }
37400
37401  /* The pGroup local variable will normally be initialized by the
37402  ** pcache1EnterMutex() macro above.  But if SQLITE_MUTEX_OMIT is defined,
37403  ** then pcache1EnterMutex() is a no-op, so we have to initialize the
37404  ** local variable here.  Delaying the initialization of pGroup is an
37405  ** optimization:  The common case is to exit the module before reaching
37406  ** this point.
37407  */
37408#ifdef SQLITE_MUTEX_OMIT
37409  pGroup = pCache->pGroup;
37410#endif
37411
37412  /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
37413  assert( pCache->nPage >= pCache->nRecyclable );
37414  nPinned = pCache->nPage - pCache->nRecyclable;
37415  assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
37416  assert( pCache->n90pct == pCache->nMax*9/10 );
37417  if( createFlag==1 && (
37418        nPinned>=pGroup->mxPinned
37419     || nPinned>=pCache->n90pct
37420     || pcache1UnderMemoryPressure(pCache)
37421  )){
37422    goto fetch_out;
37423  }
37424
37425  if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
37426    goto fetch_out;
37427  }
37428
37429  /* Step 4. Try to recycle a page. */
37430  if( pCache->bPurgeable && pGroup->pLruTail && (
37431         (pCache->nPage+1>=pCache->nMax)
37432      || pGroup->nCurrentPage>=pGroup->nMaxPage
37433      || pcache1UnderMemoryPressure(pCache)
37434  )){
37435    PCache1 *pOther;
37436    pPage = pGroup->pLruTail;
37437    pcache1RemoveFromHash(pPage);
37438    pcache1PinPage(pPage);
37439    pOther = pPage->pCache;
37440
37441    /* We want to verify that szPage and szExtra are the same for pOther
37442    ** and pCache.  Assert that we can verify this by comparing sums. */
37443    assert( (pCache->szPage & (pCache->szPage-1))==0 && pCache->szPage>=512 );
37444    assert( pCache->szExtra<512 );
37445    assert( (pOther->szPage & (pOther->szPage-1))==0 && pOther->szPage>=512 );
37446    assert( pOther->szExtra<512 );
37447
37448    if( pOther->szPage+pOther->szExtra != pCache->szPage+pCache->szExtra ){
37449      pcache1FreePage(pPage);
37450      pPage = 0;
37451    }else{
37452      pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable);
37453    }
37454  }
37455
37456  /* Step 5. If a usable page buffer has still not been found,
37457  ** attempt to allocate a new one.
37458  */
37459  if( !pPage ){
37460    if( createFlag==1 ) sqlite3BeginBenignMalloc();
37461    pPage = pcache1AllocPage(pCache);
37462    if( createFlag==1 ) sqlite3EndBenignMalloc();
37463  }
37464
37465  if( pPage ){
37466    unsigned int h = iKey % pCache->nHash;
37467    pCache->nPage++;
37468    pPage->iKey = iKey;
37469    pPage->pNext = pCache->apHash[h];
37470    pPage->pCache = pCache;
37471    pPage->pLruPrev = 0;
37472    pPage->pLruNext = 0;
37473    *(void **)pPage->page.pExtra = 0;
37474    pCache->apHash[h] = pPage;
37475  }
37476
37477fetch_out:
37478  if( pPage && iKey>pCache->iMaxKey ){
37479    pCache->iMaxKey = iKey;
37480  }
37481  pcache1LeaveMutex(pGroup);
37482  return &pPage->page;
37483}
37484
37485
37486/*
37487** Implementation of the sqlite3_pcache.xUnpin method.
37488**
37489** Mark a page as unpinned (eligible for asynchronous recycling).
37490*/
37491static void pcache1Unpin(
37492  sqlite3_pcache *p,
37493  sqlite3_pcache_page *pPg,
37494  int reuseUnlikely
37495){
37496  PCache1 *pCache = (PCache1 *)p;
37497  PgHdr1 *pPage = (PgHdr1 *)pPg;
37498  PGroup *pGroup = pCache->pGroup;
37499
37500  assert( pPage->pCache==pCache );
37501  pcache1EnterMutex(pGroup);
37502
37503  /* It is an error to call this function if the page is already
37504  ** part of the PGroup LRU list.
37505  */
37506  assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
37507  assert( pGroup->pLruHead!=pPage && pGroup->pLruTail!=pPage );
37508
37509  if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
37510    pcache1RemoveFromHash(pPage);
37511    pcache1FreePage(pPage);
37512  }else{
37513    /* Add the page to the PGroup LRU list. */
37514    if( pGroup->pLruHead ){
37515      pGroup->pLruHead->pLruPrev = pPage;
37516      pPage->pLruNext = pGroup->pLruHead;
37517      pGroup->pLruHead = pPage;
37518    }else{
37519      pGroup->pLruTail = pPage;
37520      pGroup->pLruHead = pPage;
37521    }
37522    pCache->nRecyclable++;
37523  }
37524
37525  pcache1LeaveMutex(pCache->pGroup);
37526}
37527
37528/*
37529** Implementation of the sqlite3_pcache.xRekey method.
37530*/
37531static void pcache1Rekey(
37532  sqlite3_pcache *p,
37533  sqlite3_pcache_page *pPg,
37534  unsigned int iOld,
37535  unsigned int iNew
37536){
37537  PCache1 *pCache = (PCache1 *)p;
37538  PgHdr1 *pPage = (PgHdr1 *)pPg;
37539  PgHdr1 **pp;
37540  unsigned int h;
37541  assert( pPage->iKey==iOld );
37542  assert( pPage->pCache==pCache );
37543
37544  pcache1EnterMutex(pCache->pGroup);
37545
37546  h = iOld%pCache->nHash;
37547  pp = &pCache->apHash[h];
37548  while( (*pp)!=pPage ){
37549    pp = &(*pp)->pNext;
37550  }
37551  *pp = pPage->pNext;
37552
37553  h = iNew%pCache->nHash;
37554  pPage->iKey = iNew;
37555  pPage->pNext = pCache->apHash[h];
37556  pCache->apHash[h] = pPage;
37557  if( iNew>pCache->iMaxKey ){
37558    pCache->iMaxKey = iNew;
37559  }
37560
37561  pcache1LeaveMutex(pCache->pGroup);
37562}
37563
37564/*
37565** Implementation of the sqlite3_pcache.xTruncate method.
37566**
37567** Discard all unpinned pages in the cache with a page number equal to
37568** or greater than parameter iLimit. Any pinned pages with a page number
37569** equal to or greater than iLimit are implicitly unpinned.
37570*/
37571static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
37572  PCache1 *pCache = (PCache1 *)p;
37573  pcache1EnterMutex(pCache->pGroup);
37574  if( iLimit<=pCache->iMaxKey ){
37575    pcache1TruncateUnsafe(pCache, iLimit);
37576    pCache->iMaxKey = iLimit-1;
37577  }
37578  pcache1LeaveMutex(pCache->pGroup);
37579}
37580
37581/*
37582** Implementation of the sqlite3_pcache.xDestroy method.
37583**
37584** Destroy a cache allocated using pcache1Create().
37585*/
37586static void pcache1Destroy(sqlite3_pcache *p){
37587  PCache1 *pCache = (PCache1 *)p;
37588  PGroup *pGroup = pCache->pGroup;
37589  assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
37590  pcache1EnterMutex(pGroup);
37591  pcache1TruncateUnsafe(pCache, 0);
37592  assert( pGroup->nMaxPage >= pCache->nMax );
37593  pGroup->nMaxPage -= pCache->nMax;
37594  assert( pGroup->nMinPage >= pCache->nMin );
37595  pGroup->nMinPage -= pCache->nMin;
37596  pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
37597  pcache1EnforceMaxPage(pGroup);
37598  pcache1LeaveMutex(pGroup);
37599  sqlite3_free(pCache->apHash);
37600  sqlite3_free(pCache);
37601}
37602
37603/*
37604** This function is called during initialization (sqlite3_initialize()) to
37605** install the default pluggable cache module, assuming the user has not
37606** already provided an alternative.
37607*/
37608SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
37609  static const sqlite3_pcache_methods2 defaultMethods = {
37610    1,                       /* iVersion */
37611    0,                       /* pArg */
37612    pcache1Init,             /* xInit */
37613    pcache1Shutdown,         /* xShutdown */
37614    pcache1Create,           /* xCreate */
37615    pcache1Cachesize,        /* xCachesize */
37616    pcache1Pagecount,        /* xPagecount */
37617    pcache1Fetch,            /* xFetch */
37618    pcache1Unpin,            /* xUnpin */
37619    pcache1Rekey,            /* xRekey */
37620    pcache1Truncate,         /* xTruncate */
37621    pcache1Destroy,          /* xDestroy */
37622    pcache1Shrink            /* xShrink */
37623  };
37624  sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
37625}
37626
37627#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
37628/*
37629** This function is called to free superfluous dynamically allocated memory
37630** held by the pager system. Memory in use by any SQLite pager allocated
37631** by the current thread may be sqlite3_free()ed.
37632**
37633** nReq is the number of bytes of memory required. Once this much has
37634** been released, the function returns. The return value is the total number
37635** of bytes of memory released.
37636*/
37637SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
37638  int nFree = 0;
37639  assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
37640  assert( sqlite3_mutex_notheld(pcache1.mutex) );
37641  if( pcache1.pStart==0 ){
37642    PgHdr1 *p;
37643    pcache1EnterMutex(&pcache1.grp);
37644    while( (nReq<0 || nFree<nReq) && ((p=pcache1.grp.pLruTail)!=0) ){
37645      nFree += pcache1MemSize(p->page.pBuf);
37646#ifdef SQLITE_PCACHE_SEPARATE_HEADER
37647      nFree += sqlite3MemSize(p);
37648#endif
37649      pcache1PinPage(p);
37650      pcache1RemoveFromHash(p);
37651      pcache1FreePage(p);
37652    }
37653    pcache1LeaveMutex(&pcache1.grp);
37654  }
37655  return nFree;
37656}
37657#endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
37658
37659#ifdef SQLITE_TEST
37660/*
37661** This function is used by test procedures to inspect the internal state
37662** of the global cache.
37663*/
37664SQLITE_PRIVATE void sqlite3PcacheStats(
37665  int *pnCurrent,      /* OUT: Total number of pages cached */
37666  int *pnMax,          /* OUT: Global maximum cache size */
37667  int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
37668  int *pnRecyclable    /* OUT: Total number of pages available for recycling */
37669){
37670  PgHdr1 *p;
37671  int nRecyclable = 0;
37672  for(p=pcache1.grp.pLruHead; p; p=p->pLruNext){
37673    nRecyclable++;
37674  }
37675  *pnCurrent = pcache1.grp.nCurrentPage;
37676  *pnMax = (int)pcache1.grp.nMaxPage;
37677  *pnMin = (int)pcache1.grp.nMinPage;
37678  *pnRecyclable = nRecyclable;
37679}
37680#endif
37681
37682/************** End of pcache1.c *********************************************/
37683/************** Begin file rowset.c ******************************************/
37684/*
37685** 2008 December 3
37686**
37687** The author disclaims copyright to this source code.  In place of
37688** a legal notice, here is a blessing:
37689**
37690**    May you do good and not evil.
37691**    May you find forgiveness for yourself and forgive others.
37692**    May you share freely, never taking more than you give.
37693**
37694*************************************************************************
37695**
37696** This module implements an object we call a "RowSet".
37697**
37698** The RowSet object is a collection of rowids.  Rowids
37699** are inserted into the RowSet in an arbitrary order.  Inserts
37700** can be intermixed with tests to see if a given rowid has been
37701** previously inserted into the RowSet.
37702**
37703** After all inserts are finished, it is possible to extract the
37704** elements of the RowSet in sorted order.  Once this extraction
37705** process has started, no new elements may be inserted.
37706**
37707** Hence, the primitive operations for a RowSet are:
37708**
37709**    CREATE
37710**    INSERT
37711**    TEST
37712**    SMALLEST
37713**    DESTROY
37714**
37715** The CREATE and DESTROY primitives are the constructor and destructor,
37716** obviously.  The INSERT primitive adds a new element to the RowSet.
37717** TEST checks to see if an element is already in the RowSet.  SMALLEST
37718** extracts the least value from the RowSet.
37719**
37720** The INSERT primitive might allocate additional memory.  Memory is
37721** allocated in chunks so most INSERTs do no allocation.  There is an
37722** upper bound on the size of allocated memory.  No memory is freed
37723** until DESTROY.
37724**
37725** The TEST primitive includes a "batch" number.  The TEST primitive
37726** will only see elements that were inserted before the last change
37727** in the batch number.  In other words, if an INSERT occurs between
37728** two TESTs where the TESTs have the same batch nubmer, then the
37729** value added by the INSERT will not be visible to the second TEST.
37730** The initial batch number is zero, so if the very first TEST contains
37731** a non-zero batch number, it will see all prior INSERTs.
37732**
37733** No INSERTs may occurs after a SMALLEST.  An assertion will fail if
37734** that is attempted.
37735**
37736** The cost of an INSERT is roughly constant.  (Sometime new memory
37737** has to be allocated on an INSERT.)  The cost of a TEST with a new
37738** batch number is O(NlogN) where N is the number of elements in the RowSet.
37739** The cost of a TEST using the same batch number is O(logN).  The cost
37740** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST
37741** primitives are constant time.  The cost of DESTROY is O(N).
37742**
37743** There is an added cost of O(N) when switching between TEST and
37744** SMALLEST primitives.
37745*/
37746
37747
37748/*
37749** Target size for allocation chunks.
37750*/
37751#define ROWSET_ALLOCATION_SIZE 1024
37752
37753/*
37754** The number of rowset entries per allocation chunk.
37755*/
37756#define ROWSET_ENTRY_PER_CHUNK  \
37757                       ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
37758
37759/*
37760** Each entry in a RowSet is an instance of the following object.
37761**
37762** This same object is reused to store a linked list of trees of RowSetEntry
37763** objects.  In that alternative use, pRight points to the next entry
37764** in the list, pLeft points to the tree, and v is unused.  The
37765** RowSet.pForest value points to the head of this forest list.
37766*/
37767struct RowSetEntry {
37768  i64 v;                        /* ROWID value for this entry */
37769  struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
37770  struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
37771};
37772
37773/*
37774** RowSetEntry objects are allocated in large chunks (instances of the
37775** following structure) to reduce memory allocation overhead.  The
37776** chunks are kept on a linked list so that they can be deallocated
37777** when the RowSet is destroyed.
37778*/
37779struct RowSetChunk {
37780  struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */
37781  struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
37782};
37783
37784/*
37785** A RowSet in an instance of the following structure.
37786**
37787** A typedef of this structure if found in sqliteInt.h.
37788*/
37789struct RowSet {
37790  struct RowSetChunk *pChunk;    /* List of all chunk allocations */
37791  sqlite3 *db;                   /* The database connection */
37792  struct RowSetEntry *pEntry;    /* List of entries using pRight */
37793  struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
37794  struct RowSetEntry *pFresh;    /* Source of new entry objects */
37795  struct RowSetEntry *pForest;   /* List of binary trees of entries */
37796  u16 nFresh;                    /* Number of objects on pFresh */
37797  u8 rsFlags;                    /* Various flags */
37798  u8 iBatch;                     /* Current insert batch */
37799};
37800
37801/*
37802** Allowed values for RowSet.rsFlags
37803*/
37804#define ROWSET_SORTED  0x01   /* True if RowSet.pEntry is sorted */
37805#define ROWSET_NEXT    0x02   /* True if sqlite3RowSetNext() has been called */
37806
37807/*
37808** Turn bulk memory into a RowSet object.  N bytes of memory
37809** are available at pSpace.  The db pointer is used as a memory context
37810** for any subsequent allocations that need to occur.
37811** Return a pointer to the new RowSet object.
37812**
37813** It must be the case that N is sufficient to make a Rowset.  If not
37814** an assertion fault occurs.
37815**
37816** If N is larger than the minimum, use the surplus as an initial
37817** allocation of entries available to be filled.
37818*/
37819SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
37820  RowSet *p;
37821  assert( N >= ROUND8(sizeof(*p)) );
37822  p = pSpace;
37823  p->pChunk = 0;
37824  p->db = db;
37825  p->pEntry = 0;
37826  p->pLast = 0;
37827  p->pForest = 0;
37828  p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
37829  p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
37830  p->rsFlags = ROWSET_SORTED;
37831  p->iBatch = 0;
37832  return p;
37833}
37834
37835/*
37836** Deallocate all chunks from a RowSet.  This frees all memory that
37837** the RowSet has allocated over its lifetime.  This routine is
37838** the destructor for the RowSet.
37839*/
37840SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
37841  struct RowSetChunk *pChunk, *pNextChunk;
37842  for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
37843    pNextChunk = pChunk->pNextChunk;
37844    sqlite3DbFree(p->db, pChunk);
37845  }
37846  p->pChunk = 0;
37847  p->nFresh = 0;
37848  p->pEntry = 0;
37849  p->pLast = 0;
37850  p->pForest = 0;
37851  p->rsFlags = ROWSET_SORTED;
37852}
37853
37854/*
37855** Allocate a new RowSetEntry object that is associated with the
37856** given RowSet.  Return a pointer to the new and completely uninitialized
37857** objected.
37858**
37859** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
37860** routine returns NULL.
37861*/
37862static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
37863  assert( p!=0 );
37864  if( p->nFresh==0 ){
37865    struct RowSetChunk *pNew;
37866    pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
37867    if( pNew==0 ){
37868      return 0;
37869    }
37870    pNew->pNextChunk = p->pChunk;
37871    p->pChunk = pNew;
37872    p->pFresh = pNew->aEntry;
37873    p->nFresh = ROWSET_ENTRY_PER_CHUNK;
37874  }
37875  p->nFresh--;
37876  return p->pFresh++;
37877}
37878
37879/*
37880** Insert a new value into a RowSet.
37881**
37882** The mallocFailed flag of the database connection is set if a
37883** memory allocation fails.
37884*/
37885SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
37886  struct RowSetEntry *pEntry;  /* The new entry */
37887  struct RowSetEntry *pLast;   /* The last prior entry */
37888
37889  /* This routine is never called after sqlite3RowSetNext() */
37890  assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
37891
37892  pEntry = rowSetEntryAlloc(p);
37893  if( pEntry==0 ) return;
37894  pEntry->v = rowid;
37895  pEntry->pRight = 0;
37896  pLast = p->pLast;
37897  if( pLast ){
37898    if( (p->rsFlags & ROWSET_SORTED)!=0 && rowid<=pLast->v ){
37899      p->rsFlags &= ~ROWSET_SORTED;
37900    }
37901    pLast->pRight = pEntry;
37902  }else{
37903    p->pEntry = pEntry;
37904  }
37905  p->pLast = pEntry;
37906}
37907
37908/*
37909** Merge two lists of RowSetEntry objects.  Remove duplicates.
37910**
37911** The input lists are connected via pRight pointers and are
37912** assumed to each already be in sorted order.
37913*/
37914static struct RowSetEntry *rowSetEntryMerge(
37915  struct RowSetEntry *pA,    /* First sorted list to be merged */
37916  struct RowSetEntry *pB     /* Second sorted list to be merged */
37917){
37918  struct RowSetEntry head;
37919  struct RowSetEntry *pTail;
37920
37921  pTail = &head;
37922  while( pA && pB ){
37923    assert( pA->pRight==0 || pA->v<=pA->pRight->v );
37924    assert( pB->pRight==0 || pB->v<=pB->pRight->v );
37925    if( pA->v<pB->v ){
37926      pTail->pRight = pA;
37927      pA = pA->pRight;
37928      pTail = pTail->pRight;
37929    }else if( pB->v<pA->v ){
37930      pTail->pRight = pB;
37931      pB = pB->pRight;
37932      pTail = pTail->pRight;
37933    }else{
37934      pA = pA->pRight;
37935    }
37936  }
37937  if( pA ){
37938    assert( pA->pRight==0 || pA->v<=pA->pRight->v );
37939    pTail->pRight = pA;
37940  }else{
37941    assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
37942    pTail->pRight = pB;
37943  }
37944  return head.pRight;
37945}
37946
37947/*
37948** Sort all elements on the list of RowSetEntry objects into order of
37949** increasing v.
37950*/
37951static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
37952  unsigned int i;
37953  struct RowSetEntry *pNext, *aBucket[40];
37954
37955  memset(aBucket, 0, sizeof(aBucket));
37956  while( pIn ){
37957    pNext = pIn->pRight;
37958    pIn->pRight = 0;
37959    for(i=0; aBucket[i]; i++){
37960      pIn = rowSetEntryMerge(aBucket[i], pIn);
37961      aBucket[i] = 0;
37962    }
37963    aBucket[i] = pIn;
37964    pIn = pNext;
37965  }
37966  pIn = 0;
37967  for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
37968    pIn = rowSetEntryMerge(pIn, aBucket[i]);
37969  }
37970  return pIn;
37971}
37972
37973
37974/*
37975** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
37976** Convert this tree into a linked list connected by the pRight pointers
37977** and return pointers to the first and last elements of the new list.
37978*/
37979static void rowSetTreeToList(
37980  struct RowSetEntry *pIn,         /* Root of the input tree */
37981  struct RowSetEntry **ppFirst,    /* Write head of the output list here */
37982  struct RowSetEntry **ppLast      /* Write tail of the output list here */
37983){
37984  assert( pIn!=0 );
37985  if( pIn->pLeft ){
37986    struct RowSetEntry *p;
37987    rowSetTreeToList(pIn->pLeft, ppFirst, &p);
37988    p->pRight = pIn;
37989  }else{
37990    *ppFirst = pIn;
37991  }
37992  if( pIn->pRight ){
37993    rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
37994  }else{
37995    *ppLast = pIn;
37996  }
37997  assert( (*ppLast)->pRight==0 );
37998}
37999
38000
38001/*
38002** Convert a sorted list of elements (connected by pRight) into a binary
38003** tree with depth of iDepth.  A depth of 1 means the tree contains a single
38004** node taken from the head of *ppList.  A depth of 2 means a tree with
38005** three nodes.  And so forth.
38006**
38007** Use as many entries from the input list as required and update the
38008** *ppList to point to the unused elements of the list.  If the input
38009** list contains too few elements, then construct an incomplete tree
38010** and leave *ppList set to NULL.
38011**
38012** Return a pointer to the root of the constructed binary tree.
38013*/
38014static struct RowSetEntry *rowSetNDeepTree(
38015  struct RowSetEntry **ppList,
38016  int iDepth
38017){
38018  struct RowSetEntry *p;         /* Root of the new tree */
38019  struct RowSetEntry *pLeft;     /* Left subtree */
38020  if( *ppList==0 ){
38021    return 0;
38022  }
38023  if( iDepth==1 ){
38024    p = *ppList;
38025    *ppList = p->pRight;
38026    p->pLeft = p->pRight = 0;
38027    return p;
38028  }
38029  pLeft = rowSetNDeepTree(ppList, iDepth-1);
38030  p = *ppList;
38031  if( p==0 ){
38032    return pLeft;
38033  }
38034  p->pLeft = pLeft;
38035  *ppList = p->pRight;
38036  p->pRight = rowSetNDeepTree(ppList, iDepth-1);
38037  return p;
38038}
38039
38040/*
38041** Convert a sorted list of elements into a binary tree. Make the tree
38042** as deep as it needs to be in order to contain the entire list.
38043*/
38044static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
38045  int iDepth;           /* Depth of the tree so far */
38046  struct RowSetEntry *p;       /* Current tree root */
38047  struct RowSetEntry *pLeft;   /* Left subtree */
38048
38049  assert( pList!=0 );
38050  p = pList;
38051  pList = p->pRight;
38052  p->pLeft = p->pRight = 0;
38053  for(iDepth=1; pList; iDepth++){
38054    pLeft = p;
38055    p = pList;
38056    pList = p->pRight;
38057    p->pLeft = pLeft;
38058    p->pRight = rowSetNDeepTree(&pList, iDepth);
38059  }
38060  return p;
38061}
38062
38063/*
38064** Take all the entries on p->pEntry and on the trees in p->pForest and
38065** sort them all together into one big ordered list on p->pEntry.
38066**
38067** This routine should only be called once in the life of a RowSet.
38068*/
38069static void rowSetToList(RowSet *p){
38070
38071  /* This routine is called only once */
38072  assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
38073
38074  if( (p->rsFlags & ROWSET_SORTED)==0 ){
38075    p->pEntry = rowSetEntrySort(p->pEntry);
38076  }
38077
38078  /* While this module could theoretically support it, sqlite3RowSetNext()
38079  ** is never called after sqlite3RowSetText() for the same RowSet.  So
38080  ** there is never a forest to deal with.  Should this change, simply
38081  ** remove the assert() and the #if 0. */
38082  assert( p->pForest==0 );
38083#if 0
38084  while( p->pForest ){
38085    struct RowSetEntry *pTree = p->pForest->pLeft;
38086    if( pTree ){
38087      struct RowSetEntry *pHead, *pTail;
38088      rowSetTreeToList(pTree, &pHead, &pTail);
38089      p->pEntry = rowSetEntryMerge(p->pEntry, pHead);
38090    }
38091    p->pForest = p->pForest->pRight;
38092  }
38093#endif
38094  p->rsFlags |= ROWSET_NEXT;  /* Verify this routine is never called again */
38095}
38096
38097/*
38098** Extract the smallest element from the RowSet.
38099** Write the element into *pRowid.  Return 1 on success.  Return
38100** 0 if the RowSet is already empty.
38101**
38102** After this routine has been called, the sqlite3RowSetInsert()
38103** routine may not be called again.
38104*/
38105SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
38106  assert( p!=0 );
38107
38108  /* Merge the forest into a single sorted list on first call */
38109  if( (p->rsFlags & ROWSET_NEXT)==0 ) rowSetToList(p);
38110
38111  /* Return the next entry on the list */
38112  if( p->pEntry ){
38113    *pRowid = p->pEntry->v;
38114    p->pEntry = p->pEntry->pRight;
38115    if( p->pEntry==0 ){
38116      sqlite3RowSetClear(p);
38117    }
38118    return 1;
38119  }else{
38120    return 0;
38121  }
38122}
38123
38124/*
38125** Check to see if element iRowid was inserted into the rowset as
38126** part of any insert batch prior to iBatch.  Return 1 or 0.
38127**
38128** If this is the first test of a new batch and if there exist entires
38129** on pRowSet->pEntry, then sort those entires into the forest at
38130** pRowSet->pForest so that they can be tested.
38131*/
38132SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlite3_int64 iRowid){
38133  struct RowSetEntry *p, *pTree;
38134
38135  /* This routine is never called after sqlite3RowSetNext() */
38136  assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
38137
38138  /* Sort entries into the forest on the first test of a new batch
38139  */
38140  if( iBatch!=pRowSet->iBatch ){
38141    p = pRowSet->pEntry;
38142    if( p ){
38143      struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
38144      if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){
38145        p = rowSetEntrySort(p);
38146      }
38147      for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
38148        ppPrevTree = &pTree->pRight;
38149        if( pTree->pLeft==0 ){
38150          pTree->pLeft = rowSetListToTree(p);
38151          break;
38152        }else{
38153          struct RowSetEntry *pAux, *pTail;
38154          rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
38155          pTree->pLeft = 0;
38156          p = rowSetEntryMerge(pAux, p);
38157        }
38158      }
38159      if( pTree==0 ){
38160        *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
38161        if( pTree ){
38162          pTree->v = 0;
38163          pTree->pRight = 0;
38164          pTree->pLeft = rowSetListToTree(p);
38165        }
38166      }
38167      pRowSet->pEntry = 0;
38168      pRowSet->pLast = 0;
38169      pRowSet->rsFlags |= ROWSET_SORTED;
38170    }
38171    pRowSet->iBatch = iBatch;
38172  }
38173
38174  /* Test to see if the iRowid value appears anywhere in the forest.
38175  ** Return 1 if it does and 0 if not.
38176  */
38177  for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
38178    p = pTree->pLeft;
38179    while( p ){
38180      if( p->v<iRowid ){
38181        p = p->pRight;
38182      }else if( p->v>iRowid ){
38183        p = p->pLeft;
38184      }else{
38185        return 1;
38186      }
38187    }
38188  }
38189  return 0;
38190}
38191
38192/************** End of rowset.c **********************************************/
38193/************** Begin file pager.c *******************************************/
38194/*
38195** 2001 September 15
38196**
38197** The author disclaims copyright to this source code.  In place of
38198** a legal notice, here is a blessing:
38199**
38200**    May you do good and not evil.
38201**    May you find forgiveness for yourself and forgive others.
38202**    May you share freely, never taking more than you give.
38203**
38204*************************************************************************
38205** This is the implementation of the page cache subsystem or "pager".
38206**
38207** The pager is used to access a database disk file.  It implements
38208** atomic commit and rollback through the use of a journal file that
38209** is separate from the database file.  The pager also implements file
38210** locking to prevent two processes from writing the same database
38211** file simultaneously, or one process from reading the database while
38212** another is writing.
38213*/
38214#ifndef SQLITE_OMIT_DISKIO
38215/************** Include wal.h in the middle of pager.c ***********************/
38216/************** Begin file wal.h *********************************************/
38217/*
38218** 2010 February 1
38219**
38220** The author disclaims copyright to this source code.  In place of
38221** a legal notice, here is a blessing:
38222**
38223**    May you do good and not evil.
38224**    May you find forgiveness for yourself and forgive others.
38225**    May you share freely, never taking more than you give.
38226**
38227*************************************************************************
38228** This header file defines the interface to the write-ahead logging
38229** system. Refer to the comments below and the header comment attached to
38230** the implementation of each function in log.c for further details.
38231*/
38232
38233#ifndef _WAL_H_
38234#define _WAL_H_
38235
38236
38237/* Additional values that can be added to the sync_flags argument of
38238** sqlite3WalFrames():
38239*/
38240#define WAL_SYNC_TRANSACTIONS  0x20   /* Sync at the end of each transaction */
38241#define SQLITE_SYNC_MASK       0x13   /* Mask off the SQLITE_SYNC_* values */
38242
38243#ifdef SQLITE_OMIT_WAL
38244# define sqlite3WalOpen(x,y,z)                   0
38245# define sqlite3WalLimit(x,y)
38246# define sqlite3WalClose(w,x,y,z)                0
38247# define sqlite3WalBeginReadTransaction(y,z)     0
38248# define sqlite3WalEndReadTransaction(z)
38249# define sqlite3WalDbsize(y)                     0
38250# define sqlite3WalBeginWriteTransaction(y)      0
38251# define sqlite3WalEndWriteTransaction(x)        0
38252# define sqlite3WalUndo(x,y,z)                   0
38253# define sqlite3WalSavepoint(y,z)
38254# define sqlite3WalSavepointUndo(y,z)            0
38255# define sqlite3WalFrames(u,v,w,x,y,z)           0
38256# define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
38257# define sqlite3WalCallback(z)                   0
38258# define sqlite3WalExclusiveMode(y,z)            0
38259# define sqlite3WalHeapMemory(z)                 0
38260# define sqlite3WalFramesize(z)                  0
38261# define sqlite3WalFindFrame(x,y,z)              0
38262#else
38263
38264#define WAL_SAVEPOINT_NDATA 4
38265
38266/* Connection to a write-ahead log (WAL) file.
38267** There is one object of this type for each pager.
38268*/
38269typedef struct Wal Wal;
38270
38271/* Open and close a connection to a write-ahead log. */
38272SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
38273SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
38274
38275/* Set the limiting size of a WAL file. */
38276SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
38277
38278/* Used by readers to open (lock) and close (unlock) a snapshot.  A
38279** snapshot is like a read-transaction.  It is the state of the database
38280** at an instant in time.  sqlite3WalOpenSnapshot gets a read lock and
38281** preserves the current state even if the other threads or processes
38282** write to or checkpoint the WAL.  sqlite3WalCloseSnapshot() closes the
38283** transaction and releases the lock.
38284*/
38285SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
38286SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
38287
38288/* Read a page from the write-ahead log, if it is present. */
38289SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *);
38290SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *);
38291
38292/* If the WAL is not empty, return the size of the database. */
38293SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
38294
38295/* Obtain or release the WRITER lock. */
38296SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
38297SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
38298
38299/* Undo any frames written (but not committed) to the log */
38300SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
38301
38302/* Return an integer that records the current (uncommitted) write
38303** position in the WAL */
38304SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
38305
38306/* Move the write position of the WAL back to iFrame.  Called in
38307** response to a ROLLBACK TO command. */
38308SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
38309
38310/* Write a frame or frames to the log. */
38311SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
38312
38313/* Copy pages from the log to the database file */
38314SQLITE_PRIVATE int sqlite3WalCheckpoint(
38315  Wal *pWal,                      /* Write-ahead log connection */
38316  int eMode,                      /* One of PASSIVE, FULL and RESTART */
38317  int (*xBusy)(void*),            /* Function to call when busy */
38318  void *pBusyArg,                 /* Context argument for xBusyHandler */
38319  int sync_flags,                 /* Flags to sync db file with (or 0) */
38320  int nBuf,                       /* Size of buffer nBuf */
38321  u8 *zBuf,                       /* Temporary buffer to use */
38322  int *pnLog,                     /* OUT: Number of frames in WAL */
38323  int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
38324);
38325
38326/* Return the value to pass to a sqlite3_wal_hook callback, the
38327** number of frames in the WAL at the point of the last commit since
38328** sqlite3WalCallback() was called.  If no commits have occurred since
38329** the last call, then return 0.
38330*/
38331SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
38332
38333/* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
38334** by the pager layer on the database file.
38335*/
38336SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
38337
38338/* Return true if the argument is non-NULL and the WAL module is using
38339** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
38340** WAL module is using shared-memory, return false.
38341*/
38342SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
38343
38344#ifdef SQLITE_ENABLE_ZIPVFS
38345/* If the WAL file is not empty, return the number of bytes of content
38346** stored in each frame (i.e. the db page-size when the WAL was created).
38347*/
38348SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
38349#endif
38350
38351#endif /* ifndef SQLITE_OMIT_WAL */
38352#endif /* _WAL_H_ */
38353
38354/************** End of wal.h *************************************************/
38355/************** Continuing where we left off in pager.c **********************/
38356
38357
38358/******************* NOTES ON THE DESIGN OF THE PAGER ************************
38359**
38360** This comment block describes invariants that hold when using a rollback
38361** journal.  These invariants do not apply for journal_mode=WAL,
38362** journal_mode=MEMORY, or journal_mode=OFF.
38363**
38364** Within this comment block, a page is deemed to have been synced
38365** automatically as soon as it is written when PRAGMA synchronous=OFF.
38366** Otherwise, the page is not synced until the xSync method of the VFS
38367** is called successfully on the file containing the page.
38368**
38369** Definition:  A page of the database file is said to be "overwriteable" if
38370** one or more of the following are true about the page:
38371**
38372**     (a)  The original content of the page as it was at the beginning of
38373**          the transaction has been written into the rollback journal and
38374**          synced.
38375**
38376**     (b)  The page was a freelist leaf page at the start of the transaction.
38377**
38378**     (c)  The page number is greater than the largest page that existed in
38379**          the database file at the start of the transaction.
38380**
38381** (1) A page of the database file is never overwritten unless one of the
38382**     following are true:
38383**
38384**     (a) The page and all other pages on the same sector are overwriteable.
38385**
38386**     (b) The atomic page write optimization is enabled, and the entire
38387**         transaction other than the update of the transaction sequence
38388**         number consists of a single page change.
38389**
38390** (2) The content of a page written into the rollback journal exactly matches
38391**     both the content in the database when the rollback journal was written
38392**     and the content in the database at the beginning of the current
38393**     transaction.
38394**
38395** (3) Writes to the database file are an integer multiple of the page size
38396**     in length and are aligned on a page boundary.
38397**
38398** (4) Reads from the database file are either aligned on a page boundary and
38399**     an integer multiple of the page size in length or are taken from the
38400**     first 100 bytes of the database file.
38401**
38402** (5) All writes to the database file are synced prior to the rollback journal
38403**     being deleted, truncated, or zeroed.
38404**
38405** (6) If a master journal file is used, then all writes to the database file
38406**     are synced prior to the master journal being deleted.
38407**
38408** Definition: Two databases (or the same database at two points it time)
38409** are said to be "logically equivalent" if they give the same answer to
38410** all queries.  Note in particular the content of freelist leaf
38411** pages can be changed arbitarily without effecting the logical equivalence
38412** of the database.
38413**
38414** (7) At any time, if any subset, including the empty set and the total set,
38415**     of the unsynced changes to a rollback journal are removed and the
38416**     journal is rolled back, the resulting database file will be logical
38417**     equivalent to the database file at the beginning of the transaction.
38418**
38419** (8) When a transaction is rolled back, the xTruncate method of the VFS
38420**     is called to restore the database file to the same size it was at
38421**     the beginning of the transaction.  (In some VFSes, the xTruncate
38422**     method is a no-op, but that does not change the fact the SQLite will
38423**     invoke it.)
38424**
38425** (9) Whenever the database file is modified, at least one bit in the range
38426**     of bytes from 24 through 39 inclusive will be changed prior to releasing
38427**     the EXCLUSIVE lock, thus signaling other connections on the same
38428**     database to flush their caches.
38429**
38430** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
38431**      than one billion transactions.
38432**
38433** (11) A database file is well-formed at the beginning and at the conclusion
38434**      of every transaction.
38435**
38436** (12) An EXCLUSIVE lock is held on the database file when writing to
38437**      the database file.
38438**
38439** (13) A SHARED lock is held on the database file while reading any
38440**      content out of the database file.
38441**
38442******************************************************************************/
38443
38444/*
38445** Macros for troubleshooting.  Normally turned off
38446*/
38447#if 0
38448int sqlite3PagerTrace=1;  /* True to enable tracing */
38449#define sqlite3DebugPrintf printf
38450#define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
38451#else
38452#define PAGERTRACE(X)
38453#endif
38454
38455/*
38456** The following two macros are used within the PAGERTRACE() macros above
38457** to print out file-descriptors.
38458**
38459** PAGERID() takes a pointer to a Pager struct as its argument. The
38460** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
38461** struct as its argument.
38462*/
38463#define PAGERID(p) ((int)(p->fd))
38464#define FILEHANDLEID(fd) ((int)fd)
38465
38466/*
38467** The Pager.eState variable stores the current 'state' of a pager. A
38468** pager may be in any one of the seven states shown in the following
38469** state diagram.
38470**
38471**                            OPEN <------+------+
38472**                              |         |      |
38473**                              V         |      |
38474**               +---------> READER-------+      |
38475**               |              |                |
38476**               |              V                |
38477**               |<-------WRITER_LOCKED------> ERROR
38478**               |              |                ^
38479**               |              V                |
38480**               |<------WRITER_CACHEMOD-------->|
38481**               |              |                |
38482**               |              V                |
38483**               |<-------WRITER_DBMOD---------->|
38484**               |              |                |
38485**               |              V                |
38486**               +<------WRITER_FINISHED-------->+
38487**
38488**
38489** List of state transitions and the C [function] that performs each:
38490**
38491**   OPEN              -> READER              [sqlite3PagerSharedLock]
38492**   READER            -> OPEN                [pager_unlock]
38493**
38494**   READER            -> WRITER_LOCKED       [sqlite3PagerBegin]
38495**   WRITER_LOCKED     -> WRITER_CACHEMOD     [pager_open_journal]
38496**   WRITER_CACHEMOD   -> WRITER_DBMOD        [syncJournal]
38497**   WRITER_DBMOD      -> WRITER_FINISHED     [sqlite3PagerCommitPhaseOne]
38498**   WRITER_***        -> READER              [pager_end_transaction]
38499**
38500**   WRITER_***        -> ERROR               [pager_error]
38501**   ERROR             -> OPEN                [pager_unlock]
38502**
38503**
38504**  OPEN:
38505**
38506**    The pager starts up in this state. Nothing is guaranteed in this
38507**    state - the file may or may not be locked and the database size is
38508**    unknown. The database may not be read or written.
38509**
38510**    * No read or write transaction is active.
38511**    * Any lock, or no lock at all, may be held on the database file.
38512**    * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
38513**
38514**  READER:
38515**
38516**    In this state all the requirements for reading the database in
38517**    rollback (non-WAL) mode are met. Unless the pager is (or recently
38518**    was) in exclusive-locking mode, a user-level read transaction is
38519**    open. The database size is known in this state.
38520**
38521**    A connection running with locking_mode=normal enters this state when
38522**    it opens a read-transaction on the database and returns to state
38523**    OPEN after the read-transaction is completed. However a connection
38524**    running in locking_mode=exclusive (including temp databases) remains in
38525**    this state even after the read-transaction is closed. The only way
38526**    a locking_mode=exclusive connection can transition from READER to OPEN
38527**    is via the ERROR state (see below).
38528**
38529**    * A read transaction may be active (but a write-transaction cannot).
38530**    * A SHARED or greater lock is held on the database file.
38531**    * The dbSize variable may be trusted (even if a user-level read
38532**      transaction is not active). The dbOrigSize and dbFileSize variables
38533**      may not be trusted at this point.
38534**    * If the database is a WAL database, then the WAL connection is open.
38535**    * Even if a read-transaction is not open, it is guaranteed that
38536**      there is no hot-journal in the file-system.
38537**
38538**  WRITER_LOCKED:
38539**
38540**    The pager moves to this state from READER when a write-transaction
38541**    is first opened on the database. In WRITER_LOCKED state, all locks
38542**    required to start a write-transaction are held, but no actual
38543**    modifications to the cache or database have taken place.
38544**
38545**    In rollback mode, a RESERVED or (if the transaction was opened with
38546**    BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
38547**    moving to this state, but the journal file is not written to or opened
38548**    to in this state. If the transaction is committed or rolled back while
38549**    in WRITER_LOCKED state, all that is required is to unlock the database
38550**    file.
38551**
38552**    IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
38553**    If the connection is running with locking_mode=exclusive, an attempt
38554**    is made to obtain an EXCLUSIVE lock on the database file.
38555**
38556**    * A write transaction is active.
38557**    * If the connection is open in rollback-mode, a RESERVED or greater
38558**      lock is held on the database file.
38559**    * If the connection is open in WAL-mode, a WAL write transaction
38560**      is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
38561**      called).
38562**    * The dbSize, dbOrigSize and dbFileSize variables are all valid.
38563**    * The contents of the pager cache have not been modified.
38564**    * The journal file may or may not be open.
38565**    * Nothing (not even the first header) has been written to the journal.
38566**
38567**  WRITER_CACHEMOD:
38568**
38569**    A pager moves from WRITER_LOCKED state to this state when a page is
38570**    first modified by the upper layer. In rollback mode the journal file
38571**    is opened (if it is not already open) and a header written to the
38572**    start of it. The database file on disk has not been modified.
38573**
38574**    * A write transaction is active.
38575**    * A RESERVED or greater lock is held on the database file.
38576**    * The journal file is open and the first header has been written
38577**      to it, but the header has not been synced to disk.
38578**    * The contents of the page cache have been modified.
38579**
38580**  WRITER_DBMOD:
38581**
38582**    The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
38583**    when it modifies the contents of the database file. WAL connections
38584**    never enter this state (since they do not modify the database file,
38585**    just the log file).
38586**
38587**    * A write transaction is active.
38588**    * An EXCLUSIVE or greater lock is held on the database file.
38589**    * The journal file is open and the first header has been written
38590**      and synced to disk.
38591**    * The contents of the page cache have been modified (and possibly
38592**      written to disk).
38593**
38594**  WRITER_FINISHED:
38595**
38596**    It is not possible for a WAL connection to enter this state.
38597**
38598**    A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
38599**    state after the entire transaction has been successfully written into the
38600**    database file. In this state the transaction may be committed simply
38601**    by finalizing the journal file. Once in WRITER_FINISHED state, it is
38602**    not possible to modify the database further. At this point, the upper
38603**    layer must either commit or rollback the transaction.
38604**
38605**    * A write transaction is active.
38606**    * An EXCLUSIVE or greater lock is held on the database file.
38607**    * All writing and syncing of journal and database data has finished.
38608**      If no error occurred, all that remains is to finalize the journal to
38609**      commit the transaction. If an error did occur, the caller will need
38610**      to rollback the transaction.
38611**
38612**  ERROR:
38613**
38614**    The ERROR state is entered when an IO or disk-full error (including
38615**    SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
38616**    difficult to be sure that the in-memory pager state (cache contents,
38617**    db size etc.) are consistent with the contents of the file-system.
38618**
38619**    Temporary pager files may enter the ERROR state, but in-memory pagers
38620**    cannot.
38621**
38622**    For example, if an IO error occurs while performing a rollback,
38623**    the contents of the page-cache may be left in an inconsistent state.
38624**    At this point it would be dangerous to change back to READER state
38625**    (as usually happens after a rollback). Any subsequent readers might
38626**    report database corruption (due to the inconsistent cache), and if
38627**    they upgrade to writers, they may inadvertently corrupt the database
38628**    file. To avoid this hazard, the pager switches into the ERROR state
38629**    instead of READER following such an error.
38630**
38631**    Once it has entered the ERROR state, any attempt to use the pager
38632**    to read or write data returns an error. Eventually, once all
38633**    outstanding transactions have been abandoned, the pager is able to
38634**    transition back to OPEN state, discarding the contents of the
38635**    page-cache and any other in-memory state at the same time. Everything
38636**    is reloaded from disk (and, if necessary, hot-journal rollback peformed)
38637**    when a read-transaction is next opened on the pager (transitioning
38638**    the pager into READER state). At that point the system has recovered
38639**    from the error.
38640**
38641**    Specifically, the pager jumps into the ERROR state if:
38642**
38643**      1. An error occurs while attempting a rollback. This happens in
38644**         function sqlite3PagerRollback().
38645**
38646**      2. An error occurs while attempting to finalize a journal file
38647**         following a commit in function sqlite3PagerCommitPhaseTwo().
38648**
38649**      3. An error occurs while attempting to write to the journal or
38650**         database file in function pagerStress() in order to free up
38651**         memory.
38652**
38653**    In other cases, the error is returned to the b-tree layer. The b-tree
38654**    layer then attempts a rollback operation. If the error condition
38655**    persists, the pager enters the ERROR state via condition (1) above.
38656**
38657**    Condition (3) is necessary because it can be triggered by a read-only
38658**    statement executed within a transaction. In this case, if the error
38659**    code were simply returned to the user, the b-tree layer would not
38660**    automatically attempt a rollback, as it assumes that an error in a
38661**    read-only statement cannot leave the pager in an internally inconsistent
38662**    state.
38663**
38664**    * The Pager.errCode variable is set to something other than SQLITE_OK.
38665**    * There are one or more outstanding references to pages (after the
38666**      last reference is dropped the pager should move back to OPEN state).
38667**    * The pager is not an in-memory pager.
38668**
38669**
38670** Notes:
38671**
38672**   * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
38673**     connection is open in WAL mode. A WAL connection is always in one
38674**     of the first four states.
38675**
38676**   * Normally, a connection open in exclusive mode is never in PAGER_OPEN
38677**     state. There are two exceptions: immediately after exclusive-mode has
38678**     been turned on (and before any read or write transactions are
38679**     executed), and when the pager is leaving the "error state".
38680**
38681**   * See also: assert_pager_state().
38682*/
38683#define PAGER_OPEN                  0
38684#define PAGER_READER                1
38685#define PAGER_WRITER_LOCKED         2
38686#define PAGER_WRITER_CACHEMOD       3
38687#define PAGER_WRITER_DBMOD          4
38688#define PAGER_WRITER_FINISHED       5
38689#define PAGER_ERROR                 6
38690
38691/*
38692** The Pager.eLock variable is almost always set to one of the
38693** following locking-states, according to the lock currently held on
38694** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
38695** This variable is kept up to date as locks are taken and released by
38696** the pagerLockDb() and pagerUnlockDb() wrappers.
38697**
38698** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
38699** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
38700** the operation was successful. In these circumstances pagerLockDb() and
38701** pagerUnlockDb() take a conservative approach - eLock is always updated
38702** when unlocking the file, and only updated when locking the file if the
38703** VFS call is successful. This way, the Pager.eLock variable may be set
38704** to a less exclusive (lower) value than the lock that is actually held
38705** at the system level, but it is never set to a more exclusive value.
38706**
38707** This is usually safe. If an xUnlock fails or appears to fail, there may
38708** be a few redundant xLock() calls or a lock may be held for longer than
38709** required, but nothing really goes wrong.
38710**
38711** The exception is when the database file is unlocked as the pager moves
38712** from ERROR to OPEN state. At this point there may be a hot-journal file
38713** in the file-system that needs to be rolled back (as part of a OPEN->SHARED
38714** transition, by the same pager or any other). If the call to xUnlock()
38715** fails at this point and the pager is left holding an EXCLUSIVE lock, this
38716** can confuse the call to xCheckReservedLock() call made later as part
38717** of hot-journal detection.
38718**
38719** xCheckReservedLock() is defined as returning true "if there is a RESERVED
38720** lock held by this process or any others". So xCheckReservedLock may
38721** return true because the caller itself is holding an EXCLUSIVE lock (but
38722** doesn't know it because of a previous error in xUnlock). If this happens
38723** a hot-journal may be mistaken for a journal being created by an active
38724** transaction in another process, causing SQLite to read from the database
38725** without rolling it back.
38726**
38727** To work around this, if a call to xUnlock() fails when unlocking the
38728** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
38729** is only changed back to a real locking state after a successful call
38730** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
38731** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
38732** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
38733** lock on the database file before attempting to roll it back. See function
38734** PagerSharedLock() for more detail.
38735**
38736** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
38737** PAGER_OPEN state.
38738*/
38739#define UNKNOWN_LOCK                (EXCLUSIVE_LOCK+1)
38740
38741/*
38742** A macro used for invoking the codec if there is one
38743*/
38744#ifdef SQLITE_HAS_CODEC
38745# define CODEC1(P,D,N,X,E) \
38746    if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
38747# define CODEC2(P,D,N,X,E,O) \
38748    if( P->xCodec==0 ){ O=(char*)D; }else \
38749    if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
38750#else
38751# define CODEC1(P,D,N,X,E)   /* NO-OP */
38752# define CODEC2(P,D,N,X,E,O) O=(char*)D
38753#endif
38754
38755/*
38756** The maximum allowed sector size. 64KiB. If the xSectorsize() method
38757** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
38758** This could conceivably cause corruption following a power failure on
38759** such a system. This is currently an undocumented limit.
38760*/
38761#define MAX_SECTOR_SIZE 0x10000
38762
38763/*
38764** An instance of the following structure is allocated for each active
38765** savepoint and statement transaction in the system. All such structures
38766** are stored in the Pager.aSavepoint[] array, which is allocated and
38767** resized using sqlite3Realloc().
38768**
38769** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
38770** set to 0. If a journal-header is written into the main journal while
38771** the savepoint is active, then iHdrOffset is set to the byte offset
38772** immediately following the last journal record written into the main
38773** journal before the journal-header. This is required during savepoint
38774** rollback (see pagerPlaybackSavepoint()).
38775*/
38776typedef struct PagerSavepoint PagerSavepoint;
38777struct PagerSavepoint {
38778  i64 iOffset;                 /* Starting offset in main journal */
38779  i64 iHdrOffset;              /* See above */
38780  Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
38781  Pgno nOrig;                  /* Original number of pages in file */
38782  Pgno iSubRec;                /* Index of first record in sub-journal */
38783#ifndef SQLITE_OMIT_WAL
38784  u32 aWalData[WAL_SAVEPOINT_NDATA];        /* WAL savepoint context */
38785#endif
38786};
38787
38788/*
38789** A open page cache is an instance of struct Pager. A description of
38790** some of the more important member variables follows:
38791**
38792** eState
38793**
38794**   The current 'state' of the pager object. See the comment and state
38795**   diagram above for a description of the pager state.
38796**
38797** eLock
38798**
38799**   For a real on-disk database, the current lock held on the database file -
38800**   NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
38801**
38802**   For a temporary or in-memory database (neither of which require any
38803**   locks), this variable is always set to EXCLUSIVE_LOCK. Since such
38804**   databases always have Pager.exclusiveMode==1, this tricks the pager
38805**   logic into thinking that it already has all the locks it will ever
38806**   need (and no reason to release them).
38807**
38808**   In some (obscure) circumstances, this variable may also be set to
38809**   UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
38810**   details.
38811**
38812** changeCountDone
38813**
38814**   This boolean variable is used to make sure that the change-counter
38815**   (the 4-byte header field at byte offset 24 of the database file) is
38816**   not updated more often than necessary.
38817**
38818**   It is set to true when the change-counter field is updated, which
38819**   can only happen if an exclusive lock is held on the database file.
38820**   It is cleared (set to false) whenever an exclusive lock is
38821**   relinquished on the database file. Each time a transaction is committed,
38822**   The changeCountDone flag is inspected. If it is true, the work of
38823**   updating the change-counter is omitted for the current transaction.
38824**
38825**   This mechanism means that when running in exclusive mode, a connection
38826**   need only update the change-counter once, for the first transaction
38827**   committed.
38828**
38829** setMaster
38830**
38831**   When PagerCommitPhaseOne() is called to commit a transaction, it may
38832**   (or may not) specify a master-journal name to be written into the
38833**   journal file before it is synced to disk.
38834**
38835**   Whether or not a journal file contains a master-journal pointer affects
38836**   the way in which the journal file is finalized after the transaction is
38837**   committed or rolled back when running in "journal_mode=PERSIST" mode.
38838**   If a journal file does not contain a master-journal pointer, it is
38839**   finalized by overwriting the first journal header with zeroes. If
38840**   it does contain a master-journal pointer the journal file is finalized
38841**   by truncating it to zero bytes, just as if the connection were
38842**   running in "journal_mode=truncate" mode.
38843**
38844**   Journal files that contain master journal pointers cannot be finalized
38845**   simply by overwriting the first journal-header with zeroes, as the
38846**   master journal pointer could interfere with hot-journal rollback of any
38847**   subsequently interrupted transaction that reuses the journal file.
38848**
38849**   The flag is cleared as soon as the journal file is finalized (either
38850**   by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
38851**   journal file from being successfully finalized, the setMaster flag
38852**   is cleared anyway (and the pager will move to ERROR state).
38853**
38854** doNotSpill, doNotSyncSpill
38855**
38856**   These two boolean variables control the behavior of cache-spills
38857**   (calls made by the pcache module to the pagerStress() routine to
38858**   write cached data to the file-system in order to free up memory).
38859**
38860**   When doNotSpill is non-zero, writing to the database from pagerStress()
38861**   is disabled altogether. This is done in a very obscure case that
38862**   comes up during savepoint rollback that requires the pcache module
38863**   to allocate a new page to prevent the journal file from being written
38864**   while it is being traversed by code in pager_playback().
38865**
38866**   If doNotSyncSpill is non-zero, writing to the database from pagerStress()
38867**   is permitted, but syncing the journal file is not. This flag is set
38868**   by sqlite3PagerWrite() when the file-system sector-size is larger than
38869**   the database page-size in order to prevent a journal sync from happening
38870**   in between the journalling of two pages on the same sector.
38871**
38872** subjInMemory
38873**
38874**   This is a boolean variable. If true, then any required sub-journal
38875**   is opened as an in-memory journal file. If false, then in-memory
38876**   sub-journals are only used for in-memory pager files.
38877**
38878**   This variable is updated by the upper layer each time a new
38879**   write-transaction is opened.
38880**
38881** dbSize, dbOrigSize, dbFileSize
38882**
38883**   Variable dbSize is set to the number of pages in the database file.
38884**   It is valid in PAGER_READER and higher states (all states except for
38885**   OPEN and ERROR).
38886**
38887**   dbSize is set based on the size of the database file, which may be
38888**   larger than the size of the database (the value stored at offset
38889**   28 of the database header by the btree). If the size of the file
38890**   is not an integer multiple of the page-size, the value stored in
38891**   dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
38892**   Except, any file that is greater than 0 bytes in size is considered
38893**   to have at least one page. (i.e. a 1KB file with 2K page-size leads
38894**   to dbSize==1).
38895**
38896**   During a write-transaction, if pages with page-numbers greater than
38897**   dbSize are modified in the cache, dbSize is updated accordingly.
38898**   Similarly, if the database is truncated using PagerTruncateImage(),
38899**   dbSize is updated.
38900**
38901**   Variables dbOrigSize and dbFileSize are valid in states
38902**   PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
38903**   variable at the start of the transaction. It is used during rollback,
38904**   and to determine whether or not pages need to be journalled before
38905**   being modified.
38906**
38907**   Throughout a write-transaction, dbFileSize contains the size of
38908**   the file on disk in pages. It is set to a copy of dbSize when the
38909**   write-transaction is first opened, and updated when VFS calls are made
38910**   to write or truncate the database file on disk.
38911**
38912**   The only reason the dbFileSize variable is required is to suppress
38913**   unnecessary calls to xTruncate() after committing a transaction. If,
38914**   when a transaction is committed, the dbFileSize variable indicates
38915**   that the database file is larger than the database image (Pager.dbSize),
38916**   pager_truncate() is called. The pager_truncate() call uses xFilesize()
38917**   to measure the database file on disk, and then truncates it if required.
38918**   dbFileSize is not used when rolling back a transaction. In this case
38919**   pager_truncate() is called unconditionally (which means there may be
38920**   a call to xFilesize() that is not strictly required). In either case,
38921**   pager_truncate() may cause the file to become smaller or larger.
38922**
38923** dbHintSize
38924**
38925**   The dbHintSize variable is used to limit the number of calls made to
38926**   the VFS xFileControl(FCNTL_SIZE_HINT) method.
38927**
38928**   dbHintSize is set to a copy of the dbSize variable when a
38929**   write-transaction is opened (at the same time as dbFileSize and
38930**   dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
38931**   dbHintSize is increased to the number of pages that correspond to the
38932**   size-hint passed to the method call. See pager_write_pagelist() for
38933**   details.
38934**
38935** errCode
38936**
38937**   The Pager.errCode variable is only ever used in PAGER_ERROR state. It
38938**   is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
38939**   is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
38940**   sub-codes.
38941*/
38942struct Pager {
38943  sqlite3_vfs *pVfs;          /* OS functions to use for IO */
38944  u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
38945  u8 journalMode;             /* One of the PAGER_JOURNALMODE_* values */
38946  u8 useJournal;              /* Use a rollback journal on this file */
38947  u8 noSync;                  /* Do not sync the journal if true */
38948  u8 fullSync;                /* Do extra syncs of the journal for robustness */
38949  u8 ckptSyncFlags;           /* SYNC_NORMAL or SYNC_FULL for checkpoint */
38950  u8 walSyncFlags;            /* SYNC_NORMAL or SYNC_FULL for wal writes */
38951  u8 syncFlags;               /* SYNC_NORMAL or SYNC_FULL otherwise */
38952  u8 tempFile;                /* zFilename is a temporary file */
38953  u8 readOnly;                /* True for a read-only database */
38954  u8 memDb;                   /* True to inhibit all file I/O */
38955
38956  /**************************************************************************
38957  ** The following block contains those class members that change during
38958  ** routine opertion.  Class members not in this block are either fixed
38959  ** when the pager is first created or else only change when there is a
38960  ** significant mode change (such as changing the page_size, locking_mode,
38961  ** or the journal_mode).  From another view, these class members describe
38962  ** the "state" of the pager, while other class members describe the
38963  ** "configuration" of the pager.
38964  */
38965  u8 eState;                  /* Pager state (OPEN, READER, WRITER_LOCKED..) */
38966  u8 eLock;                   /* Current lock held on database file */
38967  u8 changeCountDone;         /* Set after incrementing the change-counter */
38968  u8 setMaster;               /* True if a m-j name has been written to jrnl */
38969  u8 doNotSpill;              /* Do not spill the cache when non-zero */
38970  u8 doNotSyncSpill;          /* Do not do a spill that requires jrnl sync */
38971  u8 subjInMemory;            /* True to use in-memory sub-journals */
38972  Pgno dbSize;                /* Number of pages in the database */
38973  Pgno dbOrigSize;            /* dbSize before the current transaction */
38974  Pgno dbFileSize;            /* Number of pages in the database file */
38975  Pgno dbHintSize;            /* Value passed to FCNTL_SIZE_HINT call */
38976  int errCode;                /* One of several kinds of errors */
38977  int nRec;                   /* Pages journalled since last j-header written */
38978  u32 cksumInit;              /* Quasi-random value added to every checksum */
38979  u32 nSubRec;                /* Number of records written to sub-journal */
38980  Bitvec *pInJournal;         /* One bit for each page in the database file */
38981  sqlite3_file *fd;           /* File descriptor for database */
38982  sqlite3_file *jfd;          /* File descriptor for main journal */
38983  sqlite3_file *sjfd;         /* File descriptor for sub-journal */
38984  i64 journalOff;             /* Current write offset in the journal file */
38985  i64 journalHdr;             /* Byte offset to previous journal header */
38986  sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
38987  PagerSavepoint *aSavepoint; /* Array of active savepoints */
38988  int nSavepoint;             /* Number of elements in aSavepoint[] */
38989  char dbFileVers[16];        /* Changes whenever database file changes */
38990
38991  u8 bUseFetch;               /* True to use xFetch() */
38992  int nMmapOut;               /* Number of mmap pages currently outstanding */
38993  sqlite3_int64 szMmap;       /* Desired maximum mmap size */
38994  PgHdr *pMmapFreelist;       /* List of free mmap page headers (pDirty) */
38995  /*
38996  ** End of the routinely-changing class members
38997  ***************************************************************************/
38998
38999  u16 nExtra;                 /* Add this many bytes to each in-memory page */
39000  i16 nReserve;               /* Number of unused bytes at end of each page */
39001  u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
39002  u32 sectorSize;             /* Assumed sector size during rollback */
39003  int pageSize;               /* Number of bytes in a page */
39004  Pgno mxPgno;                /* Maximum allowed size of the database */
39005  i64 journalSizeLimit;       /* Size limit for persistent journal files */
39006  char *zFilename;            /* Name of the database file */
39007  char *zJournal;             /* Name of the journal file */
39008  int (*xBusyHandler)(void*); /* Function to call when busy */
39009  void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
39010  int aStat[3];               /* Total cache hits, misses and writes */
39011#ifdef SQLITE_TEST
39012  int nRead;                  /* Database pages read */
39013#endif
39014  void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
39015#ifdef SQLITE_HAS_CODEC
39016  void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
39017  void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
39018  void (*xCodecFree)(void*);             /* Destructor for the codec */
39019  void *pCodec;               /* First argument to xCodec... methods */
39020#endif
39021  char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
39022  PCache *pPCache;            /* Pointer to page cache object */
39023#ifndef SQLITE_OMIT_WAL
39024  Wal *pWal;                  /* Write-ahead log used by "journal_mode=wal" */
39025  char *zWal;                 /* File name for write-ahead log */
39026#endif
39027};
39028
39029/*
39030** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
39031** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS
39032** or CACHE_WRITE to sqlite3_db_status().
39033*/
39034#define PAGER_STAT_HIT   0
39035#define PAGER_STAT_MISS  1
39036#define PAGER_STAT_WRITE 2
39037
39038/*
39039** The following global variables hold counters used for
39040** testing purposes only.  These variables do not exist in
39041** a non-testing build.  These variables are not thread-safe.
39042*/
39043#ifdef SQLITE_TEST
39044SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
39045SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
39046SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
39047# define PAGER_INCR(v)  v++
39048#else
39049# define PAGER_INCR(v)
39050#endif
39051
39052
39053
39054/*
39055** Journal files begin with the following magic string.  The data
39056** was obtained from /dev/random.  It is used only as a sanity check.
39057**
39058** Since version 2.8.0, the journal format contains additional sanity
39059** checking information.  If the power fails while the journal is being
39060** written, semi-random garbage data might appear in the journal
39061** file after power is restored.  If an attempt is then made
39062** to roll the journal back, the database could be corrupted.  The additional
39063** sanity checking data is an attempt to discover the garbage in the
39064** journal and ignore it.
39065**
39066** The sanity checking information for the new journal format consists
39067** of a 32-bit checksum on each page of data.  The checksum covers both
39068** the page number and the pPager->pageSize bytes of data for the page.
39069** This cksum is initialized to a 32-bit random value that appears in the
39070** journal file right after the header.  The random initializer is important,
39071** because garbage data that appears at the end of a journal is likely
39072** data that was once in other files that have now been deleted.  If the
39073** garbage data came from an obsolete journal file, the checksums might
39074** be correct.  But by initializing the checksum to random value which
39075** is different for every journal, we minimize that risk.
39076*/
39077static const unsigned char aJournalMagic[] = {
39078  0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
39079};
39080
39081/*
39082** The size of the of each page record in the journal is given by
39083** the following macro.
39084*/
39085#define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
39086
39087/*
39088** The journal header size for this pager. This is usually the same
39089** size as a single disk sector. See also setSectorSize().
39090*/
39091#define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
39092
39093/*
39094** The macro MEMDB is true if we are dealing with an in-memory database.
39095** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
39096** the value of MEMDB will be a constant and the compiler will optimize
39097** out code that would never execute.
39098*/
39099#ifdef SQLITE_OMIT_MEMORYDB
39100# define MEMDB 0
39101#else
39102# define MEMDB pPager->memDb
39103#endif
39104
39105/*
39106** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch
39107** interfaces to access the database using memory-mapped I/O.
39108*/
39109#if SQLITE_MAX_MMAP_SIZE>0
39110# define USEFETCH(x) ((x)->bUseFetch)
39111#else
39112# define USEFETCH(x) 0
39113#endif
39114
39115/*
39116** The maximum legal page number is (2^31 - 1).
39117*/
39118#define PAGER_MAX_PGNO 2147483647
39119
39120/*
39121** The argument to this macro is a file descriptor (type sqlite3_file*).
39122** Return 0 if it is not open, or non-zero (but not 1) if it is.
39123**
39124** This is so that expressions can be written as:
39125**
39126**   if( isOpen(pPager->jfd) ){ ...
39127**
39128** instead of
39129**
39130**   if( pPager->jfd->pMethods ){ ...
39131*/
39132#define isOpen(pFd) ((pFd)->pMethods)
39133
39134/*
39135** Return true if this pager uses a write-ahead log instead of the usual
39136** rollback journal. Otherwise false.
39137*/
39138#ifndef SQLITE_OMIT_WAL
39139static int pagerUseWal(Pager *pPager){
39140  return (pPager->pWal!=0);
39141}
39142#else
39143# define pagerUseWal(x) 0
39144# define pagerRollbackWal(x) 0
39145# define pagerWalFrames(v,w,x,y) 0
39146# define pagerOpenWalIfPresent(z) SQLITE_OK
39147# define pagerBeginReadTransaction(z) SQLITE_OK
39148#endif
39149
39150#ifndef NDEBUG
39151/*
39152** Usage:
39153**
39154**   assert( assert_pager_state(pPager) );
39155**
39156** This function runs many asserts to try to find inconsistencies in
39157** the internal state of the Pager object.
39158*/
39159static int assert_pager_state(Pager *p){
39160  Pager *pPager = p;
39161
39162  /* State must be valid. */
39163  assert( p->eState==PAGER_OPEN
39164       || p->eState==PAGER_READER
39165       || p->eState==PAGER_WRITER_LOCKED
39166       || p->eState==PAGER_WRITER_CACHEMOD
39167       || p->eState==PAGER_WRITER_DBMOD
39168       || p->eState==PAGER_WRITER_FINISHED
39169       || p->eState==PAGER_ERROR
39170  );
39171
39172  /* Regardless of the current state, a temp-file connection always behaves
39173  ** as if it has an exclusive lock on the database file. It never updates
39174  ** the change-counter field, so the changeCountDone flag is always set.
39175  */
39176  assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
39177  assert( p->tempFile==0 || pPager->changeCountDone );
39178
39179  /* If the useJournal flag is clear, the journal-mode must be "OFF".
39180  ** And if the journal-mode is "OFF", the journal file must not be open.
39181  */
39182  assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
39183  assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
39184
39185  /* Check that MEMDB implies noSync. And an in-memory journal. Since
39186  ** this means an in-memory pager performs no IO at all, it cannot encounter
39187  ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
39188  ** a journal file. (although the in-memory journal implementation may
39189  ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
39190  ** is therefore not possible for an in-memory pager to enter the ERROR
39191  ** state.
39192  */
39193  if( MEMDB ){
39194    assert( p->noSync );
39195    assert( p->journalMode==PAGER_JOURNALMODE_OFF
39196         || p->journalMode==PAGER_JOURNALMODE_MEMORY
39197    );
39198    assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
39199    assert( pagerUseWal(p)==0 );
39200  }
39201
39202  /* If changeCountDone is set, a RESERVED lock or greater must be held
39203  ** on the file.
39204  */
39205  assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
39206  assert( p->eLock!=PENDING_LOCK );
39207
39208  switch( p->eState ){
39209    case PAGER_OPEN:
39210      assert( !MEMDB );
39211      assert( pPager->errCode==SQLITE_OK );
39212      assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
39213      break;
39214
39215    case PAGER_READER:
39216      assert( pPager->errCode==SQLITE_OK );
39217      assert( p->eLock!=UNKNOWN_LOCK );
39218      assert( p->eLock>=SHARED_LOCK );
39219      break;
39220
39221    case PAGER_WRITER_LOCKED:
39222      assert( p->eLock!=UNKNOWN_LOCK );
39223      assert( pPager->errCode==SQLITE_OK );
39224      if( !pagerUseWal(pPager) ){
39225        assert( p->eLock>=RESERVED_LOCK );
39226      }
39227      assert( pPager->dbSize==pPager->dbOrigSize );
39228      assert( pPager->dbOrigSize==pPager->dbFileSize );
39229      assert( pPager->dbOrigSize==pPager->dbHintSize );
39230      assert( pPager->setMaster==0 );
39231      break;
39232
39233    case PAGER_WRITER_CACHEMOD:
39234      assert( p->eLock!=UNKNOWN_LOCK );
39235      assert( pPager->errCode==SQLITE_OK );
39236      if( !pagerUseWal(pPager) ){
39237        /* It is possible that if journal_mode=wal here that neither the
39238        ** journal file nor the WAL file are open. This happens during
39239        ** a rollback transaction that switches from journal_mode=off
39240        ** to journal_mode=wal.
39241        */
39242        assert( p->eLock>=RESERVED_LOCK );
39243        assert( isOpen(p->jfd)
39244             || p->journalMode==PAGER_JOURNALMODE_OFF
39245             || p->journalMode==PAGER_JOURNALMODE_WAL
39246        );
39247      }
39248      assert( pPager->dbOrigSize==pPager->dbFileSize );
39249      assert( pPager->dbOrigSize==pPager->dbHintSize );
39250      break;
39251
39252    case PAGER_WRITER_DBMOD:
39253      assert( p->eLock==EXCLUSIVE_LOCK );
39254      assert( pPager->errCode==SQLITE_OK );
39255      assert( !pagerUseWal(pPager) );
39256      assert( p->eLock>=EXCLUSIVE_LOCK );
39257      assert( isOpen(p->jfd)
39258           || p->journalMode==PAGER_JOURNALMODE_OFF
39259           || p->journalMode==PAGER_JOURNALMODE_WAL
39260      );
39261      assert( pPager->dbOrigSize<=pPager->dbHintSize );
39262      break;
39263
39264    case PAGER_WRITER_FINISHED:
39265      assert( p->eLock==EXCLUSIVE_LOCK );
39266      assert( pPager->errCode==SQLITE_OK );
39267      assert( !pagerUseWal(pPager) );
39268      assert( isOpen(p->jfd)
39269           || p->journalMode==PAGER_JOURNALMODE_OFF
39270           || p->journalMode==PAGER_JOURNALMODE_WAL
39271      );
39272      break;
39273
39274    case PAGER_ERROR:
39275      /* There must be at least one outstanding reference to the pager if
39276      ** in ERROR state. Otherwise the pager should have already dropped
39277      ** back to OPEN state.
39278      */
39279      assert( pPager->errCode!=SQLITE_OK );
39280      assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
39281      break;
39282  }
39283
39284  return 1;
39285}
39286#endif /* ifndef NDEBUG */
39287
39288#ifdef SQLITE_DEBUG
39289/*
39290** Return a pointer to a human readable string in a static buffer
39291** containing the state of the Pager object passed as an argument. This
39292** is intended to be used within debuggers. For example, as an alternative
39293** to "print *pPager" in gdb:
39294**
39295** (gdb) printf "%s", print_pager_state(pPager)
39296*/
39297static char *print_pager_state(Pager *p){
39298  static char zRet[1024];
39299
39300  sqlite3_snprintf(1024, zRet,
39301      "Filename:      %s\n"
39302      "State:         %s errCode=%d\n"
39303      "Lock:          %s\n"
39304      "Locking mode:  locking_mode=%s\n"
39305      "Journal mode:  journal_mode=%s\n"
39306      "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
39307      "Journal:       journalOff=%lld journalHdr=%lld\n"
39308      "Size:          dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
39309      , p->zFilename
39310      , p->eState==PAGER_OPEN            ? "OPEN" :
39311        p->eState==PAGER_READER          ? "READER" :
39312        p->eState==PAGER_WRITER_LOCKED   ? "WRITER_LOCKED" :
39313        p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
39314        p->eState==PAGER_WRITER_DBMOD    ? "WRITER_DBMOD" :
39315        p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
39316        p->eState==PAGER_ERROR           ? "ERROR" : "?error?"
39317      , (int)p->errCode
39318      , p->eLock==NO_LOCK         ? "NO_LOCK" :
39319        p->eLock==RESERVED_LOCK   ? "RESERVED" :
39320        p->eLock==EXCLUSIVE_LOCK  ? "EXCLUSIVE" :
39321        p->eLock==SHARED_LOCK     ? "SHARED" :
39322        p->eLock==UNKNOWN_LOCK    ? "UNKNOWN" : "?error?"
39323      , p->exclusiveMode ? "exclusive" : "normal"
39324      , p->journalMode==PAGER_JOURNALMODE_MEMORY   ? "memory" :
39325        p->journalMode==PAGER_JOURNALMODE_OFF      ? "off" :
39326        p->journalMode==PAGER_JOURNALMODE_DELETE   ? "delete" :
39327        p->journalMode==PAGER_JOURNALMODE_PERSIST  ? "persist" :
39328        p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
39329        p->journalMode==PAGER_JOURNALMODE_WAL      ? "wal" : "?error?"
39330      , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
39331      , p->journalOff, p->journalHdr
39332      , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
39333  );
39334
39335  return zRet;
39336}
39337#endif
39338
39339/*
39340** Return true if it is necessary to write page *pPg into the sub-journal.
39341** A page needs to be written into the sub-journal if there exists one
39342** or more open savepoints for which:
39343**
39344**   * The page-number is less than or equal to PagerSavepoint.nOrig, and
39345**   * The bit corresponding to the page-number is not set in
39346**     PagerSavepoint.pInSavepoint.
39347*/
39348static int subjRequiresPage(PgHdr *pPg){
39349  Pgno pgno = pPg->pgno;
39350  Pager *pPager = pPg->pPager;
39351  int i;
39352  for(i=0; i<pPager->nSavepoint; i++){
39353    PagerSavepoint *p = &pPager->aSavepoint[i];
39354    if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
39355      return 1;
39356    }
39357  }
39358  return 0;
39359}
39360
39361/*
39362** Return true if the page is already in the journal file.
39363*/
39364static int pageInJournal(PgHdr *pPg){
39365  return sqlite3BitvecTest(pPg->pPager->pInJournal, pPg->pgno);
39366}
39367
39368/*
39369** Read a 32-bit integer from the given file descriptor.  Store the integer
39370** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
39371** error code is something goes wrong.
39372**
39373** All values are stored on disk as big-endian.
39374*/
39375static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
39376  unsigned char ac[4];
39377  int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
39378  if( rc==SQLITE_OK ){
39379    *pRes = sqlite3Get4byte(ac);
39380  }
39381  return rc;
39382}
39383
39384/*
39385** Write a 32-bit integer into a string buffer in big-endian byte order.
39386*/
39387#define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
39388
39389
39390/*
39391** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
39392** on success or an error code is something goes wrong.
39393*/
39394static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
39395  char ac[4];
39396  put32bits(ac, val);
39397  return sqlite3OsWrite(fd, ac, 4, offset);
39398}
39399
39400/*
39401** Unlock the database file to level eLock, which must be either NO_LOCK
39402** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
39403** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
39404**
39405** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
39406** called, do not modify it. See the comment above the #define of
39407** UNKNOWN_LOCK for an explanation of this.
39408*/
39409static int pagerUnlockDb(Pager *pPager, int eLock){
39410  int rc = SQLITE_OK;
39411
39412  assert( !pPager->exclusiveMode || pPager->eLock==eLock );
39413  assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
39414  assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
39415  if( isOpen(pPager->fd) ){
39416    assert( pPager->eLock>=eLock );
39417    rc = sqlite3OsUnlock(pPager->fd, eLock);
39418    if( pPager->eLock!=UNKNOWN_LOCK ){
39419      pPager->eLock = (u8)eLock;
39420    }
39421    IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
39422  }
39423  return rc;
39424}
39425
39426/*
39427** Lock the database file to level eLock, which must be either SHARED_LOCK,
39428** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
39429** Pager.eLock variable to the new locking state.
39430**
39431** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
39432** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
39433** See the comment above the #define of UNKNOWN_LOCK for an explanation
39434** of this.
39435*/
39436static int pagerLockDb(Pager *pPager, int eLock){
39437  int rc = SQLITE_OK;
39438
39439  assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
39440  if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
39441    rc = sqlite3OsLock(pPager->fd, eLock);
39442    if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
39443      pPager->eLock = (u8)eLock;
39444      IOTRACE(("LOCK %p %d\n", pPager, eLock))
39445    }
39446  }
39447  return rc;
39448}
39449
39450/*
39451** This function determines whether or not the atomic-write optimization
39452** can be used with this pager. The optimization can be used if:
39453**
39454**  (a) the value returned by OsDeviceCharacteristics() indicates that
39455**      a database page may be written atomically, and
39456**  (b) the value returned by OsSectorSize() is less than or equal
39457**      to the page size.
39458**
39459** The optimization is also always enabled for temporary files. It is
39460** an error to call this function if pPager is opened on an in-memory
39461** database.
39462**
39463** If the optimization cannot be used, 0 is returned. If it can be used,
39464** then the value returned is the size of the journal file when it
39465** contains rollback data for exactly one page.
39466*/
39467#ifdef SQLITE_ENABLE_ATOMIC_WRITE
39468static int jrnlBufferSize(Pager *pPager){
39469  assert( !MEMDB );
39470  if( !pPager->tempFile ){
39471    int dc;                           /* Device characteristics */
39472    int nSector;                      /* Sector size */
39473    int szPage;                       /* Page size */
39474
39475    assert( isOpen(pPager->fd) );
39476    dc = sqlite3OsDeviceCharacteristics(pPager->fd);
39477    nSector = pPager->sectorSize;
39478    szPage = pPager->pageSize;
39479
39480    assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
39481    assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
39482    if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
39483      return 0;
39484    }
39485  }
39486
39487  return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
39488}
39489#endif
39490
39491/*
39492** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
39493** on the cache using a hash function.  This is used for testing
39494** and debugging only.
39495*/
39496#ifdef SQLITE_CHECK_PAGES
39497/*
39498** Return a 32-bit hash of the page data for pPage.
39499*/
39500static u32 pager_datahash(int nByte, unsigned char *pData){
39501  u32 hash = 0;
39502  int i;
39503  for(i=0; i<nByte; i++){
39504    hash = (hash*1039) + pData[i];
39505  }
39506  return hash;
39507}
39508static u32 pager_pagehash(PgHdr *pPage){
39509  return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
39510}
39511static void pager_set_pagehash(PgHdr *pPage){
39512  pPage->pageHash = pager_pagehash(pPage);
39513}
39514
39515/*
39516** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
39517** is defined, and NDEBUG is not defined, an assert() statement checks
39518** that the page is either dirty or still matches the calculated page-hash.
39519*/
39520#define CHECK_PAGE(x) checkPage(x)
39521static void checkPage(PgHdr *pPg){
39522  Pager *pPager = pPg->pPager;
39523  assert( pPager->eState!=PAGER_ERROR );
39524  assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
39525}
39526
39527#else
39528#define pager_datahash(X,Y)  0
39529#define pager_pagehash(X)  0
39530#define pager_set_pagehash(X)
39531#define CHECK_PAGE(x)
39532#endif  /* SQLITE_CHECK_PAGES */
39533
39534/*
39535** When this is called the journal file for pager pPager must be open.
39536** This function attempts to read a master journal file name from the
39537** end of the file and, if successful, copies it into memory supplied
39538** by the caller. See comments above writeMasterJournal() for the format
39539** used to store a master journal file name at the end of a journal file.
39540**
39541** zMaster must point to a buffer of at least nMaster bytes allocated by
39542** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
39543** enough space to write the master journal name). If the master journal
39544** name in the journal is longer than nMaster bytes (including a
39545** nul-terminator), then this is handled as if no master journal name
39546** were present in the journal.
39547**
39548** If a master journal file name is present at the end of the journal
39549** file, then it is copied into the buffer pointed to by zMaster. A
39550** nul-terminator byte is appended to the buffer following the master
39551** journal file name.
39552**
39553** If it is determined that no master journal file name is present
39554** zMaster[0] is set to 0 and SQLITE_OK returned.
39555**
39556** If an error occurs while reading from the journal file, an SQLite
39557** error code is returned.
39558*/
39559static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
39560  int rc;                    /* Return code */
39561  u32 len;                   /* Length in bytes of master journal name */
39562  i64 szJ;                   /* Total size in bytes of journal file pJrnl */
39563  u32 cksum;                 /* MJ checksum value read from journal */
39564  u32 u;                     /* Unsigned loop counter */
39565  unsigned char aMagic[8];   /* A buffer to hold the magic header */
39566  zMaster[0] = '\0';
39567
39568  if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
39569   || szJ<16
39570   || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
39571   || len>=nMaster
39572   || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
39573   || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
39574   || memcmp(aMagic, aJournalMagic, 8)
39575   || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
39576  ){
39577    return rc;
39578  }
39579
39580  /* See if the checksum matches the master journal name */
39581  for(u=0; u<len; u++){
39582    cksum -= zMaster[u];
39583  }
39584  if( cksum ){
39585    /* If the checksum doesn't add up, then one or more of the disk sectors
39586    ** containing the master journal filename is corrupted. This means
39587    ** definitely roll back, so just return SQLITE_OK and report a (nul)
39588    ** master-journal filename.
39589    */
39590    len = 0;
39591  }
39592  zMaster[len] = '\0';
39593
39594  return SQLITE_OK;
39595}
39596
39597/*
39598** Return the offset of the sector boundary at or immediately
39599** following the value in pPager->journalOff, assuming a sector
39600** size of pPager->sectorSize bytes.
39601**
39602** i.e for a sector size of 512:
39603**
39604**   Pager.journalOff          Return value
39605**   ---------------------------------------
39606**   0                         0
39607**   512                       512
39608**   100                       512
39609**   2000                      2048
39610**
39611*/
39612static i64 journalHdrOffset(Pager *pPager){
39613  i64 offset = 0;
39614  i64 c = pPager->journalOff;
39615  if( c ){
39616    offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
39617  }
39618  assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
39619  assert( offset>=c );
39620  assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
39621  return offset;
39622}
39623
39624/*
39625** The journal file must be open when this function is called.
39626**
39627** This function is a no-op if the journal file has not been written to
39628** within the current transaction (i.e. if Pager.journalOff==0).
39629**
39630** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
39631** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
39632** zero the 28-byte header at the start of the journal file. In either case,
39633** if the pager is not in no-sync mode, sync the journal file immediately
39634** after writing or truncating it.
39635**
39636** If Pager.journalSizeLimit is set to a positive, non-zero value, and
39637** following the truncation or zeroing described above the size of the
39638** journal file in bytes is larger than this value, then truncate the
39639** journal file to Pager.journalSizeLimit bytes. The journal file does
39640** not need to be synced following this operation.
39641**
39642** If an IO error occurs, abandon processing and return the IO error code.
39643** Otherwise, return SQLITE_OK.
39644*/
39645static int zeroJournalHdr(Pager *pPager, int doTruncate){
39646  int rc = SQLITE_OK;                               /* Return code */
39647  assert( isOpen(pPager->jfd) );
39648  if( pPager->journalOff ){
39649    const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
39650
39651    IOTRACE(("JZEROHDR %p\n", pPager))
39652    if( doTruncate || iLimit==0 ){
39653      rc = sqlite3OsTruncate(pPager->jfd, 0);
39654    }else{
39655      static const char zeroHdr[28] = {0};
39656      rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
39657    }
39658    if( rc==SQLITE_OK && !pPager->noSync ){
39659      rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
39660    }
39661
39662    /* At this point the transaction is committed but the write lock
39663    ** is still held on the file. If there is a size limit configured for
39664    ** the persistent journal and the journal file currently consumes more
39665    ** space than that limit allows for, truncate it now. There is no need
39666    ** to sync the file following this operation.
39667    */
39668    if( rc==SQLITE_OK && iLimit>0 ){
39669      i64 sz;
39670      rc = sqlite3OsFileSize(pPager->jfd, &sz);
39671      if( rc==SQLITE_OK && sz>iLimit ){
39672        rc = sqlite3OsTruncate(pPager->jfd, iLimit);
39673      }
39674    }
39675  }
39676  return rc;
39677}
39678
39679/*
39680** The journal file must be open when this routine is called. A journal
39681** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
39682** current location.
39683**
39684** The format for the journal header is as follows:
39685** - 8 bytes: Magic identifying journal format.
39686** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
39687** - 4 bytes: Random number used for page hash.
39688** - 4 bytes: Initial database page count.
39689** - 4 bytes: Sector size used by the process that wrote this journal.
39690** - 4 bytes: Database page size.
39691**
39692** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
39693*/
39694static int writeJournalHdr(Pager *pPager){
39695  int rc = SQLITE_OK;                 /* Return code */
39696  char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
39697  u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
39698  u32 nWrite;                         /* Bytes of header sector written */
39699  int ii;                             /* Loop counter */
39700
39701  assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
39702
39703  if( nHeader>JOURNAL_HDR_SZ(pPager) ){
39704    nHeader = JOURNAL_HDR_SZ(pPager);
39705  }
39706
39707  /* If there are active savepoints and any of them were created
39708  ** since the most recent journal header was written, update the
39709  ** PagerSavepoint.iHdrOffset fields now.
39710  */
39711  for(ii=0; ii<pPager->nSavepoint; ii++){
39712    if( pPager->aSavepoint[ii].iHdrOffset==0 ){
39713      pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
39714    }
39715  }
39716
39717  pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
39718
39719  /*
39720  ** Write the nRec Field - the number of page records that follow this
39721  ** journal header. Normally, zero is written to this value at this time.
39722  ** After the records are added to the journal (and the journal synced,
39723  ** if in full-sync mode), the zero is overwritten with the true number
39724  ** of records (see syncJournal()).
39725  **
39726  ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
39727  ** reading the journal this value tells SQLite to assume that the
39728  ** rest of the journal file contains valid page records. This assumption
39729  ** is dangerous, as if a failure occurred whilst writing to the journal
39730  ** file it may contain some garbage data. There are two scenarios
39731  ** where this risk can be ignored:
39732  **
39733  **   * When the pager is in no-sync mode. Corruption can follow a
39734  **     power failure in this case anyway.
39735  **
39736  **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
39737  **     that garbage data is never appended to the journal file.
39738  */
39739  assert( isOpen(pPager->fd) || pPager->noSync );
39740  if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
39741   || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
39742  ){
39743    memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
39744    put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
39745  }else{
39746    memset(zHeader, 0, sizeof(aJournalMagic)+4);
39747  }
39748
39749  /* The random check-hash initializer */
39750  sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
39751  put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
39752  /* The initial database size */
39753  put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
39754  /* The assumed sector size for this process */
39755  put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
39756
39757  /* The page size */
39758  put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
39759
39760  /* Initializing the tail of the buffer is not necessary.  Everything
39761  ** works find if the following memset() is omitted.  But initializing
39762  ** the memory prevents valgrind from complaining, so we are willing to
39763  ** take the performance hit.
39764  */
39765  memset(&zHeader[sizeof(aJournalMagic)+20], 0,
39766         nHeader-(sizeof(aJournalMagic)+20));
39767
39768  /* In theory, it is only necessary to write the 28 bytes that the
39769  ** journal header consumes to the journal file here. Then increment the
39770  ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
39771  ** record is written to the following sector (leaving a gap in the file
39772  ** that will be implicitly filled in by the OS).
39773  **
39774  ** However it has been discovered that on some systems this pattern can
39775  ** be significantly slower than contiguously writing data to the file,
39776  ** even if that means explicitly writing data to the block of
39777  ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
39778  ** is done.
39779  **
39780  ** The loop is required here in case the sector-size is larger than the
39781  ** database page size. Since the zHeader buffer is only Pager.pageSize
39782  ** bytes in size, more than one call to sqlite3OsWrite() may be required
39783  ** to populate the entire journal header sector.
39784  */
39785  for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
39786    IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
39787    rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
39788    assert( pPager->journalHdr <= pPager->journalOff );
39789    pPager->journalOff += nHeader;
39790  }
39791
39792  return rc;
39793}
39794
39795/*
39796** The journal file must be open when this is called. A journal header file
39797** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
39798** file. The current location in the journal file is given by
39799** pPager->journalOff. See comments above function writeJournalHdr() for
39800** a description of the journal header format.
39801**
39802** If the header is read successfully, *pNRec is set to the number of
39803** page records following this header and *pDbSize is set to the size of the
39804** database before the transaction began, in pages. Also, pPager->cksumInit
39805** is set to the value read from the journal header. SQLITE_OK is returned
39806** in this case.
39807**
39808** If the journal header file appears to be corrupted, SQLITE_DONE is
39809** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
39810** cannot be read from the journal file an error code is returned.
39811*/
39812static int readJournalHdr(
39813  Pager *pPager,               /* Pager object */
39814  int isHot,
39815  i64 journalSize,             /* Size of the open journal file in bytes */
39816  u32 *pNRec,                  /* OUT: Value read from the nRec field */
39817  u32 *pDbSize                 /* OUT: Value of original database size field */
39818){
39819  int rc;                      /* Return code */
39820  unsigned char aMagic[8];     /* A buffer to hold the magic header */
39821  i64 iHdrOff;                 /* Offset of journal header being read */
39822
39823  assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
39824
39825  /* Advance Pager.journalOff to the start of the next sector. If the
39826  ** journal file is too small for there to be a header stored at this
39827  ** point, return SQLITE_DONE.
39828  */
39829  pPager->journalOff = journalHdrOffset(pPager);
39830  if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
39831    return SQLITE_DONE;
39832  }
39833  iHdrOff = pPager->journalOff;
39834
39835  /* Read in the first 8 bytes of the journal header. If they do not match
39836  ** the  magic string found at the start of each journal header, return
39837  ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
39838  ** proceed.
39839  */
39840  if( isHot || iHdrOff!=pPager->journalHdr ){
39841    rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
39842    if( rc ){
39843      return rc;
39844    }
39845    if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
39846      return SQLITE_DONE;
39847    }
39848  }
39849
39850  /* Read the first three 32-bit fields of the journal header: The nRec
39851  ** field, the checksum-initializer and the database size at the start
39852  ** of the transaction. Return an error code if anything goes wrong.
39853  */
39854  if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
39855   || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
39856   || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
39857  ){
39858    return rc;
39859  }
39860
39861  if( pPager->journalOff==0 ){
39862    u32 iPageSize;               /* Page-size field of journal header */
39863    u32 iSectorSize;             /* Sector-size field of journal header */
39864
39865    /* Read the page-size and sector-size journal header fields. */
39866    if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
39867     || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
39868    ){
39869      return rc;
39870    }
39871
39872    /* Versions of SQLite prior to 3.5.8 set the page-size field of the
39873    ** journal header to zero. In this case, assume that the Pager.pageSize
39874    ** variable is already set to the correct page size.
39875    */
39876    if( iPageSize==0 ){
39877      iPageSize = pPager->pageSize;
39878    }
39879
39880    /* Check that the values read from the page-size and sector-size fields
39881    ** are within range. To be 'in range', both values need to be a power
39882    ** of two greater than or equal to 512 or 32, and not greater than their
39883    ** respective compile time maximum limits.
39884    */
39885    if( iPageSize<512                  || iSectorSize<32
39886     || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
39887     || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0
39888    ){
39889      /* If the either the page-size or sector-size in the journal-header is
39890      ** invalid, then the process that wrote the journal-header must have
39891      ** crashed before the header was synced. In this case stop reading
39892      ** the journal file here.
39893      */
39894      return SQLITE_DONE;
39895    }
39896
39897    /* Update the page-size to match the value read from the journal.
39898    ** Use a testcase() macro to make sure that malloc failure within
39899    ** PagerSetPagesize() is tested.
39900    */
39901    rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
39902    testcase( rc!=SQLITE_OK );
39903
39904    /* Update the assumed sector-size to match the value used by
39905    ** the process that created this journal. If this journal was
39906    ** created by a process other than this one, then this routine
39907    ** is being called from within pager_playback(). The local value
39908    ** of Pager.sectorSize is restored at the end of that routine.
39909    */
39910    pPager->sectorSize = iSectorSize;
39911  }
39912
39913  pPager->journalOff += JOURNAL_HDR_SZ(pPager);
39914  return rc;
39915}
39916
39917
39918/*
39919** Write the supplied master journal name into the journal file for pager
39920** pPager at the current location. The master journal name must be the last
39921** thing written to a journal file. If the pager is in full-sync mode, the
39922** journal file descriptor is advanced to the next sector boundary before
39923** anything is written. The format is:
39924**
39925**   + 4 bytes: PAGER_MJ_PGNO.
39926**   + N bytes: Master journal filename in utf-8.
39927**   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
39928**   + 4 bytes: Master journal name checksum.
39929**   + 8 bytes: aJournalMagic[].
39930**
39931** The master journal page checksum is the sum of the bytes in the master
39932** journal name, where each byte is interpreted as a signed 8-bit integer.
39933**
39934** If zMaster is a NULL pointer (occurs for a single database transaction),
39935** this call is a no-op.
39936*/
39937static int writeMasterJournal(Pager *pPager, const char *zMaster){
39938  int rc;                          /* Return code */
39939  int nMaster;                     /* Length of string zMaster */
39940  i64 iHdrOff;                     /* Offset of header in journal file */
39941  i64 jrnlSize;                    /* Size of journal file on disk */
39942  u32 cksum = 0;                   /* Checksum of string zMaster */
39943
39944  assert( pPager->setMaster==0 );
39945  assert( !pagerUseWal(pPager) );
39946
39947  if( !zMaster
39948   || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
39949   || pPager->journalMode==PAGER_JOURNALMODE_OFF
39950  ){
39951    return SQLITE_OK;
39952  }
39953  pPager->setMaster = 1;
39954  assert( isOpen(pPager->jfd) );
39955  assert( pPager->journalHdr <= pPager->journalOff );
39956
39957  /* Calculate the length in bytes and the checksum of zMaster */
39958  for(nMaster=0; zMaster[nMaster]; nMaster++){
39959    cksum += zMaster[nMaster];
39960  }
39961
39962  /* If in full-sync mode, advance to the next disk sector before writing
39963  ** the master journal name. This is in case the previous page written to
39964  ** the journal has already been synced.
39965  */
39966  if( pPager->fullSync ){
39967    pPager->journalOff = journalHdrOffset(pPager);
39968  }
39969  iHdrOff = pPager->journalOff;
39970
39971  /* Write the master journal data to the end of the journal file. If
39972  ** an error occurs, return the error code to the caller.
39973  */
39974  if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
39975   || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
39976   || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
39977   || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
39978   || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
39979  ){
39980    return rc;
39981  }
39982  pPager->journalOff += (nMaster+20);
39983
39984  /* If the pager is in peristent-journal mode, then the physical
39985  ** journal-file may extend past the end of the master-journal name
39986  ** and 8 bytes of magic data just written to the file. This is
39987  ** dangerous because the code to rollback a hot-journal file
39988  ** will not be able to find the master-journal name to determine
39989  ** whether or not the journal is hot.
39990  **
39991  ** Easiest thing to do in this scenario is to truncate the journal
39992  ** file to the required size.
39993  */
39994  if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
39995   && jrnlSize>pPager->journalOff
39996  ){
39997    rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
39998  }
39999  return rc;
40000}
40001
40002/*
40003** Find a page in the hash table given its page number. Return
40004** a pointer to the page or NULL if the requested page is not
40005** already in memory.
40006*/
40007static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
40008  PgHdr *p;                         /* Return value */
40009
40010  /* It is not possible for a call to PcacheFetch() with createFlag==0 to
40011  ** fail, since no attempt to allocate dynamic memory will be made.
40012  */
40013  (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
40014  return p;
40015}
40016
40017/*
40018** Discard the entire contents of the in-memory page-cache.
40019*/
40020static void pager_reset(Pager *pPager){
40021  sqlite3BackupRestart(pPager->pBackup);
40022  sqlite3PcacheClear(pPager->pPCache);
40023}
40024
40025/*
40026** Free all structures in the Pager.aSavepoint[] array and set both
40027** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
40028** if it is open and the pager is not in exclusive mode.
40029*/
40030static void releaseAllSavepoints(Pager *pPager){
40031  int ii;               /* Iterator for looping through Pager.aSavepoint */
40032  for(ii=0; ii<pPager->nSavepoint; ii++){
40033    sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
40034  }
40035  if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
40036    sqlite3OsClose(pPager->sjfd);
40037  }
40038  sqlite3_free(pPager->aSavepoint);
40039  pPager->aSavepoint = 0;
40040  pPager->nSavepoint = 0;
40041  pPager->nSubRec = 0;
40042}
40043
40044/*
40045** Set the bit number pgno in the PagerSavepoint.pInSavepoint
40046** bitvecs of all open savepoints. Return SQLITE_OK if successful
40047** or SQLITE_NOMEM if a malloc failure occurs.
40048*/
40049static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
40050  int ii;                   /* Loop counter */
40051  int rc = SQLITE_OK;       /* Result code */
40052
40053  for(ii=0; ii<pPager->nSavepoint; ii++){
40054    PagerSavepoint *p = &pPager->aSavepoint[ii];
40055    if( pgno<=p->nOrig ){
40056      rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
40057      testcase( rc==SQLITE_NOMEM );
40058      assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
40059    }
40060  }
40061  return rc;
40062}
40063
40064/*
40065** This function is a no-op if the pager is in exclusive mode and not
40066** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
40067** state.
40068**
40069** If the pager is not in exclusive-access mode, the database file is
40070** completely unlocked. If the file is unlocked and the file-system does
40071** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
40072** closed (if it is open).
40073**
40074** If the pager is in ERROR state when this function is called, the
40075** contents of the pager cache are discarded before switching back to
40076** the OPEN state. Regardless of whether the pager is in exclusive-mode
40077** or not, any journal file left in the file-system will be treated
40078** as a hot-journal and rolled back the next time a read-transaction
40079** is opened (by this or by any other connection).
40080*/
40081static void pager_unlock(Pager *pPager){
40082
40083  assert( pPager->eState==PAGER_READER
40084       || pPager->eState==PAGER_OPEN
40085       || pPager->eState==PAGER_ERROR
40086  );
40087
40088  sqlite3BitvecDestroy(pPager->pInJournal);
40089  pPager->pInJournal = 0;
40090  releaseAllSavepoints(pPager);
40091
40092  if( pagerUseWal(pPager) ){
40093    assert( !isOpen(pPager->jfd) );
40094    sqlite3WalEndReadTransaction(pPager->pWal);
40095    pPager->eState = PAGER_OPEN;
40096  }else if( !pPager->exclusiveMode ){
40097    int rc;                       /* Error code returned by pagerUnlockDb() */
40098    int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
40099
40100    /* If the operating system support deletion of open files, then
40101    ** close the journal file when dropping the database lock.  Otherwise
40102    ** another connection with journal_mode=delete might delete the file
40103    ** out from under us.
40104    */
40105    assert( (PAGER_JOURNALMODE_MEMORY   & 5)!=1 );
40106    assert( (PAGER_JOURNALMODE_OFF      & 5)!=1 );
40107    assert( (PAGER_JOURNALMODE_WAL      & 5)!=1 );
40108    assert( (PAGER_JOURNALMODE_DELETE   & 5)!=1 );
40109    assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
40110    assert( (PAGER_JOURNALMODE_PERSIST  & 5)==1 );
40111    if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
40112     || 1!=(pPager->journalMode & 5)
40113    ){
40114      sqlite3OsClose(pPager->jfd);
40115    }
40116
40117    /* If the pager is in the ERROR state and the call to unlock the database
40118    ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
40119    ** above the #define for UNKNOWN_LOCK for an explanation of why this
40120    ** is necessary.
40121    */
40122    rc = pagerUnlockDb(pPager, NO_LOCK);
40123    if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
40124      pPager->eLock = UNKNOWN_LOCK;
40125    }
40126
40127    /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
40128    ** without clearing the error code. This is intentional - the error
40129    ** code is cleared and the cache reset in the block below.
40130    */
40131    assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
40132    pPager->changeCountDone = 0;
40133    pPager->eState = PAGER_OPEN;
40134  }
40135
40136  /* If Pager.errCode is set, the contents of the pager cache cannot be
40137  ** trusted. Now that there are no outstanding references to the pager,
40138  ** it can safely move back to PAGER_OPEN state. This happens in both
40139  ** normal and exclusive-locking mode.
40140  */
40141  if( pPager->errCode ){
40142    assert( !MEMDB );
40143    pager_reset(pPager);
40144    pPager->changeCountDone = pPager->tempFile;
40145    pPager->eState = PAGER_OPEN;
40146    pPager->errCode = SQLITE_OK;
40147  }
40148
40149  pPager->journalOff = 0;
40150  pPager->journalHdr = 0;
40151  pPager->setMaster = 0;
40152}
40153
40154/*
40155** This function is called whenever an IOERR or FULL error that requires
40156** the pager to transition into the ERROR state may ahve occurred.
40157** The first argument is a pointer to the pager structure, the second
40158** the error-code about to be returned by a pager API function. The
40159** value returned is a copy of the second argument to this function.
40160**
40161** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
40162** IOERR sub-codes, the pager enters the ERROR state and the error code
40163** is stored in Pager.errCode. While the pager remains in the ERROR state,
40164** all major API calls on the Pager will immediately return Pager.errCode.
40165**
40166** The ERROR state indicates that the contents of the pager-cache
40167** cannot be trusted. This state can be cleared by completely discarding
40168** the contents of the pager-cache. If a transaction was active when
40169** the persistent error occurred, then the rollback journal may need
40170** to be replayed to restore the contents of the database file (as if
40171** it were a hot-journal).
40172*/
40173static int pager_error(Pager *pPager, int rc){
40174  int rc2 = rc & 0xff;
40175  assert( rc==SQLITE_OK || !MEMDB );
40176  assert(
40177       pPager->errCode==SQLITE_FULL ||
40178       pPager->errCode==SQLITE_OK ||
40179       (pPager->errCode & 0xff)==SQLITE_IOERR
40180  );
40181  if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
40182    pPager->errCode = rc;
40183    pPager->eState = PAGER_ERROR;
40184  }
40185  return rc;
40186}
40187
40188static int pager_truncate(Pager *pPager, Pgno nPage);
40189
40190/*
40191** This routine ends a transaction. A transaction is usually ended by
40192** either a COMMIT or a ROLLBACK operation. This routine may be called
40193** after rollback of a hot-journal, or if an error occurs while opening
40194** the journal file or writing the very first journal-header of a
40195** database transaction.
40196**
40197** This routine is never called in PAGER_ERROR state. If it is called
40198** in PAGER_NONE or PAGER_SHARED state and the lock held is less
40199** exclusive than a RESERVED lock, it is a no-op.
40200**
40201** Otherwise, any active savepoints are released.
40202**
40203** If the journal file is open, then it is "finalized". Once a journal
40204** file has been finalized it is not possible to use it to roll back a
40205** transaction. Nor will it be considered to be a hot-journal by this
40206** or any other database connection. Exactly how a journal is finalized
40207** depends on whether or not the pager is running in exclusive mode and
40208** the current journal-mode (Pager.journalMode value), as follows:
40209**
40210**   journalMode==MEMORY
40211**     Journal file descriptor is simply closed. This destroys an
40212**     in-memory journal.
40213**
40214**   journalMode==TRUNCATE
40215**     Journal file is truncated to zero bytes in size.
40216**
40217**   journalMode==PERSIST
40218**     The first 28 bytes of the journal file are zeroed. This invalidates
40219**     the first journal header in the file, and hence the entire journal
40220**     file. An invalid journal file cannot be rolled back.
40221**
40222**   journalMode==DELETE
40223**     The journal file is closed and deleted using sqlite3OsDelete().
40224**
40225**     If the pager is running in exclusive mode, this method of finalizing
40226**     the journal file is never used. Instead, if the journalMode is
40227**     DELETE and the pager is in exclusive mode, the method described under
40228**     journalMode==PERSIST is used instead.
40229**
40230** After the journal is finalized, the pager moves to PAGER_READER state.
40231** If running in non-exclusive rollback mode, the lock on the file is
40232** downgraded to a SHARED_LOCK.
40233**
40234** SQLITE_OK is returned if no error occurs. If an error occurs during
40235** any of the IO operations to finalize the journal file or unlock the
40236** database then the IO error code is returned to the user. If the
40237** operation to finalize the journal file fails, then the code still
40238** tries to unlock the database file if not in exclusive mode. If the
40239** unlock operation fails as well, then the first error code related
40240** to the first error encountered (the journal finalization one) is
40241** returned.
40242*/
40243static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
40244  int rc = SQLITE_OK;      /* Error code from journal finalization operation */
40245  int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
40246
40247  /* Do nothing if the pager does not have an open write transaction
40248  ** or at least a RESERVED lock. This function may be called when there
40249  ** is no write-transaction active but a RESERVED or greater lock is
40250  ** held under two circumstances:
40251  **
40252  **   1. After a successful hot-journal rollback, it is called with
40253  **      eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
40254  **
40255  **   2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
40256  **      lock switches back to locking_mode=normal and then executes a
40257  **      read-transaction, this function is called with eState==PAGER_READER
40258  **      and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
40259  */
40260  assert( assert_pager_state(pPager) );
40261  assert( pPager->eState!=PAGER_ERROR );
40262  if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
40263    return SQLITE_OK;
40264  }
40265
40266  releaseAllSavepoints(pPager);
40267  assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
40268  if( isOpen(pPager->jfd) ){
40269    assert( !pagerUseWal(pPager) );
40270
40271    /* Finalize the journal file. */
40272    if( sqlite3IsMemJournal(pPager->jfd) ){
40273      assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
40274      sqlite3OsClose(pPager->jfd);
40275    }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
40276      if( pPager->journalOff==0 ){
40277        rc = SQLITE_OK;
40278      }else{
40279        rc = sqlite3OsTruncate(pPager->jfd, 0);
40280      }
40281      pPager->journalOff = 0;
40282    }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
40283      || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
40284    ){
40285      rc = zeroJournalHdr(pPager, hasMaster);
40286      pPager->journalOff = 0;
40287    }else{
40288      /* This branch may be executed with Pager.journalMode==MEMORY if
40289      ** a hot-journal was just rolled back. In this case the journal
40290      ** file should be closed and deleted. If this connection writes to
40291      ** the database file, it will do so using an in-memory journal.
40292      */
40293      int bDelete = (!pPager->tempFile && sqlite3JournalExists(pPager->jfd));
40294      assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
40295           || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
40296           || pPager->journalMode==PAGER_JOURNALMODE_WAL
40297      );
40298      sqlite3OsClose(pPager->jfd);
40299      if( bDelete ){
40300        rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
40301      }
40302    }
40303  }
40304
40305#ifdef SQLITE_CHECK_PAGES
40306  sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
40307  if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
40308    PgHdr *p = pager_lookup(pPager, 1);
40309    if( p ){
40310      p->pageHash = 0;
40311      sqlite3PagerUnref(p);
40312    }
40313  }
40314#endif
40315
40316  sqlite3BitvecDestroy(pPager->pInJournal);
40317  pPager->pInJournal = 0;
40318  pPager->nRec = 0;
40319  sqlite3PcacheCleanAll(pPager->pPCache);
40320  sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
40321
40322  if( pagerUseWal(pPager) ){
40323    /* Drop the WAL write-lock, if any. Also, if the connection was in
40324    ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
40325    ** lock held on the database file.
40326    */
40327    rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
40328    assert( rc2==SQLITE_OK );
40329  }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
40330    /* This branch is taken when committing a transaction in rollback-journal
40331    ** mode if the database file on disk is larger than the database image.
40332    ** At this point the journal has been finalized and the transaction
40333    ** successfully committed, but the EXCLUSIVE lock is still held on the
40334    ** file. So it is safe to truncate the database file to its minimum
40335    ** required size.  */
40336    assert( pPager->eLock==EXCLUSIVE_LOCK );
40337    rc = pager_truncate(pPager, pPager->dbSize);
40338  }
40339
40340  if( !pPager->exclusiveMode
40341   && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
40342  ){
40343    rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
40344    pPager->changeCountDone = 0;
40345  }
40346  pPager->eState = PAGER_READER;
40347  pPager->setMaster = 0;
40348
40349  return (rc==SQLITE_OK?rc2:rc);
40350}
40351
40352/*
40353** Execute a rollback if a transaction is active and unlock the
40354** database file.
40355**
40356** If the pager has already entered the ERROR state, do not attempt
40357** the rollback at this time. Instead, pager_unlock() is called. The
40358** call to pager_unlock() will discard all in-memory pages, unlock
40359** the database file and move the pager back to OPEN state. If this
40360** means that there is a hot-journal left in the file-system, the next
40361** connection to obtain a shared lock on the pager (which may be this one)
40362** will roll it back.
40363**
40364** If the pager has not already entered the ERROR state, but an IO or
40365** malloc error occurs during a rollback, then this will itself cause
40366** the pager to enter the ERROR state. Which will be cleared by the
40367** call to pager_unlock(), as described above.
40368*/
40369static void pagerUnlockAndRollback(Pager *pPager){
40370  if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
40371    assert( assert_pager_state(pPager) );
40372    if( pPager->eState>=PAGER_WRITER_LOCKED ){
40373      sqlite3BeginBenignMalloc();
40374      sqlite3PagerRollback(pPager);
40375      sqlite3EndBenignMalloc();
40376    }else if( !pPager->exclusiveMode ){
40377      assert( pPager->eState==PAGER_READER );
40378      pager_end_transaction(pPager, 0, 0);
40379    }
40380  }
40381  pager_unlock(pPager);
40382}
40383
40384/*
40385** Parameter aData must point to a buffer of pPager->pageSize bytes
40386** of data. Compute and return a checksum based ont the contents of the
40387** page of data and the current value of pPager->cksumInit.
40388**
40389** This is not a real checksum. It is really just the sum of the
40390** random initial value (pPager->cksumInit) and every 200th byte
40391** of the page data, starting with byte offset (pPager->pageSize%200).
40392** Each byte is interpreted as an 8-bit unsigned integer.
40393**
40394** Changing the formula used to compute this checksum results in an
40395** incompatible journal file format.
40396**
40397** If journal corruption occurs due to a power failure, the most likely
40398** scenario is that one end or the other of the record will be changed.
40399** It is much less likely that the two ends of the journal record will be
40400** correct and the middle be corrupt.  Thus, this "checksum" scheme,
40401** though fast and simple, catches the mostly likely kind of corruption.
40402*/
40403static u32 pager_cksum(Pager *pPager, const u8 *aData){
40404  u32 cksum = pPager->cksumInit;         /* Checksum value to return */
40405  int i = pPager->pageSize-200;          /* Loop counter */
40406  while( i>0 ){
40407    cksum += aData[i];
40408    i -= 200;
40409  }
40410  return cksum;
40411}
40412
40413/*
40414** Report the current page size and number of reserved bytes back
40415** to the codec.
40416*/
40417#ifdef SQLITE_HAS_CODEC
40418static void pagerReportSize(Pager *pPager){
40419  if( pPager->xCodecSizeChng ){
40420    pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
40421                           (int)pPager->nReserve);
40422  }
40423}
40424#else
40425# define pagerReportSize(X)     /* No-op if we do not support a codec */
40426#endif
40427
40428/*
40429** Read a single page from either the journal file (if isMainJrnl==1) or
40430** from the sub-journal (if isMainJrnl==0) and playback that page.
40431** The page begins at offset *pOffset into the file. The *pOffset
40432** value is increased to the start of the next page in the journal.
40433**
40434** The main rollback journal uses checksums - the statement journal does
40435** not.
40436**
40437** If the page number of the page record read from the (sub-)journal file
40438** is greater than the current value of Pager.dbSize, then playback is
40439** skipped and SQLITE_OK is returned.
40440**
40441** If pDone is not NULL, then it is a record of pages that have already
40442** been played back.  If the page at *pOffset has already been played back
40443** (if the corresponding pDone bit is set) then skip the playback.
40444** Make sure the pDone bit corresponding to the *pOffset page is set
40445** prior to returning.
40446**
40447** If the page record is successfully read from the (sub-)journal file
40448** and played back, then SQLITE_OK is returned. If an IO error occurs
40449** while reading the record from the (sub-)journal file or while writing
40450** to the database file, then the IO error code is returned. If data
40451** is successfully read from the (sub-)journal file but appears to be
40452** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
40453** two circumstances:
40454**
40455**   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
40456**   * If the record is being rolled back from the main journal file
40457**     and the checksum field does not match the record content.
40458**
40459** Neither of these two scenarios are possible during a savepoint rollback.
40460**
40461** If this is a savepoint rollback, then memory may have to be dynamically
40462** allocated by this function. If this is the case and an allocation fails,
40463** SQLITE_NOMEM is returned.
40464*/
40465static int pager_playback_one_page(
40466  Pager *pPager,                /* The pager being played back */
40467  i64 *pOffset,                 /* Offset of record to playback */
40468  Bitvec *pDone,                /* Bitvec of pages already played back */
40469  int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
40470  int isSavepnt                 /* True for a savepoint rollback */
40471){
40472  int rc;
40473  PgHdr *pPg;                   /* An existing page in the cache */
40474  Pgno pgno;                    /* The page number of a page in journal */
40475  u32 cksum;                    /* Checksum used for sanity checking */
40476  char *aData;                  /* Temporary storage for the page */
40477  sqlite3_file *jfd;            /* The file descriptor for the journal file */
40478  int isSynced;                 /* True if journal page is synced */
40479
40480  assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
40481  assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
40482  assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
40483  assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
40484
40485  aData = pPager->pTmpSpace;
40486  assert( aData );         /* Temp storage must have already been allocated */
40487  assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
40488
40489  /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
40490  ** or savepoint rollback done at the request of the caller) or this is
40491  ** a hot-journal rollback. If it is a hot-journal rollback, the pager
40492  ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
40493  ** only reads from the main journal, not the sub-journal.
40494  */
40495  assert( pPager->eState>=PAGER_WRITER_CACHEMOD
40496       || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
40497  );
40498  assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
40499
40500  /* Read the page number and page data from the journal or sub-journal
40501  ** file. Return an error code to the caller if an IO error occurs.
40502  */
40503  jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
40504  rc = read32bits(jfd, *pOffset, &pgno);
40505  if( rc!=SQLITE_OK ) return rc;
40506  rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
40507  if( rc!=SQLITE_OK ) return rc;
40508  *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
40509
40510  /* Sanity checking on the page.  This is more important that I originally
40511  ** thought.  If a power failure occurs while the journal is being written,
40512  ** it could cause invalid data to be written into the journal.  We need to
40513  ** detect this invalid data (with high probability) and ignore it.
40514  */
40515  if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
40516    assert( !isSavepnt );
40517    return SQLITE_DONE;
40518  }
40519  if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
40520    return SQLITE_OK;
40521  }
40522  if( isMainJrnl ){
40523    rc = read32bits(jfd, (*pOffset)-4, &cksum);
40524    if( rc ) return rc;
40525    if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
40526      return SQLITE_DONE;
40527    }
40528  }
40529
40530  /* If this page has already been played by before during the current
40531  ** rollback, then don't bother to play it back again.
40532  */
40533  if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
40534    return rc;
40535  }
40536
40537  /* When playing back page 1, restore the nReserve setting
40538  */
40539  if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
40540    pPager->nReserve = ((u8*)aData)[20];
40541    pagerReportSize(pPager);
40542  }
40543
40544  /* If the pager is in CACHEMOD state, then there must be a copy of this
40545  ** page in the pager cache. In this case just update the pager cache,
40546  ** not the database file. The page is left marked dirty in this case.
40547  **
40548  ** An exception to the above rule: If the database is in no-sync mode
40549  ** and a page is moved during an incremental vacuum then the page may
40550  ** not be in the pager cache. Later: if a malloc() or IO error occurs
40551  ** during a Movepage() call, then the page may not be in the cache
40552  ** either. So the condition described in the above paragraph is not
40553  ** assert()able.
40554  **
40555  ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
40556  ** pager cache if it exists and the main file. The page is then marked
40557  ** not dirty. Since this code is only executed in PAGER_OPEN state for
40558  ** a hot-journal rollback, it is guaranteed that the page-cache is empty
40559  ** if the pager is in OPEN state.
40560  **
40561  ** Ticket #1171:  The statement journal might contain page content that is
40562  ** different from the page content at the start of the transaction.
40563  ** This occurs when a page is changed prior to the start of a statement
40564  ** then changed again within the statement.  When rolling back such a
40565  ** statement we must not write to the original database unless we know
40566  ** for certain that original page contents are synced into the main rollback
40567  ** journal.  Otherwise, a power loss might leave modified data in the
40568  ** database file without an entry in the rollback journal that can
40569  ** restore the database to its original form.  Two conditions must be
40570  ** met before writing to the database files. (1) the database must be
40571  ** locked.  (2) we know that the original page content is fully synced
40572  ** in the main journal either because the page is not in cache or else
40573  ** the page is marked as needSync==0.
40574  **
40575  ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
40576  ** is possible to fail a statement on a database that does not yet exist.
40577  ** Do not attempt to write if database file has never been opened.
40578  */
40579  if( pagerUseWal(pPager) ){
40580    pPg = 0;
40581  }else{
40582    pPg = pager_lookup(pPager, pgno);
40583  }
40584  assert( pPg || !MEMDB );
40585  assert( pPager->eState!=PAGER_OPEN || pPg==0 );
40586  PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
40587           PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
40588           (isMainJrnl?"main-journal":"sub-journal")
40589  ));
40590  if( isMainJrnl ){
40591    isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
40592  }else{
40593    isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
40594  }
40595  if( isOpen(pPager->fd)
40596   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
40597   && isSynced
40598  ){
40599    i64 ofst = (pgno-1)*(i64)pPager->pageSize;
40600    testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
40601    assert( !pagerUseWal(pPager) );
40602    rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
40603    if( pgno>pPager->dbFileSize ){
40604      pPager->dbFileSize = pgno;
40605    }
40606    if( pPager->pBackup ){
40607      CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
40608      sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
40609      CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
40610    }
40611  }else if( !isMainJrnl && pPg==0 ){
40612    /* If this is a rollback of a savepoint and data was not written to
40613    ** the database and the page is not in-memory, there is a potential
40614    ** problem. When the page is next fetched by the b-tree layer, it
40615    ** will be read from the database file, which may or may not be
40616    ** current.
40617    **
40618    ** There are a couple of different ways this can happen. All are quite
40619    ** obscure. When running in synchronous mode, this can only happen
40620    ** if the page is on the free-list at the start of the transaction, then
40621    ** populated, then moved using sqlite3PagerMovepage().
40622    **
40623    ** The solution is to add an in-memory page to the cache containing
40624    ** the data just read from the sub-journal. Mark the page as dirty
40625    ** and if the pager requires a journal-sync, then mark the page as
40626    ** requiring a journal-sync before it is written.
40627    */
40628    assert( isSavepnt );
40629    assert( pPager->doNotSpill==0 );
40630    pPager->doNotSpill++;
40631    rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
40632    assert( pPager->doNotSpill==1 );
40633    pPager->doNotSpill--;
40634    if( rc!=SQLITE_OK ) return rc;
40635    pPg->flags &= ~PGHDR_NEED_READ;
40636    sqlite3PcacheMakeDirty(pPg);
40637  }
40638  if( pPg ){
40639    /* No page should ever be explicitly rolled back that is in use, except
40640    ** for page 1 which is held in use in order to keep the lock on the
40641    ** database active. However such a page may be rolled back as a result
40642    ** of an internal error resulting in an automatic call to
40643    ** sqlite3PagerRollback().
40644    */
40645    void *pData;
40646    pData = pPg->pData;
40647    memcpy(pData, (u8*)aData, pPager->pageSize);
40648    pPager->xReiniter(pPg);
40649    if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
40650      /* If the contents of this page were just restored from the main
40651      ** journal file, then its content must be as they were when the
40652      ** transaction was first opened. In this case we can mark the page
40653      ** as clean, since there will be no need to write it out to the
40654      ** database.
40655      **
40656      ** There is one exception to this rule. If the page is being rolled
40657      ** back as part of a savepoint (or statement) rollback from an
40658      ** unsynced portion of the main journal file, then it is not safe
40659      ** to mark the page as clean. This is because marking the page as
40660      ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
40661      ** already in the journal file (recorded in Pager.pInJournal) and
40662      ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
40663      ** again within this transaction, it will be marked as dirty but
40664      ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
40665      ** be written out into the database file before its journal file
40666      ** segment is synced. If a crash occurs during or following this,
40667      ** database corruption may ensue.
40668      */
40669      assert( !pagerUseWal(pPager) );
40670      sqlite3PcacheMakeClean(pPg);
40671    }
40672    pager_set_pagehash(pPg);
40673
40674    /* If this was page 1, then restore the value of Pager.dbFileVers.
40675    ** Do this before any decoding. */
40676    if( pgno==1 ){
40677      memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
40678    }
40679
40680    /* Decode the page just read from disk */
40681    CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
40682    sqlite3PcacheRelease(pPg);
40683  }
40684  return rc;
40685}
40686
40687/*
40688** Parameter zMaster is the name of a master journal file. A single journal
40689** file that referred to the master journal file has just been rolled back.
40690** This routine checks if it is possible to delete the master journal file,
40691** and does so if it is.
40692**
40693** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
40694** available for use within this function.
40695**
40696** When a master journal file is created, it is populated with the names
40697** of all of its child journals, one after another, formatted as utf-8
40698** encoded text. The end of each child journal file is marked with a
40699** nul-terminator byte (0x00). i.e. the entire contents of a master journal
40700** file for a transaction involving two databases might be:
40701**
40702**   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
40703**
40704** A master journal file may only be deleted once all of its child
40705** journals have been rolled back.
40706**
40707** This function reads the contents of the master-journal file into
40708** memory and loops through each of the child journal names. For
40709** each child journal, it checks if:
40710**
40711**   * if the child journal exists, and if so
40712**   * if the child journal contains a reference to master journal
40713**     file zMaster
40714**
40715** If a child journal can be found that matches both of the criteria
40716** above, this function returns without doing anything. Otherwise, if
40717** no such child journal can be found, file zMaster is deleted from
40718** the file-system using sqlite3OsDelete().
40719**
40720** If an IO error within this function, an error code is returned. This
40721** function allocates memory by calling sqlite3Malloc(). If an allocation
40722** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
40723** occur, SQLITE_OK is returned.
40724**
40725** TODO: This function allocates a single block of memory to load
40726** the entire contents of the master journal file. This could be
40727** a couple of kilobytes or so - potentially larger than the page
40728** size.
40729*/
40730static int pager_delmaster(Pager *pPager, const char *zMaster){
40731  sqlite3_vfs *pVfs = pPager->pVfs;
40732  int rc;                   /* Return code */
40733  sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
40734  sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
40735  char *zMasterJournal = 0; /* Contents of master journal file */
40736  i64 nMasterJournal;       /* Size of master journal file */
40737  char *zJournal;           /* Pointer to one journal within MJ file */
40738  char *zMasterPtr;         /* Space to hold MJ filename from a journal file */
40739  int nMasterPtr;           /* Amount of space allocated to zMasterPtr[] */
40740
40741  /* Allocate space for both the pJournal and pMaster file descriptors.
40742  ** If successful, open the master journal file for reading.
40743  */
40744  pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
40745  pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
40746  if( !pMaster ){
40747    rc = SQLITE_NOMEM;
40748  }else{
40749    const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
40750    rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
40751  }
40752  if( rc!=SQLITE_OK ) goto delmaster_out;
40753
40754  /* Load the entire master journal file into space obtained from
40755  ** sqlite3_malloc() and pointed to by zMasterJournal.   Also obtain
40756  ** sufficient space (in zMasterPtr) to hold the names of master
40757  ** journal files extracted from regular rollback-journals.
40758  */
40759  rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
40760  if( rc!=SQLITE_OK ) goto delmaster_out;
40761  nMasterPtr = pVfs->mxPathname+1;
40762  zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
40763  if( !zMasterJournal ){
40764    rc = SQLITE_NOMEM;
40765    goto delmaster_out;
40766  }
40767  zMasterPtr = &zMasterJournal[nMasterJournal+1];
40768  rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
40769  if( rc!=SQLITE_OK ) goto delmaster_out;
40770  zMasterJournal[nMasterJournal] = 0;
40771
40772  zJournal = zMasterJournal;
40773  while( (zJournal-zMasterJournal)<nMasterJournal ){
40774    int exists;
40775    rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
40776    if( rc!=SQLITE_OK ){
40777      goto delmaster_out;
40778    }
40779    if( exists ){
40780      /* One of the journals pointed to by the master journal exists.
40781      ** Open it and check if it points at the master journal. If
40782      ** so, return without deleting the master journal file.
40783      */
40784      int c;
40785      int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
40786      rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
40787      if( rc!=SQLITE_OK ){
40788        goto delmaster_out;
40789      }
40790
40791      rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
40792      sqlite3OsClose(pJournal);
40793      if( rc!=SQLITE_OK ){
40794        goto delmaster_out;
40795      }
40796
40797      c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
40798      if( c ){
40799        /* We have a match. Do not delete the master journal file. */
40800        goto delmaster_out;
40801      }
40802    }
40803    zJournal += (sqlite3Strlen30(zJournal)+1);
40804  }
40805
40806  sqlite3OsClose(pMaster);
40807  rc = sqlite3OsDelete(pVfs, zMaster, 0);
40808
40809delmaster_out:
40810  sqlite3_free(zMasterJournal);
40811  if( pMaster ){
40812    sqlite3OsClose(pMaster);
40813    assert( !isOpen(pJournal) );
40814    sqlite3_free(pMaster);
40815  }
40816  return rc;
40817}
40818
40819
40820/*
40821** This function is used to change the actual size of the database
40822** file in the file-system. This only happens when committing a transaction,
40823** or rolling back a transaction (including rolling back a hot-journal).
40824**
40825** If the main database file is not open, or the pager is not in either
40826** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
40827** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
40828** If the file on disk is currently larger than nPage pages, then use the VFS
40829** xTruncate() method to truncate it.
40830**
40831** Or, it might might be the case that the file on disk is smaller than
40832** nPage pages. Some operating system implementations can get confused if
40833** you try to truncate a file to some size that is larger than it
40834** currently is, so detect this case and write a single zero byte to
40835** the end of the new file instead.
40836**
40837** If successful, return SQLITE_OK. If an IO error occurs while modifying
40838** the database file, return the error code to the caller.
40839*/
40840static int pager_truncate(Pager *pPager, Pgno nPage){
40841  int rc = SQLITE_OK;
40842  assert( pPager->eState!=PAGER_ERROR );
40843  assert( pPager->eState!=PAGER_READER );
40844
40845  if( isOpen(pPager->fd)
40846   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
40847  ){
40848    i64 currentSize, newSize;
40849    int szPage = pPager->pageSize;
40850    assert( pPager->eLock==EXCLUSIVE_LOCK );
40851    /* TODO: Is it safe to use Pager.dbFileSize here? */
40852    rc = sqlite3OsFileSize(pPager->fd, &currentSize);
40853    newSize = szPage*(i64)nPage;
40854    if( rc==SQLITE_OK && currentSize!=newSize ){
40855      if( currentSize>newSize ){
40856        rc = sqlite3OsTruncate(pPager->fd, newSize);
40857      }else if( (currentSize+szPage)<=newSize ){
40858        char *pTmp = pPager->pTmpSpace;
40859        memset(pTmp, 0, szPage);
40860        testcase( (newSize-szPage) == currentSize );
40861        testcase( (newSize-szPage) >  currentSize );
40862        rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
40863      }
40864      if( rc==SQLITE_OK ){
40865        pPager->dbFileSize = nPage;
40866      }
40867    }
40868  }
40869  return rc;
40870}
40871
40872/*
40873** Return a sanitized version of the sector-size of OS file pFile. The
40874** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
40875*/
40876SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
40877  int iRet = sqlite3OsSectorSize(pFile);
40878  if( iRet<32 ){
40879    iRet = 512;
40880  }else if( iRet>MAX_SECTOR_SIZE ){
40881    assert( MAX_SECTOR_SIZE>=512 );
40882    iRet = MAX_SECTOR_SIZE;
40883  }
40884  return iRet;
40885}
40886
40887/*
40888** Set the value of the Pager.sectorSize variable for the given
40889** pager based on the value returned by the xSectorSize method
40890** of the open database file. The sector size will be used used
40891** to determine the size and alignment of journal header and
40892** master journal pointers within created journal files.
40893**
40894** For temporary files the effective sector size is always 512 bytes.
40895**
40896** Otherwise, for non-temporary files, the effective sector size is
40897** the value returned by the xSectorSize() method rounded up to 32 if
40898** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
40899** is greater than MAX_SECTOR_SIZE.
40900**
40901** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
40902** the effective sector size to its minimum value (512).  The purpose of
40903** pPager->sectorSize is to define the "blast radius" of bytes that
40904** might change if a crash occurs while writing to a single byte in
40905** that range.  But with POWERSAFE_OVERWRITE, the blast radius is zero
40906** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
40907** size.  For backwards compatibility of the rollback journal file format,
40908** we cannot reduce the effective sector size below 512.
40909*/
40910static void setSectorSize(Pager *pPager){
40911  assert( isOpen(pPager->fd) || pPager->tempFile );
40912
40913  if( pPager->tempFile
40914   || (sqlite3OsDeviceCharacteristics(pPager->fd) &
40915              SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
40916  ){
40917    /* Sector size doesn't matter for temporary files. Also, the file
40918    ** may not have been opened yet, in which case the OsSectorSize()
40919    ** call will segfault. */
40920    pPager->sectorSize = 512;
40921  }else{
40922    pPager->sectorSize = sqlite3SectorSize(pPager->fd);
40923  }
40924}
40925
40926/*
40927** Playback the journal and thus restore the database file to
40928** the state it was in before we started making changes.
40929**
40930** The journal file format is as follows:
40931**
40932**  (1)  8 byte prefix.  A copy of aJournalMagic[].
40933**  (2)  4 byte big-endian integer which is the number of valid page records
40934**       in the journal.  If this value is 0xffffffff, then compute the
40935**       number of page records from the journal size.
40936**  (3)  4 byte big-endian integer which is the initial value for the
40937**       sanity checksum.
40938**  (4)  4 byte integer which is the number of pages to truncate the
40939**       database to during a rollback.
40940**  (5)  4 byte big-endian integer which is the sector size.  The header
40941**       is this many bytes in size.
40942**  (6)  4 byte big-endian integer which is the page size.
40943**  (7)  zero padding out to the next sector size.
40944**  (8)  Zero or more pages instances, each as follows:
40945**        +  4 byte page number.
40946**        +  pPager->pageSize bytes of data.
40947**        +  4 byte checksum
40948**
40949** When we speak of the journal header, we mean the first 7 items above.
40950** Each entry in the journal is an instance of the 8th item.
40951**
40952** Call the value from the second bullet "nRec".  nRec is the number of
40953** valid page entries in the journal.  In most cases, you can compute the
40954** value of nRec from the size of the journal file.  But if a power
40955** failure occurred while the journal was being written, it could be the
40956** case that the size of the journal file had already been increased but
40957** the extra entries had not yet made it safely to disk.  In such a case,
40958** the value of nRec computed from the file size would be too large.  For
40959** that reason, we always use the nRec value in the header.
40960**
40961** If the nRec value is 0xffffffff it means that nRec should be computed
40962** from the file size.  This value is used when the user selects the
40963** no-sync option for the journal.  A power failure could lead to corruption
40964** in this case.  But for things like temporary table (which will be
40965** deleted when the power is restored) we don't care.
40966**
40967** If the file opened as the journal file is not a well-formed
40968** journal file then all pages up to the first corrupted page are rolled
40969** back (or no pages if the journal header is corrupted). The journal file
40970** is then deleted and SQLITE_OK returned, just as if no corruption had
40971** been encountered.
40972**
40973** If an I/O or malloc() error occurs, the journal-file is not deleted
40974** and an error code is returned.
40975**
40976** The isHot parameter indicates that we are trying to rollback a journal
40977** that might be a hot journal.  Or, it could be that the journal is
40978** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
40979** If the journal really is hot, reset the pager cache prior rolling
40980** back any content.  If the journal is merely persistent, no reset is
40981** needed.
40982*/
40983static int pager_playback(Pager *pPager, int isHot){
40984  sqlite3_vfs *pVfs = pPager->pVfs;
40985  i64 szJ;                 /* Size of the journal file in bytes */
40986  u32 nRec;                /* Number of Records in the journal */
40987  u32 u;                   /* Unsigned loop counter */
40988  Pgno mxPg = 0;           /* Size of the original file in pages */
40989  int rc;                  /* Result code of a subroutine */
40990  int res = 1;             /* Value returned by sqlite3OsAccess() */
40991  char *zMaster = 0;       /* Name of master journal file if any */
40992  int needPagerReset;      /* True to reset page prior to first page rollback */
40993  int nPlayback = 0;       /* Total number of pages restored from journal */
40994
40995  /* Figure out how many records are in the journal.  Abort early if
40996  ** the journal is empty.
40997  */
40998  assert( isOpen(pPager->jfd) );
40999  rc = sqlite3OsFileSize(pPager->jfd, &szJ);
41000  if( rc!=SQLITE_OK ){
41001    goto end_playback;
41002  }
41003
41004  /* Read the master journal name from the journal, if it is present.
41005  ** If a master journal file name is specified, but the file is not
41006  ** present on disk, then the journal is not hot and does not need to be
41007  ** played back.
41008  **
41009  ** TODO: Technically the following is an error because it assumes that
41010  ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
41011  ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
41012  **  mxPathname is 512, which is the same as the minimum allowable value
41013  ** for pageSize.
41014  */
41015  zMaster = pPager->pTmpSpace;
41016  rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
41017  if( rc==SQLITE_OK && zMaster[0] ){
41018    rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
41019  }
41020  zMaster = 0;
41021  if( rc!=SQLITE_OK || !res ){
41022    goto end_playback;
41023  }
41024  pPager->journalOff = 0;
41025  needPagerReset = isHot;
41026
41027  /* This loop terminates either when a readJournalHdr() or
41028  ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
41029  ** occurs.
41030  */
41031  while( 1 ){
41032    /* Read the next journal header from the journal file.  If there are
41033    ** not enough bytes left in the journal file for a complete header, or
41034    ** it is corrupted, then a process must have failed while writing it.
41035    ** This indicates nothing more needs to be rolled back.
41036    */
41037    rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
41038    if( rc!=SQLITE_OK ){
41039      if( rc==SQLITE_DONE ){
41040        rc = SQLITE_OK;
41041      }
41042      goto end_playback;
41043    }
41044
41045    /* If nRec is 0xffffffff, then this journal was created by a process
41046    ** working in no-sync mode. This means that the rest of the journal
41047    ** file consists of pages, there are no more journal headers. Compute
41048    ** the value of nRec based on this assumption.
41049    */
41050    if( nRec==0xffffffff ){
41051      assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
41052      nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
41053    }
41054
41055    /* If nRec is 0 and this rollback is of a transaction created by this
41056    ** process and if this is the final header in the journal, then it means
41057    ** that this part of the journal was being filled but has not yet been
41058    ** synced to disk.  Compute the number of pages based on the remaining
41059    ** size of the file.
41060    **
41061    ** The third term of the test was added to fix ticket #2565.
41062    ** When rolling back a hot journal, nRec==0 always means that the next
41063    ** chunk of the journal contains zero pages to be rolled back.  But
41064    ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
41065    ** the journal, it means that the journal might contain additional
41066    ** pages that need to be rolled back and that the number of pages
41067    ** should be computed based on the journal file size.
41068    */
41069    if( nRec==0 && !isHot &&
41070        pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
41071      nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
41072    }
41073
41074    /* If this is the first header read from the journal, truncate the
41075    ** database file back to its original size.
41076    */
41077    if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
41078      rc = pager_truncate(pPager, mxPg);
41079      if( rc!=SQLITE_OK ){
41080        goto end_playback;
41081      }
41082      pPager->dbSize = mxPg;
41083    }
41084
41085    /* Copy original pages out of the journal and back into the
41086    ** database file and/or page cache.
41087    */
41088    for(u=0; u<nRec; u++){
41089      if( needPagerReset ){
41090        pager_reset(pPager);
41091        needPagerReset = 0;
41092      }
41093      rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
41094      if( rc==SQLITE_OK ){
41095        nPlayback++;
41096      }else{
41097        if( rc==SQLITE_DONE ){
41098          pPager->journalOff = szJ;
41099          break;
41100        }else if( rc==SQLITE_IOERR_SHORT_READ ){
41101          /* If the journal has been truncated, simply stop reading and
41102          ** processing the journal. This might happen if the journal was
41103          ** not completely written and synced prior to a crash.  In that
41104          ** case, the database should have never been written in the
41105          ** first place so it is OK to simply abandon the rollback. */
41106          rc = SQLITE_OK;
41107          goto end_playback;
41108        }else{
41109          /* If we are unable to rollback, quit and return the error
41110          ** code.  This will cause the pager to enter the error state
41111          ** so that no further harm will be done.  Perhaps the next
41112          ** process to come along will be able to rollback the database.
41113          */
41114          goto end_playback;
41115        }
41116      }
41117    }
41118  }
41119  /*NOTREACHED*/
41120  assert( 0 );
41121
41122end_playback:
41123  /* Following a rollback, the database file should be back in its original
41124  ** state prior to the start of the transaction, so invoke the
41125  ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
41126  ** assertion that the transaction counter was modified.
41127  */
41128#ifdef SQLITE_DEBUG
41129  if( pPager->fd->pMethods ){
41130    sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
41131  }
41132#endif
41133
41134  /* If this playback is happening automatically as a result of an IO or
41135  ** malloc error that occurred after the change-counter was updated but
41136  ** before the transaction was committed, then the change-counter
41137  ** modification may just have been reverted. If this happens in exclusive
41138  ** mode, then subsequent transactions performed by the connection will not
41139  ** update the change-counter at all. This may lead to cache inconsistency
41140  ** problems for other processes at some point in the future. So, just
41141  ** in case this has happened, clear the changeCountDone flag now.
41142  */
41143  pPager->changeCountDone = pPager->tempFile;
41144
41145  if( rc==SQLITE_OK ){
41146    zMaster = pPager->pTmpSpace;
41147    rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
41148    testcase( rc!=SQLITE_OK );
41149  }
41150  if( rc==SQLITE_OK
41151   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
41152  ){
41153    rc = sqlite3PagerSync(pPager);
41154  }
41155  if( rc==SQLITE_OK ){
41156    rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0);
41157    testcase( rc!=SQLITE_OK );
41158  }
41159  if( rc==SQLITE_OK && zMaster[0] && res ){
41160    /* If there was a master journal and this routine will return success,
41161    ** see if it is possible to delete the master journal.
41162    */
41163    rc = pager_delmaster(pPager, zMaster);
41164    testcase( rc!=SQLITE_OK );
41165  }
41166  if( isHot && nPlayback ){
41167    sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
41168                nPlayback, pPager->zJournal);
41169  }
41170
41171  /* The Pager.sectorSize variable may have been updated while rolling
41172  ** back a journal created by a process with a different sector size
41173  ** value. Reset it to the correct value for this process.
41174  */
41175  setSectorSize(pPager);
41176  return rc;
41177}
41178
41179
41180/*
41181** Read the content for page pPg out of the database file and into
41182** pPg->pData. A shared lock or greater must be held on the database
41183** file before this function is called.
41184**
41185** If page 1 is read, then the value of Pager.dbFileVers[] is set to
41186** the value read from the database file.
41187**
41188** If an IO error occurs, then the IO error is returned to the caller.
41189** Otherwise, SQLITE_OK is returned.
41190*/
41191static int readDbPage(PgHdr *pPg, u32 iFrame){
41192  Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
41193  Pgno pgno = pPg->pgno;       /* Page number to read */
41194  int rc = SQLITE_OK;          /* Return code */
41195  int pgsz = pPager->pageSize; /* Number of bytes to read */
41196
41197  assert( pPager->eState>=PAGER_READER && !MEMDB );
41198  assert( isOpen(pPager->fd) );
41199
41200  if( NEVER(!isOpen(pPager->fd)) ){
41201    assert( pPager->tempFile );
41202    memset(pPg->pData, 0, pPager->pageSize);
41203    return SQLITE_OK;
41204  }
41205
41206#ifndef SQLITE_OMIT_WAL
41207  if( iFrame ){
41208    /* Try to pull the page from the write-ahead log. */
41209    rc = sqlite3WalReadFrame(pPager->pWal, iFrame, pgsz, pPg->pData);
41210  }else
41211#endif
41212  {
41213    i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
41214    rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
41215    if( rc==SQLITE_IOERR_SHORT_READ ){
41216      rc = SQLITE_OK;
41217    }
41218  }
41219
41220  if( pgno==1 ){
41221    if( rc ){
41222      /* If the read is unsuccessful, set the dbFileVers[] to something
41223      ** that will never be a valid file version.  dbFileVers[] is a copy
41224      ** of bytes 24..39 of the database.  Bytes 28..31 should always be
41225      ** zero or the size of the database in page. Bytes 32..35 and 35..39
41226      ** should be page numbers which are never 0xffffffff.  So filling
41227      ** pPager->dbFileVers[] with all 0xff bytes should suffice.
41228      **
41229      ** For an encrypted database, the situation is more complex:  bytes
41230      ** 24..39 of the database are white noise.  But the probability of
41231      ** white noising equaling 16 bytes of 0xff is vanishingly small so
41232      ** we should still be ok.
41233      */
41234      memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
41235    }else{
41236      u8 *dbFileVers = &((u8*)pPg->pData)[24];
41237      memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
41238    }
41239  }
41240  CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
41241
41242  PAGER_INCR(sqlite3_pager_readdb_count);
41243  PAGER_INCR(pPager->nRead);
41244  IOTRACE(("PGIN %p %d\n", pPager, pgno));
41245  PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
41246               PAGERID(pPager), pgno, pager_pagehash(pPg)));
41247
41248  return rc;
41249}
41250
41251/*
41252** Update the value of the change-counter at offsets 24 and 92 in
41253** the header and the sqlite version number at offset 96.
41254**
41255** This is an unconditional update.  See also the pager_incr_changecounter()
41256** routine which only updates the change-counter if the update is actually
41257** needed, as determined by the pPager->changeCountDone state variable.
41258*/
41259static void pager_write_changecounter(PgHdr *pPg){
41260  u32 change_counter;
41261
41262  /* Increment the value just read and write it back to byte 24. */
41263  change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
41264  put32bits(((char*)pPg->pData)+24, change_counter);
41265
41266  /* Also store the SQLite version number in bytes 96..99 and in
41267  ** bytes 92..95 store the change counter for which the version number
41268  ** is valid. */
41269  put32bits(((char*)pPg->pData)+92, change_counter);
41270  put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
41271}
41272
41273#ifndef SQLITE_OMIT_WAL
41274/*
41275** This function is invoked once for each page that has already been
41276** written into the log file when a WAL transaction is rolled back.
41277** Parameter iPg is the page number of said page. The pCtx argument
41278** is actually a pointer to the Pager structure.
41279**
41280** If page iPg is present in the cache, and has no outstanding references,
41281** it is discarded. Otherwise, if there are one or more outstanding
41282** references, the page content is reloaded from the database. If the
41283** attempt to reload content from the database is required and fails,
41284** return an SQLite error code. Otherwise, SQLITE_OK.
41285*/
41286static int pagerUndoCallback(void *pCtx, Pgno iPg){
41287  int rc = SQLITE_OK;
41288  Pager *pPager = (Pager *)pCtx;
41289  PgHdr *pPg;
41290
41291  assert( pagerUseWal(pPager) );
41292  pPg = sqlite3PagerLookup(pPager, iPg);
41293  if( pPg ){
41294    if( sqlite3PcachePageRefcount(pPg)==1 ){
41295      sqlite3PcacheDrop(pPg);
41296    }else{
41297      u32 iFrame = 0;
41298      rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
41299      if( rc==SQLITE_OK ){
41300        rc = readDbPage(pPg, iFrame);
41301      }
41302      if( rc==SQLITE_OK ){
41303        pPager->xReiniter(pPg);
41304      }
41305      sqlite3PagerUnref(pPg);
41306    }
41307  }
41308
41309  /* Normally, if a transaction is rolled back, any backup processes are
41310  ** updated as data is copied out of the rollback journal and into the
41311  ** database. This is not generally possible with a WAL database, as
41312  ** rollback involves simply truncating the log file. Therefore, if one
41313  ** or more frames have already been written to the log (and therefore
41314  ** also copied into the backup databases) as part of this transaction,
41315  ** the backups must be restarted.
41316  */
41317  sqlite3BackupRestart(pPager->pBackup);
41318
41319  return rc;
41320}
41321
41322/*
41323** This function is called to rollback a transaction on a WAL database.
41324*/
41325static int pagerRollbackWal(Pager *pPager){
41326  int rc;                         /* Return Code */
41327  PgHdr *pList;                   /* List of dirty pages to revert */
41328
41329  /* For all pages in the cache that are currently dirty or have already
41330  ** been written (but not committed) to the log file, do one of the
41331  ** following:
41332  **
41333  **   + Discard the cached page (if refcount==0), or
41334  **   + Reload page content from the database (if refcount>0).
41335  */
41336  pPager->dbSize = pPager->dbOrigSize;
41337  rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
41338  pList = sqlite3PcacheDirtyList(pPager->pPCache);
41339  while( pList && rc==SQLITE_OK ){
41340    PgHdr *pNext = pList->pDirty;
41341    rc = pagerUndoCallback((void *)pPager, pList->pgno);
41342    pList = pNext;
41343  }
41344
41345  return rc;
41346}
41347
41348/*
41349** This function is a wrapper around sqlite3WalFrames(). As well as logging
41350** the contents of the list of pages headed by pList (connected by pDirty),
41351** this function notifies any active backup processes that the pages have
41352** changed.
41353**
41354** The list of pages passed into this routine is always sorted by page number.
41355** Hence, if page 1 appears anywhere on the list, it will be the first page.
41356*/
41357static int pagerWalFrames(
41358  Pager *pPager,                  /* Pager object */
41359  PgHdr *pList,                   /* List of frames to log */
41360  Pgno nTruncate,                 /* Database size after this commit */
41361  int isCommit                    /* True if this is a commit */
41362){
41363  int rc;                         /* Return code */
41364  int nList;                      /* Number of pages in pList */
41365#if defined(SQLITE_DEBUG) || defined(SQLITE_CHECK_PAGES)
41366  PgHdr *p;                       /* For looping over pages */
41367#endif
41368
41369  assert( pPager->pWal );
41370  assert( pList );
41371#ifdef SQLITE_DEBUG
41372  /* Verify that the page list is in accending order */
41373  for(p=pList; p && p->pDirty; p=p->pDirty){
41374    assert( p->pgno < p->pDirty->pgno );
41375  }
41376#endif
41377
41378  assert( pList->pDirty==0 || isCommit );
41379  if( isCommit ){
41380    /* If a WAL transaction is being committed, there is no point in writing
41381    ** any pages with page numbers greater than nTruncate into the WAL file.
41382    ** They will never be read by any client. So remove them from the pDirty
41383    ** list here. */
41384    PgHdr *p;
41385    PgHdr **ppNext = &pList;
41386    nList = 0;
41387    for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
41388      if( p->pgno<=nTruncate ){
41389        ppNext = &p->pDirty;
41390        nList++;
41391      }
41392    }
41393    assert( pList );
41394  }else{
41395    nList = 1;
41396  }
41397  pPager->aStat[PAGER_STAT_WRITE] += nList;
41398
41399  if( pList->pgno==1 ) pager_write_changecounter(pList);
41400  rc = sqlite3WalFrames(pPager->pWal,
41401      pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
41402  );
41403  if( rc==SQLITE_OK && pPager->pBackup ){
41404    PgHdr *p;
41405    for(p=pList; p; p=p->pDirty){
41406      sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
41407    }
41408  }
41409
41410#ifdef SQLITE_CHECK_PAGES
41411  pList = sqlite3PcacheDirtyList(pPager->pPCache);
41412  for(p=pList; p; p=p->pDirty){
41413    pager_set_pagehash(p);
41414  }
41415#endif
41416
41417  return rc;
41418}
41419
41420/*
41421** Begin a read transaction on the WAL.
41422**
41423** This routine used to be called "pagerOpenSnapshot()" because it essentially
41424** makes a snapshot of the database at the current point in time and preserves
41425** that snapshot for use by the reader in spite of concurrently changes by
41426** other writers or checkpointers.
41427*/
41428static int pagerBeginReadTransaction(Pager *pPager){
41429  int rc;                         /* Return code */
41430  int changed = 0;                /* True if cache must be reset */
41431
41432  assert( pagerUseWal(pPager) );
41433  assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
41434
41435  /* sqlite3WalEndReadTransaction() was not called for the previous
41436  ** transaction in locking_mode=EXCLUSIVE.  So call it now.  If we
41437  ** are in locking_mode=NORMAL and EndRead() was previously called,
41438  ** the duplicate call is harmless.
41439  */
41440  sqlite3WalEndReadTransaction(pPager->pWal);
41441
41442  rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
41443  if( rc!=SQLITE_OK || changed ){
41444    pager_reset(pPager);
41445    if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
41446  }
41447
41448  return rc;
41449}
41450#endif
41451
41452/*
41453** This function is called as part of the transition from PAGER_OPEN
41454** to PAGER_READER state to determine the size of the database file
41455** in pages (assuming the page size currently stored in Pager.pageSize).
41456**
41457** If no error occurs, SQLITE_OK is returned and the size of the database
41458** in pages is stored in *pnPage. Otherwise, an error code (perhaps
41459** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
41460*/
41461static int pagerPagecount(Pager *pPager, Pgno *pnPage){
41462  Pgno nPage;                     /* Value to return via *pnPage */
41463
41464  /* Query the WAL sub-system for the database size. The WalDbsize()
41465  ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
41466  ** if the database size is not available. The database size is not
41467  ** available from the WAL sub-system if the log file is empty or
41468  ** contains no valid committed transactions.
41469  */
41470  assert( pPager->eState==PAGER_OPEN );
41471  assert( pPager->eLock>=SHARED_LOCK );
41472  nPage = sqlite3WalDbsize(pPager->pWal);
41473
41474  /* If the database size was not available from the WAL sub-system,
41475  ** determine it based on the size of the database file. If the size
41476  ** of the database file is not an integer multiple of the page-size,
41477  ** round down to the nearest page. Except, any file larger than 0
41478  ** bytes in size is considered to contain at least one page.
41479  */
41480  if( nPage==0 ){
41481    i64 n = 0;                    /* Size of db file in bytes */
41482    assert( isOpen(pPager->fd) || pPager->tempFile );
41483    if( isOpen(pPager->fd) ){
41484      int rc = sqlite3OsFileSize(pPager->fd, &n);
41485      if( rc!=SQLITE_OK ){
41486        return rc;
41487      }
41488    }
41489    nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
41490  }
41491
41492  /* If the current number of pages in the file is greater than the
41493  ** configured maximum pager number, increase the allowed limit so
41494  ** that the file can be read.
41495  */
41496  if( nPage>pPager->mxPgno ){
41497    pPager->mxPgno = (Pgno)nPage;
41498  }
41499
41500  *pnPage = nPage;
41501  return SQLITE_OK;
41502}
41503
41504#ifndef SQLITE_OMIT_WAL
41505/*
41506** Check if the *-wal file that corresponds to the database opened by pPager
41507** exists if the database is not empy, or verify that the *-wal file does
41508** not exist (by deleting it) if the database file is empty.
41509**
41510** If the database is not empty and the *-wal file exists, open the pager
41511** in WAL mode.  If the database is empty or if no *-wal file exists and
41512** if no error occurs, make sure Pager.journalMode is not set to
41513** PAGER_JOURNALMODE_WAL.
41514**
41515** Return SQLITE_OK or an error code.
41516**
41517** The caller must hold a SHARED lock on the database file to call this
41518** function. Because an EXCLUSIVE lock on the db file is required to delete
41519** a WAL on a none-empty database, this ensures there is no race condition
41520** between the xAccess() below and an xDelete() being executed by some
41521** other connection.
41522*/
41523static int pagerOpenWalIfPresent(Pager *pPager){
41524  int rc = SQLITE_OK;
41525  assert( pPager->eState==PAGER_OPEN );
41526  assert( pPager->eLock>=SHARED_LOCK );
41527
41528  if( !pPager->tempFile ){
41529    int isWal;                    /* True if WAL file exists */
41530    Pgno nPage;                   /* Size of the database file */
41531
41532    rc = pagerPagecount(pPager, &nPage);
41533    if( rc ) return rc;
41534    if( nPage==0 ){
41535      rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
41536      if( rc==SQLITE_IOERR_DELETE_NOENT ) rc = SQLITE_OK;
41537      isWal = 0;
41538    }else{
41539      rc = sqlite3OsAccess(
41540          pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
41541      );
41542    }
41543    if( rc==SQLITE_OK ){
41544      if( isWal ){
41545        testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
41546        rc = sqlite3PagerOpenWal(pPager, 0);
41547      }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
41548        pPager->journalMode = PAGER_JOURNALMODE_DELETE;
41549      }
41550    }
41551  }
41552  return rc;
41553}
41554#endif
41555
41556/*
41557** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
41558** the entire master journal file. The case pSavepoint==NULL occurs when
41559** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
41560** savepoint.
41561**
41562** When pSavepoint is not NULL (meaning a non-transaction savepoint is
41563** being rolled back), then the rollback consists of up to three stages,
41564** performed in the order specified:
41565**
41566**   * Pages are played back from the main journal starting at byte
41567**     offset PagerSavepoint.iOffset and continuing to
41568**     PagerSavepoint.iHdrOffset, or to the end of the main journal
41569**     file if PagerSavepoint.iHdrOffset is zero.
41570**
41571**   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
41572**     back starting from the journal header immediately following
41573**     PagerSavepoint.iHdrOffset to the end of the main journal file.
41574**
41575**   * Pages are then played back from the sub-journal file, starting
41576**     with the PagerSavepoint.iSubRec and continuing to the end of
41577**     the journal file.
41578**
41579** Throughout the rollback process, each time a page is rolled back, the
41580** corresponding bit is set in a bitvec structure (variable pDone in the
41581** implementation below). This is used to ensure that a page is only
41582** rolled back the first time it is encountered in either journal.
41583**
41584** If pSavepoint is NULL, then pages are only played back from the main
41585** journal file. There is no need for a bitvec in this case.
41586**
41587** In either case, before playback commences the Pager.dbSize variable
41588** is reset to the value that it held at the start of the savepoint
41589** (or transaction). No page with a page-number greater than this value
41590** is played back. If one is encountered it is simply skipped.
41591*/
41592static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
41593  i64 szJ;                 /* Effective size of the main journal */
41594  i64 iHdrOff;             /* End of first segment of main-journal records */
41595  int rc = SQLITE_OK;      /* Return code */
41596  Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
41597
41598  assert( pPager->eState!=PAGER_ERROR );
41599  assert( pPager->eState>=PAGER_WRITER_LOCKED );
41600
41601  /* Allocate a bitvec to use to store the set of pages rolled back */
41602  if( pSavepoint ){
41603    pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
41604    if( !pDone ){
41605      return SQLITE_NOMEM;
41606    }
41607  }
41608
41609  /* Set the database size back to the value it was before the savepoint
41610  ** being reverted was opened.
41611  */
41612  pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
41613  pPager->changeCountDone = pPager->tempFile;
41614
41615  if( !pSavepoint && pagerUseWal(pPager) ){
41616    return pagerRollbackWal(pPager);
41617  }
41618
41619  /* Use pPager->journalOff as the effective size of the main rollback
41620  ** journal.  The actual file might be larger than this in
41621  ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
41622  ** past pPager->journalOff is off-limits to us.
41623  */
41624  szJ = pPager->journalOff;
41625  assert( pagerUseWal(pPager)==0 || szJ==0 );
41626
41627  /* Begin by rolling back records from the main journal starting at
41628  ** PagerSavepoint.iOffset and continuing to the next journal header.
41629  ** There might be records in the main journal that have a page number
41630  ** greater than the current database size (pPager->dbSize) but those
41631  ** will be skipped automatically.  Pages are added to pDone as they
41632  ** are played back.
41633  */
41634  if( pSavepoint && !pagerUseWal(pPager) ){
41635    iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
41636    pPager->journalOff = pSavepoint->iOffset;
41637    while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
41638      rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
41639    }
41640    assert( rc!=SQLITE_DONE );
41641  }else{
41642    pPager->journalOff = 0;
41643  }
41644
41645  /* Continue rolling back records out of the main journal starting at
41646  ** the first journal header seen and continuing until the effective end
41647  ** of the main journal file.  Continue to skip out-of-range pages and
41648  ** continue adding pages rolled back to pDone.
41649  */
41650  while( rc==SQLITE_OK && pPager->journalOff<szJ ){
41651    u32 ii;            /* Loop counter */
41652    u32 nJRec = 0;     /* Number of Journal Records */
41653    u32 dummy;
41654    rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
41655    assert( rc!=SQLITE_DONE );
41656
41657    /*
41658    ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
41659    ** test is related to ticket #2565.  See the discussion in the
41660    ** pager_playback() function for additional information.
41661    */
41662    if( nJRec==0
41663     && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
41664    ){
41665      nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
41666    }
41667    for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
41668      rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
41669    }
41670    assert( rc!=SQLITE_DONE );
41671  }
41672  assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
41673
41674  /* Finally,  rollback pages from the sub-journal.  Page that were
41675  ** previously rolled back out of the main journal (and are hence in pDone)
41676  ** will be skipped.  Out-of-range pages are also skipped.
41677  */
41678  if( pSavepoint ){
41679    u32 ii;            /* Loop counter */
41680    i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
41681
41682    if( pagerUseWal(pPager) ){
41683      rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
41684    }
41685    for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
41686      assert( offset==(i64)ii*(4+pPager->pageSize) );
41687      rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
41688    }
41689    assert( rc!=SQLITE_DONE );
41690  }
41691
41692  sqlite3BitvecDestroy(pDone);
41693  if( rc==SQLITE_OK ){
41694    pPager->journalOff = szJ;
41695  }
41696
41697  return rc;
41698}
41699
41700/*
41701** Change the maximum number of in-memory pages that are allowed.
41702*/
41703SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
41704  sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
41705}
41706
41707/*
41708** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap.
41709*/
41710static void pagerFixMaplimit(Pager *pPager){
41711#if SQLITE_MAX_MMAP_SIZE>0
41712  sqlite3_file *fd = pPager->fd;
41713  if( isOpen(fd) ){
41714    sqlite3_int64 sz;
41715    pPager->bUseFetch = (fd->pMethods->iVersion>=3) && pPager->szMmap>0;
41716    sz = pPager->szMmap;
41717    sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz);
41718  }
41719#endif
41720}
41721
41722/*
41723** Change the maximum size of any memory mapping made of the database file.
41724*/
41725SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){
41726  pPager->szMmap = szMmap;
41727  pagerFixMaplimit(pPager);
41728}
41729
41730/*
41731** Free as much memory as possible from the pager.
41732*/
41733SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
41734  sqlite3PcacheShrink(pPager->pPCache);
41735}
41736
41737/*
41738** Adjust the robustness of the database to damage due to OS crashes
41739** or power failures by changing the number of syncs()s when writing
41740** the rollback journal.  There are three levels:
41741**
41742**    OFF       sqlite3OsSync() is never called.  This is the default
41743**              for temporary and transient files.
41744**
41745**    NORMAL    The journal is synced once before writes begin on the
41746**              database.  This is normally adequate protection, but
41747**              it is theoretically possible, though very unlikely,
41748**              that an inopertune power failure could leave the journal
41749**              in a state which would cause damage to the database
41750**              when it is rolled back.
41751**
41752**    FULL      The journal is synced twice before writes begin on the
41753**              database (with some additional information - the nRec field
41754**              of the journal header - being written in between the two
41755**              syncs).  If we assume that writing a
41756**              single disk sector is atomic, then this mode provides
41757**              assurance that the journal will not be corrupted to the
41758**              point of causing damage to the database during rollback.
41759**
41760** The above is for a rollback-journal mode.  For WAL mode, OFF continues
41761** to mean that no syncs ever occur.  NORMAL means that the WAL is synced
41762** prior to the start of checkpoint and that the database file is synced
41763** at the conclusion of the checkpoint if the entire content of the WAL
41764** was written back into the database.  But no sync operations occur for
41765** an ordinary commit in NORMAL mode with WAL.  FULL means that the WAL
41766** file is synced following each commit operation, in addition to the
41767** syncs associated with NORMAL.
41768**
41769** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL.  The
41770** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
41771** using fcntl(F_FULLFSYNC).  SQLITE_SYNC_NORMAL means to do an
41772** ordinary fsync() call.  There is no difference between SQLITE_SYNC_FULL
41773** and SQLITE_SYNC_NORMAL on platforms other than MacOSX.  But the
41774** synchronous=FULL versus synchronous=NORMAL setting determines when
41775** the xSync primitive is called and is relevant to all platforms.
41776**
41777** Numeric values associated with these states are OFF==1, NORMAL=2,
41778** and FULL=3.
41779*/
41780#ifndef SQLITE_OMIT_PAGER_PRAGMAS
41781SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(
41782  Pager *pPager,        /* The pager to set safety level for */
41783  int level,            /* PRAGMA synchronous.  1=OFF, 2=NORMAL, 3=FULL */
41784  int bFullFsync,       /* PRAGMA fullfsync */
41785  int bCkptFullFsync    /* PRAGMA checkpoint_fullfsync */
41786){
41787  assert( level>=1 && level<=3 );
41788  pPager->noSync =  (level==1 || pPager->tempFile) ?1:0;
41789  pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
41790  if( pPager->noSync ){
41791    pPager->syncFlags = 0;
41792    pPager->ckptSyncFlags = 0;
41793  }else if( bFullFsync ){
41794    pPager->syncFlags = SQLITE_SYNC_FULL;
41795    pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
41796  }else if( bCkptFullFsync ){
41797    pPager->syncFlags = SQLITE_SYNC_NORMAL;
41798    pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
41799  }else{
41800    pPager->syncFlags = SQLITE_SYNC_NORMAL;
41801    pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
41802  }
41803  pPager->walSyncFlags = pPager->syncFlags;
41804  if( pPager->fullSync ){
41805    pPager->walSyncFlags |= WAL_SYNC_TRANSACTIONS;
41806  }
41807}
41808#endif
41809
41810/*
41811** The following global variable is incremented whenever the library
41812** attempts to open a temporary file.  This information is used for
41813** testing and analysis only.
41814*/
41815#ifdef SQLITE_TEST
41816SQLITE_API int sqlite3_opentemp_count = 0;
41817#endif
41818
41819/*
41820** Open a temporary file.
41821**
41822** Write the file descriptor into *pFile. Return SQLITE_OK on success
41823** or some other error code if we fail. The OS will automatically
41824** delete the temporary file when it is closed.
41825**
41826** The flags passed to the VFS layer xOpen() call are those specified
41827** by parameter vfsFlags ORed with the following:
41828**
41829**     SQLITE_OPEN_READWRITE
41830**     SQLITE_OPEN_CREATE
41831**     SQLITE_OPEN_EXCLUSIVE
41832**     SQLITE_OPEN_DELETEONCLOSE
41833*/
41834static int pagerOpentemp(
41835  Pager *pPager,        /* The pager object */
41836  sqlite3_file *pFile,  /* Write the file descriptor here */
41837  int vfsFlags          /* Flags passed through to the VFS */
41838){
41839  int rc;               /* Return code */
41840
41841#ifdef SQLITE_TEST
41842  sqlite3_opentemp_count++;  /* Used for testing and analysis only */
41843#endif
41844
41845  vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
41846            SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
41847  rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
41848  assert( rc!=SQLITE_OK || isOpen(pFile) );
41849  return rc;
41850}
41851
41852/*
41853** Set the busy handler function.
41854**
41855** The pager invokes the busy-handler if sqlite3OsLock() returns
41856** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
41857** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
41858** lock. It does *not* invoke the busy handler when upgrading from
41859** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
41860** (which occurs during hot-journal rollback). Summary:
41861**
41862**   Transition                        | Invokes xBusyHandler
41863**   --------------------------------------------------------
41864**   NO_LOCK       -> SHARED_LOCK      | Yes
41865**   SHARED_LOCK   -> RESERVED_LOCK    | No
41866**   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
41867**   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
41868**
41869** If the busy-handler callback returns non-zero, the lock is
41870** retried. If it returns zero, then the SQLITE_BUSY error is
41871** returned to the caller of the pager API function.
41872*/
41873SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
41874  Pager *pPager,                       /* Pager object */
41875  int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
41876  void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
41877){
41878  pPager->xBusyHandler = xBusyHandler;
41879  pPager->pBusyHandlerArg = pBusyHandlerArg;
41880
41881  if( isOpen(pPager->fd) ){
41882    void **ap = (void **)&pPager->xBusyHandler;
41883    assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
41884    assert( ap[1]==pBusyHandlerArg );
41885    sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
41886  }
41887}
41888
41889/*
41890** Change the page size used by the Pager object. The new page size
41891** is passed in *pPageSize.
41892**
41893** If the pager is in the error state when this function is called, it
41894** is a no-op. The value returned is the error state error code (i.e.
41895** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
41896**
41897** Otherwise, if all of the following are true:
41898**
41899**   * the new page size (value of *pPageSize) is valid (a power
41900**     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
41901**
41902**   * there are no outstanding page references, and
41903**
41904**   * the database is either not an in-memory database or it is
41905**     an in-memory database that currently consists of zero pages.
41906**
41907** then the pager object page size is set to *pPageSize.
41908**
41909** If the page size is changed, then this function uses sqlite3PagerMalloc()
41910** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
41911** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
41912** In all other cases, SQLITE_OK is returned.
41913**
41914** If the page size is not changed, either because one of the enumerated
41915** conditions above is not true, the pager was in error state when this
41916** function was called, or because the memory allocation attempt failed,
41917** then *pPageSize is set to the old, retained page size before returning.
41918*/
41919SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
41920  int rc = SQLITE_OK;
41921
41922  /* It is not possible to do a full assert_pager_state() here, as this
41923  ** function may be called from within PagerOpen(), before the state
41924  ** of the Pager object is internally consistent.
41925  **
41926  ** At one point this function returned an error if the pager was in
41927  ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
41928  ** there is at least one outstanding page reference, this function
41929  ** is a no-op for that case anyhow.
41930  */
41931
41932  u32 pageSize = *pPageSize;
41933  assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
41934  if( (pPager->memDb==0 || pPager->dbSize==0)
41935   && sqlite3PcacheRefCount(pPager->pPCache)==0
41936   && pageSize && pageSize!=(u32)pPager->pageSize
41937  ){
41938    char *pNew = NULL;             /* New temp space */
41939    i64 nByte = 0;
41940
41941    if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
41942      rc = sqlite3OsFileSize(pPager->fd, &nByte);
41943    }
41944    if( rc==SQLITE_OK ){
41945      pNew = (char *)sqlite3PageMalloc(pageSize);
41946      if( !pNew ) rc = SQLITE_NOMEM;
41947    }
41948
41949    if( rc==SQLITE_OK ){
41950      pager_reset(pPager);
41951      pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
41952      pPager->pageSize = pageSize;
41953      sqlite3PageFree(pPager->pTmpSpace);
41954      pPager->pTmpSpace = pNew;
41955      sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
41956    }
41957  }
41958
41959  *pPageSize = pPager->pageSize;
41960  if( rc==SQLITE_OK ){
41961    if( nReserve<0 ) nReserve = pPager->nReserve;
41962    assert( nReserve>=0 && nReserve<1000 );
41963    pPager->nReserve = (i16)nReserve;
41964    pagerReportSize(pPager);
41965    pagerFixMaplimit(pPager);
41966  }
41967  return rc;
41968}
41969
41970/*
41971** Return a pointer to the "temporary page" buffer held internally
41972** by the pager.  This is a buffer that is big enough to hold the
41973** entire content of a database page.  This buffer is used internally
41974** during rollback and will be overwritten whenever a rollback
41975** occurs.  But other modules are free to use it too, as long as
41976** no rollbacks are happening.
41977*/
41978SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
41979  return pPager->pTmpSpace;
41980}
41981
41982/*
41983** Attempt to set the maximum database page count if mxPage is positive.
41984** Make no changes if mxPage is zero or negative.  And never reduce the
41985** maximum page count below the current size of the database.
41986**
41987** Regardless of mxPage, return the current maximum page count.
41988*/
41989SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
41990  if( mxPage>0 ){
41991    pPager->mxPgno = mxPage;
41992  }
41993  assert( pPager->eState!=PAGER_OPEN );      /* Called only by OP_MaxPgcnt */
41994  assert( pPager->mxPgno>=pPager->dbSize );  /* OP_MaxPgcnt enforces this */
41995  return pPager->mxPgno;
41996}
41997
41998/*
41999** The following set of routines are used to disable the simulated
42000** I/O error mechanism.  These routines are used to avoid simulated
42001** errors in places where we do not care about errors.
42002**
42003** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
42004** and generate no code.
42005*/
42006#ifdef SQLITE_TEST
42007SQLITE_API extern int sqlite3_io_error_pending;
42008SQLITE_API extern int sqlite3_io_error_hit;
42009static int saved_cnt;
42010void disable_simulated_io_errors(void){
42011  saved_cnt = sqlite3_io_error_pending;
42012  sqlite3_io_error_pending = -1;
42013}
42014void enable_simulated_io_errors(void){
42015  sqlite3_io_error_pending = saved_cnt;
42016}
42017#else
42018# define disable_simulated_io_errors()
42019# define enable_simulated_io_errors()
42020#endif
42021
42022/*
42023** Read the first N bytes from the beginning of the file into memory
42024** that pDest points to.
42025**
42026** If the pager was opened on a transient file (zFilename==""), or
42027** opened on a file less than N bytes in size, the output buffer is
42028** zeroed and SQLITE_OK returned. The rationale for this is that this
42029** function is used to read database headers, and a new transient or
42030** zero sized database has a header than consists entirely of zeroes.
42031**
42032** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
42033** the error code is returned to the caller and the contents of the
42034** output buffer undefined.
42035*/
42036SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
42037  int rc = SQLITE_OK;
42038  memset(pDest, 0, N);
42039  assert( isOpen(pPager->fd) || pPager->tempFile );
42040
42041  /* This routine is only called by btree immediately after creating
42042  ** the Pager object.  There has not been an opportunity to transition
42043  ** to WAL mode yet.
42044  */
42045  assert( !pagerUseWal(pPager) );
42046
42047  if( isOpen(pPager->fd) ){
42048    IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
42049    rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
42050    if( rc==SQLITE_IOERR_SHORT_READ ){
42051      rc = SQLITE_OK;
42052    }
42053  }
42054  return rc;
42055}
42056
42057/*
42058** This function may only be called when a read-transaction is open on
42059** the pager. It returns the total number of pages in the database.
42060**
42061** However, if the file is between 1 and <page-size> bytes in size, then
42062** this is considered a 1 page file.
42063*/
42064SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
42065  assert( pPager->eState>=PAGER_READER );
42066  assert( pPager->eState!=PAGER_WRITER_FINISHED );
42067  *pnPage = (int)pPager->dbSize;
42068}
42069
42070
42071/*
42072** Try to obtain a lock of type locktype on the database file. If
42073** a similar or greater lock is already held, this function is a no-op
42074** (returning SQLITE_OK immediately).
42075**
42076** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
42077** the busy callback if the lock is currently not available. Repeat
42078** until the busy callback returns false or until the attempt to
42079** obtain the lock succeeds.
42080**
42081** Return SQLITE_OK on success and an error code if we cannot obtain
42082** the lock. If the lock is obtained successfully, set the Pager.state
42083** variable to locktype before returning.
42084*/
42085static int pager_wait_on_lock(Pager *pPager, int locktype){
42086  int rc;                              /* Return code */
42087
42088  /* Check that this is either a no-op (because the requested lock is
42089  ** already held, or one of the transistions that the busy-handler
42090  ** may be invoked during, according to the comment above
42091  ** sqlite3PagerSetBusyhandler().
42092  */
42093  assert( (pPager->eLock>=locktype)
42094       || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
42095       || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
42096  );
42097
42098  do {
42099    rc = pagerLockDb(pPager, locktype);
42100  }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
42101  return rc;
42102}
42103
42104/*
42105** Function assertTruncateConstraint(pPager) checks that one of the
42106** following is true for all dirty pages currently in the page-cache:
42107**
42108**   a) The page number is less than or equal to the size of the
42109**      current database image, in pages, OR
42110**
42111**   b) if the page content were written at this time, it would not
42112**      be necessary to write the current content out to the sub-journal
42113**      (as determined by function subjRequiresPage()).
42114**
42115** If the condition asserted by this function were not true, and the
42116** dirty page were to be discarded from the cache via the pagerStress()
42117** routine, pagerStress() would not write the current page content to
42118** the database file. If a savepoint transaction were rolled back after
42119** this happened, the correct behavior would be to restore the current
42120** content of the page. However, since this content is not present in either
42121** the database file or the portion of the rollback journal and
42122** sub-journal rolled back the content could not be restored and the
42123** database image would become corrupt. It is therefore fortunate that
42124** this circumstance cannot arise.
42125*/
42126#if defined(SQLITE_DEBUG)
42127static void assertTruncateConstraintCb(PgHdr *pPg){
42128  assert( pPg->flags&PGHDR_DIRTY );
42129  assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
42130}
42131static void assertTruncateConstraint(Pager *pPager){
42132  sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
42133}
42134#else
42135# define assertTruncateConstraint(pPager)
42136#endif
42137
42138/*
42139** Truncate the in-memory database file image to nPage pages. This
42140** function does not actually modify the database file on disk. It
42141** just sets the internal state of the pager object so that the
42142** truncation will be done when the current transaction is committed.
42143**
42144** This function is only called right before committing a transaction.
42145** Once this function has been called, the transaction must either be
42146** rolled back or committed. It is not safe to call this function and
42147** then continue writing to the database.
42148*/
42149SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
42150  assert( pPager->dbSize>=nPage );
42151  assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
42152  pPager->dbSize = nPage;
42153
42154  /* At one point the code here called assertTruncateConstraint() to
42155  ** ensure that all pages being truncated away by this operation are,
42156  ** if one or more savepoints are open, present in the savepoint
42157  ** journal so that they can be restored if the savepoint is rolled
42158  ** back. This is no longer necessary as this function is now only
42159  ** called right before committing a transaction. So although the
42160  ** Pager object may still have open savepoints (Pager.nSavepoint!=0),
42161  ** they cannot be rolled back. So the assertTruncateConstraint() call
42162  ** is no longer correct. */
42163}
42164
42165
42166/*
42167** This function is called before attempting a hot-journal rollback. It
42168** syncs the journal file to disk, then sets pPager->journalHdr to the
42169** size of the journal file so that the pager_playback() routine knows
42170** that the entire journal file has been synced.
42171**
42172** Syncing a hot-journal to disk before attempting to roll it back ensures
42173** that if a power-failure occurs during the rollback, the process that
42174** attempts rollback following system recovery sees the same journal
42175** content as this process.
42176**
42177** If everything goes as planned, SQLITE_OK is returned. Otherwise,
42178** an SQLite error code.
42179*/
42180static int pagerSyncHotJournal(Pager *pPager){
42181  int rc = SQLITE_OK;
42182  if( !pPager->noSync ){
42183    rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
42184  }
42185  if( rc==SQLITE_OK ){
42186    rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
42187  }
42188  return rc;
42189}
42190
42191/*
42192** Obtain a reference to a memory mapped page object for page number pgno.
42193** The new object will use the pointer pData, obtained from xFetch().
42194** If successful, set *ppPage to point to the new page reference
42195** and return SQLITE_OK. Otherwise, return an SQLite error code and set
42196** *ppPage to zero.
42197**
42198** Page references obtained by calling this function should be released
42199** by calling pagerReleaseMapPage().
42200*/
42201static int pagerAcquireMapPage(
42202  Pager *pPager,                  /* Pager object */
42203  Pgno pgno,                      /* Page number */
42204  void *pData,                    /* xFetch()'d data for this page */
42205  PgHdr **ppPage                  /* OUT: Acquired page object */
42206){
42207  PgHdr *p;                       /* Memory mapped page to return */
42208
42209  if( pPager->pMmapFreelist ){
42210    *ppPage = p = pPager->pMmapFreelist;
42211    pPager->pMmapFreelist = p->pDirty;
42212    p->pDirty = 0;
42213    memset(p->pExtra, 0, pPager->nExtra);
42214  }else{
42215    *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
42216    if( p==0 ){
42217      sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
42218      return SQLITE_NOMEM;
42219    }
42220    p->pExtra = (void *)&p[1];
42221    p->flags = PGHDR_MMAP;
42222    p->nRef = 1;
42223    p->pPager = pPager;
42224  }
42225
42226  assert( p->pExtra==(void *)&p[1] );
42227  assert( p->pPage==0 );
42228  assert( p->flags==PGHDR_MMAP );
42229  assert( p->pPager==pPager );
42230  assert( p->nRef==1 );
42231
42232  p->pgno = pgno;
42233  p->pData = pData;
42234  pPager->nMmapOut++;
42235
42236  return SQLITE_OK;
42237}
42238
42239/*
42240** Release a reference to page pPg. pPg must have been returned by an
42241** earlier call to pagerAcquireMapPage().
42242*/
42243static void pagerReleaseMapPage(PgHdr *pPg){
42244  Pager *pPager = pPg->pPager;
42245  pPager->nMmapOut--;
42246  pPg->pDirty = pPager->pMmapFreelist;
42247  pPager->pMmapFreelist = pPg;
42248
42249  assert( pPager->fd->pMethods->iVersion>=3 );
42250  sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);
42251}
42252
42253/*
42254** Free all PgHdr objects stored in the Pager.pMmapFreelist list.
42255*/
42256static void pagerFreeMapHdrs(Pager *pPager){
42257  PgHdr *p;
42258  PgHdr *pNext;
42259  for(p=pPager->pMmapFreelist; p; p=pNext){
42260    pNext = p->pDirty;
42261    sqlite3_free(p);
42262  }
42263}
42264
42265
42266/*
42267** Shutdown the page cache.  Free all memory and close all files.
42268**
42269** If a transaction was in progress when this routine is called, that
42270** transaction is rolled back.  All outstanding pages are invalidated
42271** and their memory is freed.  Any attempt to use a page associated
42272** with this page cache after this function returns will likely
42273** result in a coredump.
42274**
42275** This function always succeeds. If a transaction is active an attempt
42276** is made to roll it back. If an error occurs during the rollback
42277** a hot journal may be left in the filesystem but no error is returned
42278** to the caller.
42279*/
42280SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
42281  u8 *pTmp = (u8 *)pPager->pTmpSpace;
42282
42283  assert( assert_pager_state(pPager) );
42284  disable_simulated_io_errors();
42285  sqlite3BeginBenignMalloc();
42286  pagerFreeMapHdrs(pPager);
42287  /* pPager->errCode = 0; */
42288  pPager->exclusiveMode = 0;
42289#ifndef SQLITE_OMIT_WAL
42290  sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
42291  pPager->pWal = 0;
42292#endif
42293  pager_reset(pPager);
42294  if( MEMDB ){
42295    pager_unlock(pPager);
42296  }else{
42297    /* If it is open, sync the journal file before calling UnlockAndRollback.
42298    ** If this is not done, then an unsynced portion of the open journal
42299    ** file may be played back into the database. If a power failure occurs
42300    ** while this is happening, the database could become corrupt.
42301    **
42302    ** If an error occurs while trying to sync the journal, shift the pager
42303    ** into the ERROR state. This causes UnlockAndRollback to unlock the
42304    ** database and close the journal file without attempting to roll it
42305    ** back or finalize it. The next database user will have to do hot-journal
42306    ** rollback before accessing the database file.
42307    */
42308    if( isOpen(pPager->jfd) ){
42309      pager_error(pPager, pagerSyncHotJournal(pPager));
42310    }
42311    pagerUnlockAndRollback(pPager);
42312  }
42313  sqlite3EndBenignMalloc();
42314  enable_simulated_io_errors();
42315  PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
42316  IOTRACE(("CLOSE %p\n", pPager))
42317  sqlite3OsClose(pPager->jfd);
42318  sqlite3OsClose(pPager->fd);
42319  sqlite3PageFree(pTmp);
42320  sqlite3PcacheClose(pPager->pPCache);
42321
42322#ifdef SQLITE_HAS_CODEC
42323  if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
42324#endif
42325
42326  assert( !pPager->aSavepoint && !pPager->pInJournal );
42327  assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
42328
42329  sqlite3_free(pPager);
42330  return SQLITE_OK;
42331}
42332
42333#if !defined(NDEBUG) || defined(SQLITE_TEST)
42334/*
42335** Return the page number for page pPg.
42336*/
42337SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
42338  return pPg->pgno;
42339}
42340#endif
42341
42342/*
42343** Increment the reference count for page pPg.
42344*/
42345SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
42346  sqlite3PcacheRef(pPg);
42347}
42348
42349/*
42350** Sync the journal. In other words, make sure all the pages that have
42351** been written to the journal have actually reached the surface of the
42352** disk and can be restored in the event of a hot-journal rollback.
42353**
42354** If the Pager.noSync flag is set, then this function is a no-op.
42355** Otherwise, the actions required depend on the journal-mode and the
42356** device characteristics of the file-system, as follows:
42357**
42358**   * If the journal file is an in-memory journal file, no action need
42359**     be taken.
42360**
42361**   * Otherwise, if the device does not support the SAFE_APPEND property,
42362**     then the nRec field of the most recently written journal header
42363**     is updated to contain the number of journal records that have
42364**     been written following it. If the pager is operating in full-sync
42365**     mode, then the journal file is synced before this field is updated.
42366**
42367**   * If the device does not support the SEQUENTIAL property, then
42368**     journal file is synced.
42369**
42370** Or, in pseudo-code:
42371**
42372**   if( NOT <in-memory journal> ){
42373**     if( NOT SAFE_APPEND ){
42374**       if( <full-sync mode> ) xSync(<journal file>);
42375**       <update nRec field>
42376**     }
42377**     if( NOT SEQUENTIAL ) xSync(<journal file>);
42378**   }
42379**
42380** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
42381** page currently held in memory before returning SQLITE_OK. If an IO
42382** error is encountered, then the IO error code is returned to the caller.
42383*/
42384static int syncJournal(Pager *pPager, int newHdr){
42385  int rc;                         /* Return code */
42386
42387  assert( pPager->eState==PAGER_WRITER_CACHEMOD
42388       || pPager->eState==PAGER_WRITER_DBMOD
42389  );
42390  assert( assert_pager_state(pPager) );
42391  assert( !pagerUseWal(pPager) );
42392
42393  rc = sqlite3PagerExclusiveLock(pPager);
42394  if( rc!=SQLITE_OK ) return rc;
42395
42396  if( !pPager->noSync ){
42397    assert( !pPager->tempFile );
42398    if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
42399      const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
42400      assert( isOpen(pPager->jfd) );
42401
42402      if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
42403        /* This block deals with an obscure problem. If the last connection
42404        ** that wrote to this database was operating in persistent-journal
42405        ** mode, then the journal file may at this point actually be larger
42406        ** than Pager.journalOff bytes. If the next thing in the journal
42407        ** file happens to be a journal-header (written as part of the
42408        ** previous connection's transaction), and a crash or power-failure
42409        ** occurs after nRec is updated but before this connection writes
42410        ** anything else to the journal file (or commits/rolls back its
42411        ** transaction), then SQLite may become confused when doing the
42412        ** hot-journal rollback following recovery. It may roll back all
42413        ** of this connections data, then proceed to rolling back the old,
42414        ** out-of-date data that follows it. Database corruption.
42415        **
42416        ** To work around this, if the journal file does appear to contain
42417        ** a valid header following Pager.journalOff, then write a 0x00
42418        ** byte to the start of it to prevent it from being recognized.
42419        **
42420        ** Variable iNextHdrOffset is set to the offset at which this
42421        ** problematic header will occur, if it exists. aMagic is used
42422        ** as a temporary buffer to inspect the first couple of bytes of
42423        ** the potential journal header.
42424        */
42425        i64 iNextHdrOffset;
42426        u8 aMagic[8];
42427        u8 zHeader[sizeof(aJournalMagic)+4];
42428
42429        memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
42430        put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
42431
42432        iNextHdrOffset = journalHdrOffset(pPager);
42433        rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
42434        if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
42435          static const u8 zerobyte = 0;
42436          rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
42437        }
42438        if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
42439          return rc;
42440        }
42441
42442        /* Write the nRec value into the journal file header. If in
42443        ** full-synchronous mode, sync the journal first. This ensures that
42444        ** all data has really hit the disk before nRec is updated to mark
42445        ** it as a candidate for rollback.
42446        **
42447        ** This is not required if the persistent media supports the
42448        ** SAFE_APPEND property. Because in this case it is not possible
42449        ** for garbage data to be appended to the file, the nRec field
42450        ** is populated with 0xFFFFFFFF when the journal header is written
42451        ** and never needs to be updated.
42452        */
42453        if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
42454          PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
42455          IOTRACE(("JSYNC %p\n", pPager))
42456          rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
42457          if( rc!=SQLITE_OK ) return rc;
42458        }
42459        IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
42460        rc = sqlite3OsWrite(
42461            pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
42462        );
42463        if( rc!=SQLITE_OK ) return rc;
42464      }
42465      if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
42466        PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
42467        IOTRACE(("JSYNC %p\n", pPager))
42468        rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
42469          (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
42470        );
42471        if( rc!=SQLITE_OK ) return rc;
42472      }
42473
42474      pPager->journalHdr = pPager->journalOff;
42475      if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
42476        pPager->nRec = 0;
42477        rc = writeJournalHdr(pPager);
42478        if( rc!=SQLITE_OK ) return rc;
42479      }
42480    }else{
42481      pPager->journalHdr = pPager->journalOff;
42482    }
42483  }
42484
42485  /* Unless the pager is in noSync mode, the journal file was just
42486  ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
42487  ** all pages.
42488  */
42489  sqlite3PcacheClearSyncFlags(pPager->pPCache);
42490  pPager->eState = PAGER_WRITER_DBMOD;
42491  assert( assert_pager_state(pPager) );
42492  return SQLITE_OK;
42493}
42494
42495/*
42496** The argument is the first in a linked list of dirty pages connected
42497** by the PgHdr.pDirty pointer. This function writes each one of the
42498** in-memory pages in the list to the database file. The argument may
42499** be NULL, representing an empty list. In this case this function is
42500** a no-op.
42501**
42502** The pager must hold at least a RESERVED lock when this function
42503** is called. Before writing anything to the database file, this lock
42504** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
42505** SQLITE_BUSY is returned and no data is written to the database file.
42506**
42507** If the pager is a temp-file pager and the actual file-system file
42508** is not yet open, it is created and opened before any data is
42509** written out.
42510**
42511** Once the lock has been upgraded and, if necessary, the file opened,
42512** the pages are written out to the database file in list order. Writing
42513** a page is skipped if it meets either of the following criteria:
42514**
42515**   * The page number is greater than Pager.dbSize, or
42516**   * The PGHDR_DONT_WRITE flag is set on the page.
42517**
42518** If writing out a page causes the database file to grow, Pager.dbFileSize
42519** is updated accordingly. If page 1 is written out, then the value cached
42520** in Pager.dbFileVers[] is updated to match the new value stored in
42521** the database file.
42522**
42523** If everything is successful, SQLITE_OK is returned. If an IO error
42524** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
42525** be obtained, SQLITE_BUSY is returned.
42526*/
42527static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
42528  int rc = SQLITE_OK;                  /* Return code */
42529
42530  /* This function is only called for rollback pagers in WRITER_DBMOD state. */
42531  assert( !pagerUseWal(pPager) );
42532  assert( pPager->eState==PAGER_WRITER_DBMOD );
42533  assert( pPager->eLock==EXCLUSIVE_LOCK );
42534
42535  /* If the file is a temp-file has not yet been opened, open it now. It
42536  ** is not possible for rc to be other than SQLITE_OK if this branch
42537  ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
42538  */
42539  if( !isOpen(pPager->fd) ){
42540    assert( pPager->tempFile && rc==SQLITE_OK );
42541    rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
42542  }
42543
42544  /* Before the first write, give the VFS a hint of what the final
42545  ** file size will be.
42546  */
42547  assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
42548  if( rc==SQLITE_OK
42549   && (pList->pDirty ? pPager->dbSize : pList->pgno+1)>pPager->dbHintSize
42550  ){
42551    sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
42552    sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
42553    pPager->dbHintSize = pPager->dbSize;
42554  }
42555
42556  while( rc==SQLITE_OK && pList ){
42557    Pgno pgno = pList->pgno;
42558
42559    /* If there are dirty pages in the page cache with page numbers greater
42560    ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
42561    ** make the file smaller (presumably by auto-vacuum code). Do not write
42562    ** any such pages to the file.
42563    **
42564    ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
42565    ** set (set by sqlite3PagerDontWrite()).
42566    */
42567    if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
42568      i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
42569      char *pData;                                   /* Data to write */
42570
42571      assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
42572      if( pList->pgno==1 ) pager_write_changecounter(pList);
42573
42574      /* Encode the database */
42575      CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
42576
42577      /* Write out the page data. */
42578      rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
42579
42580      /* If page 1 was just written, update Pager.dbFileVers to match
42581      ** the value now stored in the database file. If writing this
42582      ** page caused the database file to grow, update dbFileSize.
42583      */
42584      if( pgno==1 ){
42585        memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
42586      }
42587      if( pgno>pPager->dbFileSize ){
42588        pPager->dbFileSize = pgno;
42589      }
42590      pPager->aStat[PAGER_STAT_WRITE]++;
42591
42592      /* Update any backup objects copying the contents of this pager. */
42593      sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
42594
42595      PAGERTRACE(("STORE %d page %d hash(%08x)\n",
42596                   PAGERID(pPager), pgno, pager_pagehash(pList)));
42597      IOTRACE(("PGOUT %p %d\n", pPager, pgno));
42598      PAGER_INCR(sqlite3_pager_writedb_count);
42599    }else{
42600      PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
42601    }
42602    pager_set_pagehash(pList);
42603    pList = pList->pDirty;
42604  }
42605
42606  return rc;
42607}
42608
42609/*
42610** Ensure that the sub-journal file is open. If it is already open, this
42611** function is a no-op.
42612**
42613** SQLITE_OK is returned if everything goes according to plan. An
42614** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
42615** fails.
42616*/
42617static int openSubJournal(Pager *pPager){
42618  int rc = SQLITE_OK;
42619  if( !isOpen(pPager->sjfd) ){
42620    if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
42621      sqlite3MemJournalOpen(pPager->sjfd);
42622    }else{
42623      rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
42624    }
42625  }
42626  return rc;
42627}
42628
42629/*
42630** Append a record of the current state of page pPg to the sub-journal.
42631** It is the callers responsibility to use subjRequiresPage() to check
42632** that it is really required before calling this function.
42633**
42634** If successful, set the bit corresponding to pPg->pgno in the bitvecs
42635** for all open savepoints before returning.
42636**
42637** This function returns SQLITE_OK if everything is successful, an IO
42638** error code if the attempt to write to the sub-journal fails, or
42639** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
42640** bitvec.
42641*/
42642static int subjournalPage(PgHdr *pPg){
42643  int rc = SQLITE_OK;
42644  Pager *pPager = pPg->pPager;
42645  if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
42646
42647    /* Open the sub-journal, if it has not already been opened */
42648    assert( pPager->useJournal );
42649    assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
42650    assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
42651    assert( pagerUseWal(pPager)
42652         || pageInJournal(pPg)
42653         || pPg->pgno>pPager->dbOrigSize
42654    );
42655    rc = openSubJournal(pPager);
42656
42657    /* If the sub-journal was opened successfully (or was already open),
42658    ** write the journal record into the file.  */
42659    if( rc==SQLITE_OK ){
42660      void *pData = pPg->pData;
42661      i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
42662      char *pData2;
42663
42664      CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
42665      PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
42666      rc = write32bits(pPager->sjfd, offset, pPg->pgno);
42667      if( rc==SQLITE_OK ){
42668        rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
42669      }
42670    }
42671  }
42672  if( rc==SQLITE_OK ){
42673    pPager->nSubRec++;
42674    assert( pPager->nSavepoint>0 );
42675    rc = addToSavepointBitvecs(pPager, pPg->pgno);
42676  }
42677  return rc;
42678}
42679
42680/*
42681** This function is called by the pcache layer when it has reached some
42682** soft memory limit. The first argument is a pointer to a Pager object
42683** (cast as a void*). The pager is always 'purgeable' (not an in-memory
42684** database). The second argument is a reference to a page that is
42685** currently dirty but has no outstanding references. The page
42686** is always associated with the Pager object passed as the first
42687** argument.
42688**
42689** The job of this function is to make pPg clean by writing its contents
42690** out to the database file, if possible. This may involve syncing the
42691** journal file.
42692**
42693** If successful, sqlite3PcacheMakeClean() is called on the page and
42694** SQLITE_OK returned. If an IO error occurs while trying to make the
42695** page clean, the IO error code is returned. If the page cannot be
42696** made clean for some other reason, but no error occurs, then SQLITE_OK
42697** is returned by sqlite3PcacheMakeClean() is not called.
42698*/
42699static int pagerStress(void *p, PgHdr *pPg){
42700  Pager *pPager = (Pager *)p;
42701  int rc = SQLITE_OK;
42702
42703  assert( pPg->pPager==pPager );
42704  assert( pPg->flags&PGHDR_DIRTY );
42705
42706  /* The doNotSyncSpill flag is set during times when doing a sync of
42707  ** journal (and adding a new header) is not allowed.  This occurs
42708  ** during calls to sqlite3PagerWrite() while trying to journal multiple
42709  ** pages belonging to the same sector.
42710  **
42711  ** The doNotSpill flag inhibits all cache spilling regardless of whether
42712  ** or not a sync is required.  This is set during a rollback.
42713  **
42714  ** Spilling is also prohibited when in an error state since that could
42715  ** lead to database corruption.   In the current implementaton it
42716  ** is impossible for sqlite3PcacheFetch() to be called with createFlag==1
42717  ** while in the error state, hence it is impossible for this routine to
42718  ** be called in the error state.  Nevertheless, we include a NEVER()
42719  ** test for the error state as a safeguard against future changes.
42720  */
42721  if( NEVER(pPager->errCode) ) return SQLITE_OK;
42722  if( pPager->doNotSpill ) return SQLITE_OK;
42723  if( pPager->doNotSyncSpill && (pPg->flags & PGHDR_NEED_SYNC)!=0 ){
42724    return SQLITE_OK;
42725  }
42726
42727  pPg->pDirty = 0;
42728  if( pagerUseWal(pPager) ){
42729    /* Write a single frame for this page to the log. */
42730    if( subjRequiresPage(pPg) ){
42731      rc = subjournalPage(pPg);
42732    }
42733    if( rc==SQLITE_OK ){
42734      rc = pagerWalFrames(pPager, pPg, 0, 0);
42735    }
42736  }else{
42737
42738    /* Sync the journal file if required. */
42739    if( pPg->flags&PGHDR_NEED_SYNC
42740     || pPager->eState==PAGER_WRITER_CACHEMOD
42741    ){
42742      rc = syncJournal(pPager, 1);
42743    }
42744
42745    /* If the page number of this page is larger than the current size of
42746    ** the database image, it may need to be written to the sub-journal.
42747    ** This is because the call to pager_write_pagelist() below will not
42748    ** actually write data to the file in this case.
42749    **
42750    ** Consider the following sequence of events:
42751    **
42752    **   BEGIN;
42753    **     <journal page X>
42754    **     <modify page X>
42755    **     SAVEPOINT sp;
42756    **       <shrink database file to Y pages>
42757    **       pagerStress(page X)
42758    **     ROLLBACK TO sp;
42759    **
42760    ** If (X>Y), then when pagerStress is called page X will not be written
42761    ** out to the database file, but will be dropped from the cache. Then,
42762    ** following the "ROLLBACK TO sp" statement, reading page X will read
42763    ** data from the database file. This will be the copy of page X as it
42764    ** was when the transaction started, not as it was when "SAVEPOINT sp"
42765    ** was executed.
42766    **
42767    ** The solution is to write the current data for page X into the
42768    ** sub-journal file now (if it is not already there), so that it will
42769    ** be restored to its current value when the "ROLLBACK TO sp" is
42770    ** executed.
42771    */
42772    if( NEVER(
42773        rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
42774    ) ){
42775      rc = subjournalPage(pPg);
42776    }
42777
42778    /* Write the contents of the page out to the database file. */
42779    if( rc==SQLITE_OK ){
42780      assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
42781      rc = pager_write_pagelist(pPager, pPg);
42782    }
42783  }
42784
42785  /* Mark the page as clean. */
42786  if( rc==SQLITE_OK ){
42787    PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
42788    sqlite3PcacheMakeClean(pPg);
42789  }
42790
42791  return pager_error(pPager, rc);
42792}
42793
42794
42795/*
42796** Allocate and initialize a new Pager object and put a pointer to it
42797** in *ppPager. The pager should eventually be freed by passing it
42798** to sqlite3PagerClose().
42799**
42800** The zFilename argument is the path to the database file to open.
42801** If zFilename is NULL then a randomly-named temporary file is created
42802** and used as the file to be cached. Temporary files are be deleted
42803** automatically when they are closed. If zFilename is ":memory:" then
42804** all information is held in cache. It is never written to disk.
42805** This can be used to implement an in-memory database.
42806**
42807** The nExtra parameter specifies the number of bytes of space allocated
42808** along with each page reference. This space is available to the user
42809** via the sqlite3PagerGetExtra() API.
42810**
42811** The flags argument is used to specify properties that affect the
42812** operation of the pager. It should be passed some bitwise combination
42813** of the PAGER_* flags.
42814**
42815** The vfsFlags parameter is a bitmask to pass to the flags parameter
42816** of the xOpen() method of the supplied VFS when opening files.
42817**
42818** If the pager object is allocated and the specified file opened
42819** successfully, SQLITE_OK is returned and *ppPager set to point to
42820** the new pager object. If an error occurs, *ppPager is set to NULL
42821** and error code returned. This function may return SQLITE_NOMEM
42822** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
42823** various SQLITE_IO_XXX errors.
42824*/
42825SQLITE_PRIVATE int sqlite3PagerOpen(
42826  sqlite3_vfs *pVfs,       /* The virtual file system to use */
42827  Pager **ppPager,         /* OUT: Return the Pager structure here */
42828  const char *zFilename,   /* Name of the database file to open */
42829  int nExtra,              /* Extra bytes append to each in-memory page */
42830  int flags,               /* flags controlling this file */
42831  int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */
42832  void (*xReinit)(DbPage*) /* Function to reinitialize pages */
42833){
42834  u8 *pPtr;
42835  Pager *pPager = 0;       /* Pager object to allocate and return */
42836  int rc = SQLITE_OK;      /* Return code */
42837  int tempFile = 0;        /* True for temp files (incl. in-memory files) */
42838  int memDb = 0;           /* True if this is an in-memory file */
42839  int readOnly = 0;        /* True if this is a read-only file */
42840  int journalFileSize;     /* Bytes to allocate for each journal fd */
42841  char *zPathname = 0;     /* Full path to database file */
42842  int nPathname = 0;       /* Number of bytes in zPathname */
42843  int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
42844  int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
42845  u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
42846  const char *zUri = 0;    /* URI args to copy */
42847  int nUri = 0;            /* Number of bytes of URI args at *zUri */
42848
42849  /* Figure out how much space is required for each journal file-handle
42850  ** (there are two of them, the main journal and the sub-journal). This
42851  ** is the maximum space required for an in-memory journal file handle
42852  ** and a regular journal file-handle. Note that a "regular journal-handle"
42853  ** may be a wrapper capable of caching the first portion of the journal
42854  ** file in memory to implement the atomic-write optimization (see
42855  ** source file journal.c).
42856  */
42857  if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
42858    journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
42859  }else{
42860    journalFileSize = ROUND8(sqlite3MemJournalSize());
42861  }
42862
42863  /* Set the output variable to NULL in case an error occurs. */
42864  *ppPager = 0;
42865
42866#ifndef SQLITE_OMIT_MEMORYDB
42867  if( flags & PAGER_MEMORY ){
42868    memDb = 1;
42869    if( zFilename && zFilename[0] ){
42870      zPathname = sqlite3DbStrDup(0, zFilename);
42871      if( zPathname==0  ) return SQLITE_NOMEM;
42872      nPathname = sqlite3Strlen30(zPathname);
42873      zFilename = 0;
42874    }
42875  }
42876#endif
42877
42878  /* Compute and store the full pathname in an allocated buffer pointed
42879  ** to by zPathname, length nPathname. Or, if this is a temporary file,
42880  ** leave both nPathname and zPathname set to 0.
42881  */
42882  if( zFilename && zFilename[0] ){
42883    const char *z;
42884    nPathname = pVfs->mxPathname+1;
42885    zPathname = sqlite3DbMallocRaw(0, nPathname*2);
42886    if( zPathname==0 ){
42887      return SQLITE_NOMEM;
42888    }
42889    zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
42890    rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
42891    nPathname = sqlite3Strlen30(zPathname);
42892    z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
42893    while( *z ){
42894      z += sqlite3Strlen30(z)+1;
42895      z += sqlite3Strlen30(z)+1;
42896    }
42897    nUri = (int)(&z[1] - zUri);
42898    assert( nUri>=0 );
42899    if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
42900      /* This branch is taken when the journal path required by
42901      ** the database being opened will be more than pVfs->mxPathname
42902      ** bytes in length. This means the database cannot be opened,
42903      ** as it will not be possible to open the journal file or even
42904      ** check for a hot-journal before reading.
42905      */
42906      rc = SQLITE_CANTOPEN_BKPT;
42907    }
42908    if( rc!=SQLITE_OK ){
42909      sqlite3DbFree(0, zPathname);
42910      return rc;
42911    }
42912  }
42913
42914  /* Allocate memory for the Pager structure, PCache object, the
42915  ** three file descriptors, the database file name and the journal
42916  ** file name. The layout in memory is as follows:
42917  **
42918  **     Pager object                    (sizeof(Pager) bytes)
42919  **     PCache object                   (sqlite3PcacheSize() bytes)
42920  **     Database file handle            (pVfs->szOsFile bytes)
42921  **     Sub-journal file handle         (journalFileSize bytes)
42922  **     Main journal file handle        (journalFileSize bytes)
42923  **     Database file name              (nPathname+1 bytes)
42924  **     Journal file name               (nPathname+8+1 bytes)
42925  */
42926  pPtr = (u8 *)sqlite3MallocZero(
42927    ROUND8(sizeof(*pPager)) +      /* Pager structure */
42928    ROUND8(pcacheSize) +           /* PCache object */
42929    ROUND8(pVfs->szOsFile) +       /* The main db file */
42930    journalFileSize * 2 +          /* The two journal files */
42931    nPathname + 1 + nUri +         /* zFilename */
42932    nPathname + 8 + 2              /* zJournal */
42933#ifndef SQLITE_OMIT_WAL
42934    + nPathname + 4 + 2            /* zWal */
42935#endif
42936  );
42937  assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
42938  if( !pPtr ){
42939    sqlite3DbFree(0, zPathname);
42940    return SQLITE_NOMEM;
42941  }
42942  pPager =              (Pager*)(pPtr);
42943  pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
42944  pPager->fd =   (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
42945  pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
42946  pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
42947  pPager->zFilename =    (char*)(pPtr += journalFileSize);
42948  assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
42949
42950  /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
42951  if( zPathname ){
42952    assert( nPathname>0 );
42953    pPager->zJournal =   (char*)(pPtr += nPathname + 1 + nUri);
42954    memcpy(pPager->zFilename, zPathname, nPathname);
42955    if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
42956    memcpy(pPager->zJournal, zPathname, nPathname);
42957    memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2);
42958    sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
42959#ifndef SQLITE_OMIT_WAL
42960    pPager->zWal = &pPager->zJournal[nPathname+8+1];
42961    memcpy(pPager->zWal, zPathname, nPathname);
42962    memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
42963    sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
42964#endif
42965    sqlite3DbFree(0, zPathname);
42966  }
42967  pPager->pVfs = pVfs;
42968  pPager->vfsFlags = vfsFlags;
42969
42970  /* Open the pager file.
42971  */
42972  if( zFilename && zFilename[0] ){
42973    int fout = 0;                    /* VFS flags returned by xOpen() */
42974    rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
42975    assert( !memDb );
42976    readOnly = (fout&SQLITE_OPEN_READONLY);
42977
42978    /* If the file was successfully opened for read/write access,
42979    ** choose a default page size in case we have to create the
42980    ** database file. The default page size is the maximum of:
42981    **
42982    **    + SQLITE_DEFAULT_PAGE_SIZE,
42983    **    + The value returned by sqlite3OsSectorSize()
42984    **    + The largest page size that can be written atomically.
42985    */
42986    if( rc==SQLITE_OK && !readOnly ){
42987      setSectorSize(pPager);
42988      assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
42989      if( szPageDflt<pPager->sectorSize ){
42990        if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
42991          szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
42992        }else{
42993          szPageDflt = (u32)pPager->sectorSize;
42994        }
42995      }
42996#ifdef SQLITE_ENABLE_ATOMIC_WRITE
42997      {
42998        int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
42999        int ii;
43000        assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
43001        assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
43002        assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
43003        for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
43004          if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
43005            szPageDflt = ii;
43006          }
43007        }
43008      }
43009#endif
43010    }
43011  }else{
43012    /* If a temporary file is requested, it is not opened immediately.
43013    ** In this case we accept the default page size and delay actually
43014    ** opening the file until the first call to OsWrite().
43015    **
43016    ** This branch is also run for an in-memory database. An in-memory
43017    ** database is the same as a temp-file that is never written out to
43018    ** disk and uses an in-memory rollback journal.
43019    */
43020    tempFile = 1;
43021    pPager->eState = PAGER_READER;
43022    pPager->eLock = EXCLUSIVE_LOCK;
43023    readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
43024  }
43025
43026  /* The following call to PagerSetPagesize() serves to set the value of
43027  ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
43028  */
43029  if( rc==SQLITE_OK ){
43030    assert( pPager->memDb==0 );
43031    rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
43032    testcase( rc!=SQLITE_OK );
43033  }
43034
43035  /* If an error occurred in either of the blocks above, free the
43036  ** Pager structure and close the file.
43037  */
43038  if( rc!=SQLITE_OK ){
43039    assert( !pPager->pTmpSpace );
43040    sqlite3OsClose(pPager->fd);
43041    sqlite3_free(pPager);
43042    return rc;
43043  }
43044
43045  /* Initialize the PCache object. */
43046  assert( nExtra<1000 );
43047  nExtra = ROUND8(nExtra);
43048  sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
43049                    !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
43050
43051  PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
43052  IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
43053
43054  pPager->useJournal = (u8)useJournal;
43055  /* pPager->stmtOpen = 0; */
43056  /* pPager->stmtInUse = 0; */
43057  /* pPager->nRef = 0; */
43058  /* pPager->stmtSize = 0; */
43059  /* pPager->stmtJSize = 0; */
43060  /* pPager->nPage = 0; */
43061  pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
43062  /* pPager->state = PAGER_UNLOCK; */
43063#if 0
43064  assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
43065#endif
43066  /* pPager->errMask = 0; */
43067  pPager->tempFile = (u8)tempFile;
43068  assert( tempFile==PAGER_LOCKINGMODE_NORMAL
43069          || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
43070  assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
43071  pPager->exclusiveMode = (u8)tempFile;
43072  pPager->changeCountDone = pPager->tempFile;
43073  pPager->memDb = (u8)memDb;
43074  pPager->readOnly = (u8)readOnly;
43075  assert( useJournal || pPager->tempFile );
43076  pPager->noSync = pPager->tempFile;
43077  if( pPager->noSync ){
43078    assert( pPager->fullSync==0 );
43079    assert( pPager->syncFlags==0 );
43080    assert( pPager->walSyncFlags==0 );
43081    assert( pPager->ckptSyncFlags==0 );
43082  }else{
43083    pPager->fullSync = 1;
43084    pPager->syncFlags = SQLITE_SYNC_NORMAL;
43085    pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS;
43086    pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
43087  }
43088  /* pPager->pFirst = 0; */
43089  /* pPager->pFirstSynced = 0; */
43090  /* pPager->pLast = 0; */
43091  pPager->nExtra = (u16)nExtra;
43092  pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
43093  assert( isOpen(pPager->fd) || tempFile );
43094  setSectorSize(pPager);
43095  if( !useJournal ){
43096    pPager->journalMode = PAGER_JOURNALMODE_OFF;
43097  }else if( memDb ){
43098    pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
43099  }
43100  /* pPager->xBusyHandler = 0; */
43101  /* pPager->pBusyHandlerArg = 0; */
43102  pPager->xReiniter = xReinit;
43103  /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
43104  /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */
43105
43106  *ppPager = pPager;
43107  return SQLITE_OK;
43108}
43109
43110
43111
43112/*
43113** This function is called after transitioning from PAGER_UNLOCK to
43114** PAGER_SHARED state. It tests if there is a hot journal present in
43115** the file-system for the given pager. A hot journal is one that
43116** needs to be played back. According to this function, a hot-journal
43117** file exists if the following criteria are met:
43118**
43119**   * The journal file exists in the file system, and
43120**   * No process holds a RESERVED or greater lock on the database file, and
43121**   * The database file itself is greater than 0 bytes in size, and
43122**   * The first byte of the journal file exists and is not 0x00.
43123**
43124** If the current size of the database file is 0 but a journal file
43125** exists, that is probably an old journal left over from a prior
43126** database with the same name. In this case the journal file is
43127** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
43128** is returned.
43129**
43130** This routine does not check if there is a master journal filename
43131** at the end of the file. If there is, and that master journal file
43132** does not exist, then the journal file is not really hot. In this
43133** case this routine will return a false-positive. The pager_playback()
43134** routine will discover that the journal file is not really hot and
43135** will not roll it back.
43136**
43137** If a hot-journal file is found to exist, *pExists is set to 1 and
43138** SQLITE_OK returned. If no hot-journal file is present, *pExists is
43139** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
43140** to determine whether or not a hot-journal file exists, the IO error
43141** code is returned and the value of *pExists is undefined.
43142*/
43143static int hasHotJournal(Pager *pPager, int *pExists){
43144  sqlite3_vfs * const pVfs = pPager->pVfs;
43145  int rc = SQLITE_OK;           /* Return code */
43146  int exists = 1;               /* True if a journal file is present */
43147  int jrnlOpen = !!isOpen(pPager->jfd);
43148
43149  assert( pPager->useJournal );
43150  assert( isOpen(pPager->fd) );
43151  assert( pPager->eState==PAGER_OPEN );
43152
43153  assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
43154    SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
43155  ));
43156
43157  *pExists = 0;
43158  if( !jrnlOpen ){
43159    rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
43160  }
43161  if( rc==SQLITE_OK && exists ){
43162    int locked = 0;             /* True if some process holds a RESERVED lock */
43163
43164    /* Race condition here:  Another process might have been holding the
43165    ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
43166    ** call above, but then delete the journal and drop the lock before
43167    ** we get to the following sqlite3OsCheckReservedLock() call.  If that
43168    ** is the case, this routine might think there is a hot journal when
43169    ** in fact there is none.  This results in a false-positive which will
43170    ** be dealt with by the playback routine.  Ticket #3883.
43171    */
43172    rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
43173    if( rc==SQLITE_OK && !locked ){
43174      Pgno nPage;                 /* Number of pages in database file */
43175
43176      /* Check the size of the database file. If it consists of 0 pages,
43177      ** then delete the journal file. See the header comment above for
43178      ** the reasoning here.  Delete the obsolete journal file under
43179      ** a RESERVED lock to avoid race conditions and to avoid violating
43180      ** [H33020].
43181      */
43182      rc = pagerPagecount(pPager, &nPage);
43183      if( rc==SQLITE_OK ){
43184        if( nPage==0 ){
43185          sqlite3BeginBenignMalloc();
43186          if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
43187            sqlite3OsDelete(pVfs, pPager->zJournal, 0);
43188            if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
43189          }
43190          sqlite3EndBenignMalloc();
43191        }else{
43192          /* The journal file exists and no other connection has a reserved
43193          ** or greater lock on the database file. Now check that there is
43194          ** at least one non-zero bytes at the start of the journal file.
43195          ** If there is, then we consider this journal to be hot. If not,
43196          ** it can be ignored.
43197          */
43198          if( !jrnlOpen ){
43199            int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
43200            rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
43201          }
43202          if( rc==SQLITE_OK ){
43203            u8 first = 0;
43204            rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
43205            if( rc==SQLITE_IOERR_SHORT_READ ){
43206              rc = SQLITE_OK;
43207            }
43208            if( !jrnlOpen ){
43209              sqlite3OsClose(pPager->jfd);
43210            }
43211            *pExists = (first!=0);
43212          }else if( rc==SQLITE_CANTOPEN ){
43213            /* If we cannot open the rollback journal file in order to see if
43214            ** its has a zero header, that might be due to an I/O error, or
43215            ** it might be due to the race condition described above and in
43216            ** ticket #3883.  Either way, assume that the journal is hot.
43217            ** This might be a false positive.  But if it is, then the
43218            ** automatic journal playback and recovery mechanism will deal
43219            ** with it under an EXCLUSIVE lock where we do not need to
43220            ** worry so much with race conditions.
43221            */
43222            *pExists = 1;
43223            rc = SQLITE_OK;
43224          }
43225        }
43226      }
43227    }
43228  }
43229
43230  return rc;
43231}
43232
43233/*
43234** This function is called to obtain a shared lock on the database file.
43235** It is illegal to call sqlite3PagerAcquire() until after this function
43236** has been successfully called. If a shared-lock is already held when
43237** this function is called, it is a no-op.
43238**
43239** The following operations are also performed by this function.
43240**
43241**   1) If the pager is currently in PAGER_OPEN state (no lock held
43242**      on the database file), then an attempt is made to obtain a
43243**      SHARED lock on the database file. Immediately after obtaining
43244**      the SHARED lock, the file-system is checked for a hot-journal,
43245**      which is played back if present. Following any hot-journal
43246**      rollback, the contents of the cache are validated by checking
43247**      the 'change-counter' field of the database file header and
43248**      discarded if they are found to be invalid.
43249**
43250**   2) If the pager is running in exclusive-mode, and there are currently
43251**      no outstanding references to any pages, and is in the error state,
43252**      then an attempt is made to clear the error state by discarding
43253**      the contents of the page cache and rolling back any open journal
43254**      file.
43255**
43256** If everything is successful, SQLITE_OK is returned. If an IO error
43257** occurs while locking the database, checking for a hot-journal file or
43258** rolling back a journal file, the IO error code is returned.
43259*/
43260SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
43261  int rc = SQLITE_OK;                /* Return code */
43262
43263  /* This routine is only called from b-tree and only when there are no
43264  ** outstanding pages. This implies that the pager state should either
43265  ** be OPEN or READER. READER is only possible if the pager is or was in
43266  ** exclusive access mode.
43267  */
43268  assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
43269  assert( assert_pager_state(pPager) );
43270  assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
43271  if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
43272
43273  if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
43274    int bHotJournal = 1;          /* True if there exists a hot journal-file */
43275
43276    assert( !MEMDB );
43277
43278    rc = pager_wait_on_lock(pPager, SHARED_LOCK);
43279    if( rc!=SQLITE_OK ){
43280      assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
43281      goto failed;
43282    }
43283
43284    /* If a journal file exists, and there is no RESERVED lock on the
43285    ** database file, then it either needs to be played back or deleted.
43286    */
43287    if( pPager->eLock<=SHARED_LOCK ){
43288      rc = hasHotJournal(pPager, &bHotJournal);
43289    }
43290    if( rc!=SQLITE_OK ){
43291      goto failed;
43292    }
43293    if( bHotJournal ){
43294      if( pPager->readOnly ){
43295        rc = SQLITE_READONLY_ROLLBACK;
43296        goto failed;
43297      }
43298
43299      /* Get an EXCLUSIVE lock on the database file. At this point it is
43300      ** important that a RESERVED lock is not obtained on the way to the
43301      ** EXCLUSIVE lock. If it were, another process might open the
43302      ** database file, detect the RESERVED lock, and conclude that the
43303      ** database is safe to read while this process is still rolling the
43304      ** hot-journal back.
43305      **
43306      ** Because the intermediate RESERVED lock is not requested, any
43307      ** other process attempting to access the database file will get to
43308      ** this point in the code and fail to obtain its own EXCLUSIVE lock
43309      ** on the database file.
43310      **
43311      ** Unless the pager is in locking_mode=exclusive mode, the lock is
43312      ** downgraded to SHARED_LOCK before this function returns.
43313      */
43314      rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
43315      if( rc!=SQLITE_OK ){
43316        goto failed;
43317      }
43318
43319      /* If it is not already open and the file exists on disk, open the
43320      ** journal for read/write access. Write access is required because
43321      ** in exclusive-access mode the file descriptor will be kept open
43322      ** and possibly used for a transaction later on. Also, write-access
43323      ** is usually required to finalize the journal in journal_mode=persist
43324      ** mode (and also for journal_mode=truncate on some systems).
43325      **
43326      ** If the journal does not exist, it usually means that some
43327      ** other connection managed to get in and roll it back before
43328      ** this connection obtained the exclusive lock above. Or, it
43329      ** may mean that the pager was in the error-state when this
43330      ** function was called and the journal file does not exist.
43331      */
43332      if( !isOpen(pPager->jfd) ){
43333        sqlite3_vfs * const pVfs = pPager->pVfs;
43334        int bExists;              /* True if journal file exists */
43335        rc = sqlite3OsAccess(
43336            pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
43337        if( rc==SQLITE_OK && bExists ){
43338          int fout = 0;
43339          int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
43340          assert( !pPager->tempFile );
43341          rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
43342          assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
43343          if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
43344            rc = SQLITE_CANTOPEN_BKPT;
43345            sqlite3OsClose(pPager->jfd);
43346          }
43347        }
43348      }
43349
43350      /* Playback and delete the journal.  Drop the database write
43351      ** lock and reacquire the read lock. Purge the cache before
43352      ** playing back the hot-journal so that we don't end up with
43353      ** an inconsistent cache.  Sync the hot journal before playing
43354      ** it back since the process that crashed and left the hot journal
43355      ** probably did not sync it and we are required to always sync
43356      ** the journal before playing it back.
43357      */
43358      if( isOpen(pPager->jfd) ){
43359        assert( rc==SQLITE_OK );
43360        rc = pagerSyncHotJournal(pPager);
43361        if( rc==SQLITE_OK ){
43362          rc = pager_playback(pPager, 1);
43363          pPager->eState = PAGER_OPEN;
43364        }
43365      }else if( !pPager->exclusiveMode ){
43366        pagerUnlockDb(pPager, SHARED_LOCK);
43367      }
43368
43369      if( rc!=SQLITE_OK ){
43370        /* This branch is taken if an error occurs while trying to open
43371        ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
43372        ** pager_unlock() routine will be called before returning to unlock
43373        ** the file. If the unlock attempt fails, then Pager.eLock must be
43374        ** set to UNKNOWN_LOCK (see the comment above the #define for
43375        ** UNKNOWN_LOCK above for an explanation).
43376        **
43377        ** In order to get pager_unlock() to do this, set Pager.eState to
43378        ** PAGER_ERROR now. This is not actually counted as a transition
43379        ** to ERROR state in the state diagram at the top of this file,
43380        ** since we know that the same call to pager_unlock() will very
43381        ** shortly transition the pager object to the OPEN state. Calling
43382        ** assert_pager_state() would fail now, as it should not be possible
43383        ** to be in ERROR state when there are zero outstanding page
43384        ** references.
43385        */
43386        pager_error(pPager, rc);
43387        goto failed;
43388      }
43389
43390      assert( pPager->eState==PAGER_OPEN );
43391      assert( (pPager->eLock==SHARED_LOCK)
43392           || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
43393      );
43394    }
43395
43396    if( !pPager->tempFile && (
43397        pPager->pBackup
43398     || sqlite3PcachePagecount(pPager->pPCache)>0
43399     || USEFETCH(pPager)
43400    )){
43401      /* The shared-lock has just been acquired on the database file
43402      ** and there are already pages in the cache (from a previous
43403      ** read or write transaction).  Check to see if the database
43404      ** has been modified.  If the database has changed, flush the
43405      ** cache.
43406      **
43407      ** Database changes is detected by looking at 15 bytes beginning
43408      ** at offset 24 into the file.  The first 4 of these 16 bytes are
43409      ** a 32-bit counter that is incremented with each change.  The
43410      ** other bytes change randomly with each file change when
43411      ** a codec is in use.
43412      **
43413      ** There is a vanishingly small chance that a change will not be
43414      ** detected.  The chance of an undetected change is so small that
43415      ** it can be neglected.
43416      */
43417      Pgno nPage = 0;
43418      char dbFileVers[sizeof(pPager->dbFileVers)];
43419
43420      rc = pagerPagecount(pPager, &nPage);
43421      if( rc ) goto failed;
43422
43423      if( nPage>0 ){
43424        IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
43425        rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
43426        if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
43427          goto failed;
43428        }
43429      }else{
43430        memset(dbFileVers, 0, sizeof(dbFileVers));
43431      }
43432
43433      if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
43434        pager_reset(pPager);
43435
43436        /* Unmap the database file. It is possible that external processes
43437        ** may have truncated the database file and then extended it back
43438        ** to its original size while this process was not holding a lock.
43439        ** In this case there may exist a Pager.pMap mapping that appears
43440        ** to be the right size but is not actually valid. Avoid this
43441        ** possibility by unmapping the db here. */
43442        if( USEFETCH(pPager) ){
43443          sqlite3OsUnfetch(pPager->fd, 0, 0);
43444        }
43445      }
43446    }
43447
43448    /* If there is a WAL file in the file-system, open this database in WAL
43449    ** mode. Otherwise, the following function call is a no-op.
43450    */
43451    rc = pagerOpenWalIfPresent(pPager);
43452#ifndef SQLITE_OMIT_WAL
43453    assert( pPager->pWal==0 || rc==SQLITE_OK );
43454#endif
43455  }
43456
43457  if( pagerUseWal(pPager) ){
43458    assert( rc==SQLITE_OK );
43459    rc = pagerBeginReadTransaction(pPager);
43460  }
43461
43462  if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
43463    rc = pagerPagecount(pPager, &pPager->dbSize);
43464  }
43465
43466 failed:
43467  if( rc!=SQLITE_OK ){
43468    assert( !MEMDB );
43469    pager_unlock(pPager);
43470    assert( pPager->eState==PAGER_OPEN );
43471  }else{
43472    pPager->eState = PAGER_READER;
43473  }
43474  return rc;
43475}
43476
43477/*
43478** If the reference count has reached zero, rollback any active
43479** transaction and unlock the pager.
43480**
43481** Except, in locking_mode=EXCLUSIVE when there is nothing to in
43482** the rollback journal, the unlock is not performed and there is
43483** nothing to rollback, so this routine is a no-op.
43484*/
43485static void pagerUnlockIfUnused(Pager *pPager){
43486  if( pPager->nMmapOut==0 && (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
43487    pagerUnlockAndRollback(pPager);
43488  }
43489}
43490
43491/*
43492** Acquire a reference to page number pgno in pager pPager (a page
43493** reference has type DbPage*). If the requested reference is
43494** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
43495**
43496** If the requested page is already in the cache, it is returned.
43497** Otherwise, a new page object is allocated and populated with data
43498** read from the database file. In some cases, the pcache module may
43499** choose not to allocate a new page object and may reuse an existing
43500** object with no outstanding references.
43501**
43502** The extra data appended to a page is always initialized to zeros the
43503** first time a page is loaded into memory. If the page requested is
43504** already in the cache when this function is called, then the extra
43505** data is left as it was when the page object was last used.
43506**
43507** If the database image is smaller than the requested page or if a
43508** non-zero value is passed as the noContent parameter and the
43509** requested page is not already stored in the cache, then no
43510** actual disk read occurs. In this case the memory image of the
43511** page is initialized to all zeros.
43512**
43513** If noContent is true, it means that we do not care about the contents
43514** of the page. This occurs in two seperate scenarios:
43515**
43516**   a) When reading a free-list leaf page from the database, and
43517**
43518**   b) When a savepoint is being rolled back and we need to load
43519**      a new page into the cache to be filled with the data read
43520**      from the savepoint journal.
43521**
43522** If noContent is true, then the data returned is zeroed instead of
43523** being read from the database. Additionally, the bits corresponding
43524** to pgno in Pager.pInJournal (bitvec of pages already written to the
43525** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
43526** savepoints are set. This means if the page is made writable at any
43527** point in the future, using a call to sqlite3PagerWrite(), its contents
43528** will not be journaled. This saves IO.
43529**
43530** The acquisition might fail for several reasons.  In all cases,
43531** an appropriate error code is returned and *ppPage is set to NULL.
43532**
43533** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
43534** to find a page in the in-memory cache first.  If the page is not already
43535** in memory, this routine goes to disk to read it in whereas Lookup()
43536** just returns 0.  This routine acquires a read-lock the first time it
43537** has to go to disk, and could also playback an old journal if necessary.
43538** Since Lookup() never goes to disk, it never has to deal with locks
43539** or journal files.
43540*/
43541SQLITE_PRIVATE int sqlite3PagerAcquire(
43542  Pager *pPager,      /* The pager open on the database file */
43543  Pgno pgno,          /* Page number to fetch */
43544  DbPage **ppPage,    /* Write a pointer to the page here */
43545  int flags           /* PAGER_ACQUIRE_XXX flags */
43546){
43547  int rc = SQLITE_OK;
43548  PgHdr *pPg = 0;
43549  u32 iFrame = 0;                 /* Frame to read from WAL file */
43550  const int noContent = (flags & PAGER_ACQUIRE_NOCONTENT);
43551
43552  /* It is acceptable to use a read-only (mmap) page for any page except
43553  ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
43554  ** flag was specified by the caller. And so long as the db is not a
43555  ** temporary or in-memory database.  */
43556  const int bMmapOk = (pgno!=1 && USEFETCH(pPager)
43557   && (pPager->eState==PAGER_READER || (flags & PAGER_ACQUIRE_READONLY))
43558#ifdef SQLITE_HAS_CODEC
43559   && pPager->xCodec==0
43560#endif
43561  );
43562
43563  assert( pPager->eState>=PAGER_READER );
43564  assert( assert_pager_state(pPager) );
43565  assert( noContent==0 || bMmapOk==0 );
43566
43567  if( pgno==0 ){
43568    return SQLITE_CORRUPT_BKPT;
43569  }
43570
43571  /* If the pager is in the error state, return an error immediately.
43572  ** Otherwise, request the page from the PCache layer. */
43573  if( pPager->errCode!=SQLITE_OK ){
43574    rc = pPager->errCode;
43575  }else{
43576
43577    if( bMmapOk && pagerUseWal(pPager) ){
43578      rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
43579      if( rc!=SQLITE_OK ) goto pager_acquire_err;
43580    }
43581
43582    if( iFrame==0 && bMmapOk ){
43583      void *pData = 0;
43584
43585      rc = sqlite3OsFetch(pPager->fd,
43586          (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
43587      );
43588
43589      if( rc==SQLITE_OK && pData ){
43590        if( pPager->eState>PAGER_READER ){
43591          (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
43592        }
43593        if( pPg==0 ){
43594          rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
43595        }else{
43596          sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);
43597        }
43598        if( pPg ){
43599          assert( rc==SQLITE_OK );
43600          *ppPage = pPg;
43601          return SQLITE_OK;
43602        }
43603      }
43604      if( rc!=SQLITE_OK ){
43605        goto pager_acquire_err;
43606      }
43607    }
43608
43609    rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
43610  }
43611
43612  if( rc!=SQLITE_OK ){
43613    /* Either the call to sqlite3PcacheFetch() returned an error or the
43614    ** pager was already in the error-state when this function was called.
43615    ** Set pPg to 0 and jump to the exception handler.  */
43616    pPg = 0;
43617    goto pager_acquire_err;
43618  }
43619  assert( (*ppPage)->pgno==pgno );
43620  assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
43621
43622  if( (*ppPage)->pPager && !noContent ){
43623    /* In this case the pcache already contains an initialized copy of
43624    ** the page. Return without further ado.  */
43625    assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
43626    pPager->aStat[PAGER_STAT_HIT]++;
43627    return SQLITE_OK;
43628
43629  }else{
43630    /* The pager cache has created a new page. Its content needs to
43631    ** be initialized.  */
43632
43633    pPg = *ppPage;
43634    pPg->pPager = pPager;
43635
43636    /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
43637    ** number greater than this, or the unused locking-page, is requested. */
43638    if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
43639      rc = SQLITE_CORRUPT_BKPT;
43640      goto pager_acquire_err;
43641    }
43642
43643    if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
43644      if( pgno>pPager->mxPgno ){
43645        rc = SQLITE_FULL;
43646        goto pager_acquire_err;
43647      }
43648      if( noContent ){
43649        /* Failure to set the bits in the InJournal bit-vectors is benign.
43650        ** It merely means that we might do some extra work to journal a
43651        ** page that does not need to be journaled.  Nevertheless, be sure
43652        ** to test the case where a malloc error occurs while trying to set
43653        ** a bit in a bit vector.
43654        */
43655        sqlite3BeginBenignMalloc();
43656        if( pgno<=pPager->dbOrigSize ){
43657          TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
43658          testcase( rc==SQLITE_NOMEM );
43659        }
43660        TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
43661        testcase( rc==SQLITE_NOMEM );
43662        sqlite3EndBenignMalloc();
43663      }
43664      memset(pPg->pData, 0, pPager->pageSize);
43665      IOTRACE(("ZERO %p %d\n", pPager, pgno));
43666    }else{
43667      if( pagerUseWal(pPager) && bMmapOk==0 ){
43668        rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
43669        if( rc!=SQLITE_OK ) goto pager_acquire_err;
43670      }
43671      assert( pPg->pPager==pPager );
43672      pPager->aStat[PAGER_STAT_MISS]++;
43673      rc = readDbPage(pPg, iFrame);
43674      if( rc!=SQLITE_OK ){
43675        goto pager_acquire_err;
43676      }
43677    }
43678    pager_set_pagehash(pPg);
43679  }
43680
43681  return SQLITE_OK;
43682
43683pager_acquire_err:
43684  assert( rc!=SQLITE_OK );
43685  if( pPg ){
43686    sqlite3PcacheDrop(pPg);
43687  }
43688  pagerUnlockIfUnused(pPager);
43689
43690  *ppPage = 0;
43691  return rc;
43692}
43693
43694/*
43695** Acquire a page if it is already in the in-memory cache.  Do
43696** not read the page from disk.  Return a pointer to the page,
43697** or 0 if the page is not in cache.
43698**
43699** See also sqlite3PagerGet().  The difference between this routine
43700** and sqlite3PagerGet() is that _get() will go to the disk and read
43701** in the page if the page is not already in cache.  This routine
43702** returns NULL if the page is not in cache or if a disk I/O error
43703** has ever happened.
43704*/
43705SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
43706  PgHdr *pPg = 0;
43707  assert( pPager!=0 );
43708  assert( pgno!=0 );
43709  assert( pPager->pPCache!=0 );
43710  assert( pPager->eState>=PAGER_READER && pPager->eState!=PAGER_ERROR );
43711  sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
43712  return pPg;
43713}
43714
43715/*
43716** Release a page reference.
43717**
43718** If the number of references to the page drop to zero, then the
43719** page is added to the LRU list.  When all references to all pages
43720** are released, a rollback occurs and the lock on the database is
43721** removed.
43722*/
43723SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
43724  if( pPg ){
43725    Pager *pPager = pPg->pPager;
43726    if( pPg->flags & PGHDR_MMAP ){
43727      pagerReleaseMapPage(pPg);
43728    }else{
43729      sqlite3PcacheRelease(pPg);
43730    }
43731    pagerUnlockIfUnused(pPager);
43732  }
43733}
43734
43735/*
43736** This function is called at the start of every write transaction.
43737** There must already be a RESERVED or EXCLUSIVE lock on the database
43738** file when this routine is called.
43739**
43740** Open the journal file for pager pPager and write a journal header
43741** to the start of it. If there are active savepoints, open the sub-journal
43742** as well. This function is only used when the journal file is being
43743** opened to write a rollback log for a transaction. It is not used
43744** when opening a hot journal file to roll it back.
43745**
43746** If the journal file is already open (as it may be in exclusive mode),
43747** then this function just writes a journal header to the start of the
43748** already open file.
43749**
43750** Whether or not the journal file is opened by this function, the
43751** Pager.pInJournal bitvec structure is allocated.
43752**
43753** Return SQLITE_OK if everything is successful. Otherwise, return
43754** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
43755** an IO error code if opening or writing the journal file fails.
43756*/
43757static int pager_open_journal(Pager *pPager){
43758  int rc = SQLITE_OK;                        /* Return code */
43759  sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
43760
43761  assert( pPager->eState==PAGER_WRITER_LOCKED );
43762  assert( assert_pager_state(pPager) );
43763  assert( pPager->pInJournal==0 );
43764
43765  /* If already in the error state, this function is a no-op.  But on
43766  ** the other hand, this routine is never called if we are already in
43767  ** an error state. */
43768  if( NEVER(pPager->errCode) ) return pPager->errCode;
43769
43770  if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
43771    pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
43772    if( pPager->pInJournal==0 ){
43773      return SQLITE_NOMEM;
43774    }
43775
43776    /* Open the journal file if it is not already open. */
43777    if( !isOpen(pPager->jfd) ){
43778      if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
43779        sqlite3MemJournalOpen(pPager->jfd);
43780      }else{
43781        const int flags =                   /* VFS flags to open journal file */
43782          SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
43783          (pPager->tempFile ?
43784            (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
43785            (SQLITE_OPEN_MAIN_JOURNAL)
43786          );
43787  #ifdef SQLITE_ENABLE_ATOMIC_WRITE
43788        rc = sqlite3JournalOpen(
43789            pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
43790        );
43791  #else
43792        rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
43793  #endif
43794      }
43795      assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
43796    }
43797
43798
43799    /* Write the first journal header to the journal file and open
43800    ** the sub-journal if necessary.
43801    */
43802    if( rc==SQLITE_OK ){
43803      /* TODO: Check if all of these are really required. */
43804      pPager->nRec = 0;
43805      pPager->journalOff = 0;
43806      pPager->setMaster = 0;
43807      pPager->journalHdr = 0;
43808      rc = writeJournalHdr(pPager);
43809    }
43810  }
43811
43812  if( rc!=SQLITE_OK ){
43813    sqlite3BitvecDestroy(pPager->pInJournal);
43814    pPager->pInJournal = 0;
43815  }else{
43816    assert( pPager->eState==PAGER_WRITER_LOCKED );
43817    pPager->eState = PAGER_WRITER_CACHEMOD;
43818  }
43819
43820  return rc;
43821}
43822
43823/*
43824** Begin a write-transaction on the specified pager object. If a
43825** write-transaction has already been opened, this function is a no-op.
43826**
43827** If the exFlag argument is false, then acquire at least a RESERVED
43828** lock on the database file. If exFlag is true, then acquire at least
43829** an EXCLUSIVE lock. If such a lock is already held, no locking
43830** functions need be called.
43831**
43832** If the subjInMemory argument is non-zero, then any sub-journal opened
43833** within this transaction will be opened as an in-memory file. This
43834** has no effect if the sub-journal is already opened (as it may be when
43835** running in exclusive mode) or if the transaction does not require a
43836** sub-journal. If the subjInMemory argument is zero, then any required
43837** sub-journal is implemented in-memory if pPager is an in-memory database,
43838** or using a temporary file otherwise.
43839*/
43840SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
43841  int rc = SQLITE_OK;
43842
43843  if( pPager->errCode ) return pPager->errCode;
43844  assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
43845  pPager->subjInMemory = (u8)subjInMemory;
43846
43847  if( ALWAYS(pPager->eState==PAGER_READER) ){
43848    assert( pPager->pInJournal==0 );
43849
43850    if( pagerUseWal(pPager) ){
43851      /* If the pager is configured to use locking_mode=exclusive, and an
43852      ** exclusive lock on the database is not already held, obtain it now.
43853      */
43854      if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
43855        rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
43856        if( rc!=SQLITE_OK ){
43857          return rc;
43858        }
43859        sqlite3WalExclusiveMode(pPager->pWal, 1);
43860      }
43861
43862      /* Grab the write lock on the log file. If successful, upgrade to
43863      ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
43864      ** The busy-handler is not invoked if another connection already
43865      ** holds the write-lock. If possible, the upper layer will call it.
43866      */
43867      rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
43868    }else{
43869      /* Obtain a RESERVED lock on the database file. If the exFlag parameter
43870      ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
43871      ** busy-handler callback can be used when upgrading to the EXCLUSIVE
43872      ** lock, but not when obtaining the RESERVED lock.
43873      */
43874      rc = pagerLockDb(pPager, RESERVED_LOCK);
43875      if( rc==SQLITE_OK && exFlag ){
43876        rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
43877      }
43878    }
43879
43880    if( rc==SQLITE_OK ){
43881      /* Change to WRITER_LOCKED state.
43882      **
43883      ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
43884      ** when it has an open transaction, but never to DBMOD or FINISHED.
43885      ** This is because in those states the code to roll back savepoint
43886      ** transactions may copy data from the sub-journal into the database
43887      ** file as well as into the page cache. Which would be incorrect in
43888      ** WAL mode.
43889      */
43890      pPager->eState = PAGER_WRITER_LOCKED;
43891      pPager->dbHintSize = pPager->dbSize;
43892      pPager->dbFileSize = pPager->dbSize;
43893      pPager->dbOrigSize = pPager->dbSize;
43894      pPager->journalOff = 0;
43895    }
43896
43897    assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
43898    assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
43899    assert( assert_pager_state(pPager) );
43900  }
43901
43902  PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
43903  return rc;
43904}
43905
43906/*
43907** Mark a single data page as writeable. The page is written into the
43908** main journal or sub-journal as required. If the page is written into
43909** one of the journals, the corresponding bit is set in the
43910** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
43911** of any open savepoints as appropriate.
43912*/
43913static int pager_write(PgHdr *pPg){
43914  void *pData = pPg->pData;
43915  Pager *pPager = pPg->pPager;
43916  int rc = SQLITE_OK;
43917
43918  /* This routine is not called unless a write-transaction has already
43919  ** been started. The journal file may or may not be open at this point.
43920  ** It is never called in the ERROR state.
43921  */
43922  assert( pPager->eState==PAGER_WRITER_LOCKED
43923       || pPager->eState==PAGER_WRITER_CACHEMOD
43924       || pPager->eState==PAGER_WRITER_DBMOD
43925  );
43926  assert( assert_pager_state(pPager) );
43927
43928  /* If an error has been previously detected, report the same error
43929  ** again. This should not happen, but the check provides robustness. */
43930  if( NEVER(pPager->errCode) )  return pPager->errCode;
43931
43932  /* Higher-level routines never call this function if database is not
43933  ** writable.  But check anyway, just for robustness. */
43934  if( NEVER(pPager->readOnly) ) return SQLITE_PERM;
43935
43936  CHECK_PAGE(pPg);
43937
43938  /* The journal file needs to be opened. Higher level routines have already
43939  ** obtained the necessary locks to begin the write-transaction, but the
43940  ** rollback journal might not yet be open. Open it now if this is the case.
43941  **
43942  ** This is done before calling sqlite3PcacheMakeDirty() on the page.
43943  ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
43944  ** an error might occur and the pager would end up in WRITER_LOCKED state
43945  ** with pages marked as dirty in the cache.
43946  */
43947  if( pPager->eState==PAGER_WRITER_LOCKED ){
43948    rc = pager_open_journal(pPager);
43949    if( rc!=SQLITE_OK ) return rc;
43950  }
43951  assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
43952  assert( assert_pager_state(pPager) );
43953
43954  /* Mark the page as dirty.  If the page has already been written
43955  ** to the journal then we can return right away.
43956  */
43957  sqlite3PcacheMakeDirty(pPg);
43958  if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){
43959    assert( !pagerUseWal(pPager) );
43960  }else{
43961
43962    /* The transaction journal now exists and we have a RESERVED or an
43963    ** EXCLUSIVE lock on the main database file.  Write the current page to
43964    ** the transaction journal if it is not there already.
43965    */
43966    if( !pageInJournal(pPg) && !pagerUseWal(pPager) ){
43967      assert( pagerUseWal(pPager)==0 );
43968      if( pPg->pgno<=pPager->dbOrigSize && isOpen(pPager->jfd) ){
43969        u32 cksum;
43970        char *pData2;
43971        i64 iOff = pPager->journalOff;
43972
43973        /* We should never write to the journal file the page that
43974        ** contains the database locks.  The following assert verifies
43975        ** that we do not. */
43976        assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
43977
43978        assert( pPager->journalHdr<=pPager->journalOff );
43979        CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
43980        cksum = pager_cksum(pPager, (u8*)pData2);
43981
43982        /* Even if an IO or diskfull error occurs while journalling the
43983        ** page in the block above, set the need-sync flag for the page.
43984        ** Otherwise, when the transaction is rolled back, the logic in
43985        ** playback_one_page() will think that the page needs to be restored
43986        ** in the database file. And if an IO error occurs while doing so,
43987        ** then corruption may follow.
43988        */
43989        pPg->flags |= PGHDR_NEED_SYNC;
43990
43991        rc = write32bits(pPager->jfd, iOff, pPg->pgno);
43992        if( rc!=SQLITE_OK ) return rc;
43993        rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
43994        if( rc!=SQLITE_OK ) return rc;
43995        rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
43996        if( rc!=SQLITE_OK ) return rc;
43997
43998        IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
43999                 pPager->journalOff, pPager->pageSize));
44000        PAGER_INCR(sqlite3_pager_writej_count);
44001        PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
44002             PAGERID(pPager), pPg->pgno,
44003             ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
44004
44005        pPager->journalOff += 8 + pPager->pageSize;
44006        pPager->nRec++;
44007        assert( pPager->pInJournal!=0 );
44008        rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
44009        testcase( rc==SQLITE_NOMEM );
44010        assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
44011        rc |= addToSavepointBitvecs(pPager, pPg->pgno);
44012        if( rc!=SQLITE_OK ){
44013          assert( rc==SQLITE_NOMEM );
44014          return rc;
44015        }
44016      }else{
44017        if( pPager->eState!=PAGER_WRITER_DBMOD ){
44018          pPg->flags |= PGHDR_NEED_SYNC;
44019        }
44020        PAGERTRACE(("APPEND %d page %d needSync=%d\n",
44021                PAGERID(pPager), pPg->pgno,
44022               ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
44023      }
44024    }
44025
44026    /* If the statement journal is open and the page is not in it,
44027    ** then write the current page to the statement journal.  Note that
44028    ** the statement journal format differs from the standard journal format
44029    ** in that it omits the checksums and the header.
44030    */
44031    if( subjRequiresPage(pPg) ){
44032      rc = subjournalPage(pPg);
44033    }
44034  }
44035
44036  /* Update the database size and return.
44037  */
44038  if( pPager->dbSize<pPg->pgno ){
44039    pPager->dbSize = pPg->pgno;
44040  }
44041  return rc;
44042}
44043
44044/*
44045** Mark a data page as writeable. This routine must be called before
44046** making changes to a page. The caller must check the return value
44047** of this function and be careful not to change any page data unless
44048** this routine returns SQLITE_OK.
44049**
44050** The difference between this function and pager_write() is that this
44051** function also deals with the special case where 2 or more pages
44052** fit on a single disk sector. In this case all co-resident pages
44053** must have been written to the journal file before returning.
44054**
44055** If an error occurs, SQLITE_NOMEM or an IO error code is returned
44056** as appropriate. Otherwise, SQLITE_OK.
44057*/
44058SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
44059  int rc = SQLITE_OK;
44060
44061  PgHdr *pPg = pDbPage;
44062  Pager *pPager = pPg->pPager;
44063  Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
44064
44065  assert( (pPg->flags & PGHDR_MMAP)==0 );
44066  assert( pPager->eState>=PAGER_WRITER_LOCKED );
44067  assert( pPager->eState!=PAGER_ERROR );
44068  assert( assert_pager_state(pPager) );
44069
44070  if( nPagePerSector>1 ){
44071    Pgno nPageCount;          /* Total number of pages in database file */
44072    Pgno pg1;                 /* First page of the sector pPg is located on. */
44073    int nPage = 0;            /* Number of pages starting at pg1 to journal */
44074    int ii;                   /* Loop counter */
44075    int needSync = 0;         /* True if any page has PGHDR_NEED_SYNC */
44076
44077    /* Set the doNotSyncSpill flag to 1. This is because we cannot allow
44078    ** a journal header to be written between the pages journaled by
44079    ** this function.
44080    */
44081    assert( !MEMDB );
44082    assert( pPager->doNotSyncSpill==0 );
44083    pPager->doNotSyncSpill++;
44084
44085    /* This trick assumes that both the page-size and sector-size are
44086    ** an integer power of 2. It sets variable pg1 to the identifier
44087    ** of the first page of the sector pPg is located on.
44088    */
44089    pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
44090
44091    nPageCount = pPager->dbSize;
44092    if( pPg->pgno>nPageCount ){
44093      nPage = (pPg->pgno - pg1)+1;
44094    }else if( (pg1+nPagePerSector-1)>nPageCount ){
44095      nPage = nPageCount+1-pg1;
44096    }else{
44097      nPage = nPagePerSector;
44098    }
44099    assert(nPage>0);
44100    assert(pg1<=pPg->pgno);
44101    assert((pg1+nPage)>pPg->pgno);
44102
44103    for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
44104      Pgno pg = pg1+ii;
44105      PgHdr *pPage;
44106      if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
44107        if( pg!=PAGER_MJ_PGNO(pPager) ){
44108          rc = sqlite3PagerGet(pPager, pg, &pPage);
44109          if( rc==SQLITE_OK ){
44110            rc = pager_write(pPage);
44111            if( pPage->flags&PGHDR_NEED_SYNC ){
44112              needSync = 1;
44113            }
44114            sqlite3PagerUnref(pPage);
44115          }
44116        }
44117      }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
44118        if( pPage->flags&PGHDR_NEED_SYNC ){
44119          needSync = 1;
44120        }
44121        sqlite3PagerUnref(pPage);
44122      }
44123    }
44124
44125    /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
44126    ** starting at pg1, then it needs to be set for all of them. Because
44127    ** writing to any of these nPage pages may damage the others, the
44128    ** journal file must contain sync()ed copies of all of them
44129    ** before any of them can be written out to the database file.
44130    */
44131    if( rc==SQLITE_OK && needSync ){
44132      assert( !MEMDB );
44133      for(ii=0; ii<nPage; ii++){
44134        PgHdr *pPage = pager_lookup(pPager, pg1+ii);
44135        if( pPage ){
44136          pPage->flags |= PGHDR_NEED_SYNC;
44137          sqlite3PagerUnref(pPage);
44138        }
44139      }
44140    }
44141
44142    assert( pPager->doNotSyncSpill==1 );
44143    pPager->doNotSyncSpill--;
44144  }else{
44145    rc = pager_write(pDbPage);
44146  }
44147  return rc;
44148}
44149
44150/*
44151** Return TRUE if the page given in the argument was previously passed
44152** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
44153** to change the content of the page.
44154*/
44155#ifndef NDEBUG
44156SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
44157  return pPg->flags&PGHDR_DIRTY;
44158}
44159#endif
44160
44161/*
44162** A call to this routine tells the pager that it is not necessary to
44163** write the information on page pPg back to the disk, even though
44164** that page might be marked as dirty.  This happens, for example, when
44165** the page has been added as a leaf of the freelist and so its
44166** content no longer matters.
44167**
44168** The overlying software layer calls this routine when all of the data
44169** on the given page is unused. The pager marks the page as clean so
44170** that it does not get written to disk.
44171**
44172** Tests show that this optimization can quadruple the speed of large
44173** DELETE operations.
44174*/
44175SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
44176  Pager *pPager = pPg->pPager;
44177  if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
44178    PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
44179    IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
44180    pPg->flags |= PGHDR_DONT_WRITE;
44181    pager_set_pagehash(pPg);
44182  }
44183}
44184
44185/*
44186** This routine is called to increment the value of the database file
44187** change-counter, stored as a 4-byte big-endian integer starting at
44188** byte offset 24 of the pager file.  The secondary change counter at
44189** 92 is also updated, as is the SQLite version number at offset 96.
44190**
44191** But this only happens if the pPager->changeCountDone flag is false.
44192** To avoid excess churning of page 1, the update only happens once.
44193** See also the pager_write_changecounter() routine that does an
44194** unconditional update of the change counters.
44195**
44196** If the isDirectMode flag is zero, then this is done by calling
44197** sqlite3PagerWrite() on page 1, then modifying the contents of the
44198** page data. In this case the file will be updated when the current
44199** transaction is committed.
44200**
44201** The isDirectMode flag may only be non-zero if the library was compiled
44202** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
44203** if isDirect is non-zero, then the database file is updated directly
44204** by writing an updated version of page 1 using a call to the
44205** sqlite3OsWrite() function.
44206*/
44207static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
44208  int rc = SQLITE_OK;
44209
44210  assert( pPager->eState==PAGER_WRITER_CACHEMOD
44211       || pPager->eState==PAGER_WRITER_DBMOD
44212  );
44213  assert( assert_pager_state(pPager) );
44214
44215  /* Declare and initialize constant integer 'isDirect'. If the
44216  ** atomic-write optimization is enabled in this build, then isDirect
44217  ** is initialized to the value passed as the isDirectMode parameter
44218  ** to this function. Otherwise, it is always set to zero.
44219  **
44220  ** The idea is that if the atomic-write optimization is not
44221  ** enabled at compile time, the compiler can omit the tests of
44222  ** 'isDirect' below, as well as the block enclosed in the
44223  ** "if( isDirect )" condition.
44224  */
44225#ifndef SQLITE_ENABLE_ATOMIC_WRITE
44226# define DIRECT_MODE 0
44227  assert( isDirectMode==0 );
44228  UNUSED_PARAMETER(isDirectMode);
44229#else
44230# define DIRECT_MODE isDirectMode
44231#endif
44232
44233  if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
44234    PgHdr *pPgHdr;                /* Reference to page 1 */
44235
44236    assert( !pPager->tempFile && isOpen(pPager->fd) );
44237
44238    /* Open page 1 of the file for writing. */
44239    rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
44240    assert( pPgHdr==0 || rc==SQLITE_OK );
44241
44242    /* If page one was fetched successfully, and this function is not
44243    ** operating in direct-mode, make page 1 writable.  When not in
44244    ** direct mode, page 1 is always held in cache and hence the PagerGet()
44245    ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
44246    */
44247    if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
44248      rc = sqlite3PagerWrite(pPgHdr);
44249    }
44250
44251    if( rc==SQLITE_OK ){
44252      /* Actually do the update of the change counter */
44253      pager_write_changecounter(pPgHdr);
44254
44255      /* If running in direct mode, write the contents of page 1 to the file. */
44256      if( DIRECT_MODE ){
44257        const void *zBuf;
44258        assert( pPager->dbFileSize>0 );
44259        CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
44260        if( rc==SQLITE_OK ){
44261          rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
44262          pPager->aStat[PAGER_STAT_WRITE]++;
44263        }
44264        if( rc==SQLITE_OK ){
44265          /* Update the pager's copy of the change-counter. Otherwise, the
44266          ** next time a read transaction is opened the cache will be
44267          ** flushed (as the change-counter values will not match).  */
44268          const void *pCopy = (const void *)&((const char *)zBuf)[24];
44269          memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));
44270          pPager->changeCountDone = 1;
44271        }
44272      }else{
44273        pPager->changeCountDone = 1;
44274      }
44275    }
44276
44277    /* Release the page reference. */
44278    sqlite3PagerUnref(pPgHdr);
44279  }
44280  return rc;
44281}
44282
44283/*
44284** Sync the database file to disk. This is a no-op for in-memory databases
44285** or pages with the Pager.noSync flag set.
44286**
44287** If successful, or if called on a pager for which it is a no-op, this
44288** function returns SQLITE_OK. Otherwise, an IO error code is returned.
44289*/
44290SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){
44291  int rc = SQLITE_OK;
44292  if( !pPager->noSync ){
44293    assert( !MEMDB );
44294    rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
44295  }else if( isOpen(pPager->fd) ){
44296    assert( !MEMDB );
44297    rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC_OMITTED, 0);
44298    if( rc==SQLITE_NOTFOUND ){
44299      rc = SQLITE_OK;
44300    }
44301  }
44302  return rc;
44303}
44304
44305/*
44306** This function may only be called while a write-transaction is active in
44307** rollback. If the connection is in WAL mode, this call is a no-op.
44308** Otherwise, if the connection does not already have an EXCLUSIVE lock on
44309** the database file, an attempt is made to obtain one.
44310**
44311** If the EXCLUSIVE lock is already held or the attempt to obtain it is
44312** successful, or the connection is in WAL mode, SQLITE_OK is returned.
44313** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
44314** returned.
44315*/
44316SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
44317  int rc = SQLITE_OK;
44318  assert( pPager->eState==PAGER_WRITER_CACHEMOD
44319       || pPager->eState==PAGER_WRITER_DBMOD
44320       || pPager->eState==PAGER_WRITER_LOCKED
44321  );
44322  assert( assert_pager_state(pPager) );
44323  if( 0==pagerUseWal(pPager) ){
44324    rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
44325  }
44326  return rc;
44327}
44328
44329/*
44330** Sync the database file for the pager pPager. zMaster points to the name
44331** of a master journal file that should be written into the individual
44332** journal file. zMaster may be NULL, which is interpreted as no master
44333** journal (a single database transaction).
44334**
44335** This routine ensures that:
44336**
44337**   * The database file change-counter is updated,
44338**   * the journal is synced (unless the atomic-write optimization is used),
44339**   * all dirty pages are written to the database file,
44340**   * the database file is truncated (if required), and
44341**   * the database file synced.
44342**
44343** The only thing that remains to commit the transaction is to finalize
44344** (delete, truncate or zero the first part of) the journal file (or
44345** delete the master journal file if specified).
44346**
44347** Note that if zMaster==NULL, this does not overwrite a previous value
44348** passed to an sqlite3PagerCommitPhaseOne() call.
44349**
44350** If the final parameter - noSync - is true, then the database file itself
44351** is not synced. The caller must call sqlite3PagerSync() directly to
44352** sync the database file before calling CommitPhaseTwo() to delete the
44353** journal file in this case.
44354*/
44355SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
44356  Pager *pPager,                  /* Pager object */
44357  const char *zMaster,            /* If not NULL, the master journal name */
44358  int noSync                      /* True to omit the xSync on the db file */
44359){
44360  int rc = SQLITE_OK;             /* Return code */
44361
44362  assert( pPager->eState==PAGER_WRITER_LOCKED
44363       || pPager->eState==PAGER_WRITER_CACHEMOD
44364       || pPager->eState==PAGER_WRITER_DBMOD
44365       || pPager->eState==PAGER_ERROR
44366  );
44367  assert( assert_pager_state(pPager) );
44368
44369  /* If a prior error occurred, report that error again. */
44370  if( NEVER(pPager->errCode) ) return pPager->errCode;
44371
44372  PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
44373      pPager->zFilename, zMaster, pPager->dbSize));
44374
44375  /* If no database changes have been made, return early. */
44376  if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
44377
44378  if( MEMDB ){
44379    /* If this is an in-memory db, or no pages have been written to, or this
44380    ** function has already been called, it is mostly a no-op.  However, any
44381    ** backup in progress needs to be restarted.
44382    */
44383    sqlite3BackupRestart(pPager->pBackup);
44384  }else{
44385    if( pagerUseWal(pPager) ){
44386      PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
44387      PgHdr *pPageOne = 0;
44388      if( pList==0 ){
44389        /* Must have at least one page for the WAL commit flag.
44390        ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
44391        rc = sqlite3PagerGet(pPager, 1, &pPageOne);
44392        pList = pPageOne;
44393        pList->pDirty = 0;
44394      }
44395      assert( rc==SQLITE_OK );
44396      if( ALWAYS(pList) ){
44397        rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
44398      }
44399      sqlite3PagerUnref(pPageOne);
44400      if( rc==SQLITE_OK ){
44401        sqlite3PcacheCleanAll(pPager->pPCache);
44402      }
44403    }else{
44404      /* The following block updates the change-counter. Exactly how it
44405      ** does this depends on whether or not the atomic-update optimization
44406      ** was enabled at compile time, and if this transaction meets the
44407      ** runtime criteria to use the operation:
44408      **
44409      **    * The file-system supports the atomic-write property for
44410      **      blocks of size page-size, and
44411      **    * This commit is not part of a multi-file transaction, and
44412      **    * Exactly one page has been modified and store in the journal file.
44413      **
44414      ** If the optimization was not enabled at compile time, then the
44415      ** pager_incr_changecounter() function is called to update the change
44416      ** counter in 'indirect-mode'. If the optimization is compiled in but
44417      ** is not applicable to this transaction, call sqlite3JournalCreate()
44418      ** to make sure the journal file has actually been created, then call
44419      ** pager_incr_changecounter() to update the change-counter in indirect
44420      ** mode.
44421      **
44422      ** Otherwise, if the optimization is both enabled and applicable,
44423      ** then call pager_incr_changecounter() to update the change-counter
44424      ** in 'direct' mode. In this case the journal file will never be
44425      ** created for this transaction.
44426      */
44427  #ifdef SQLITE_ENABLE_ATOMIC_WRITE
44428      PgHdr *pPg;
44429      assert( isOpen(pPager->jfd)
44430           || pPager->journalMode==PAGER_JOURNALMODE_OFF
44431           || pPager->journalMode==PAGER_JOURNALMODE_WAL
44432      );
44433      if( !zMaster && isOpen(pPager->jfd)
44434       && pPager->journalOff==jrnlBufferSize(pPager)
44435       && pPager->dbSize>=pPager->dbOrigSize
44436       && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
44437      ){
44438        /* Update the db file change counter via the direct-write method. The
44439        ** following call will modify the in-memory representation of page 1
44440        ** to include the updated change counter and then write page 1
44441        ** directly to the database file. Because of the atomic-write
44442        ** property of the host file-system, this is safe.
44443        */
44444        rc = pager_incr_changecounter(pPager, 1);
44445      }else{
44446        rc = sqlite3JournalCreate(pPager->jfd);
44447        if( rc==SQLITE_OK ){
44448          rc = pager_incr_changecounter(pPager, 0);
44449        }
44450      }
44451  #else
44452      rc = pager_incr_changecounter(pPager, 0);
44453  #endif
44454      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
44455
44456      /* Write the master journal name into the journal file. If a master
44457      ** journal file name has already been written to the journal file,
44458      ** or if zMaster is NULL (no master journal), then this call is a no-op.
44459      */
44460      rc = writeMasterJournal(pPager, zMaster);
44461      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
44462
44463      /* Sync the journal file and write all dirty pages to the database.
44464      ** If the atomic-update optimization is being used, this sync will not
44465      ** create the journal file or perform any real IO.
44466      **
44467      ** Because the change-counter page was just modified, unless the
44468      ** atomic-update optimization is used it is almost certain that the
44469      ** journal requires a sync here. However, in locking_mode=exclusive
44470      ** on a system under memory pressure it is just possible that this is
44471      ** not the case. In this case it is likely enough that the redundant
44472      ** xSync() call will be changed to a no-op by the OS anyhow.
44473      */
44474      rc = syncJournal(pPager, 0);
44475      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
44476
44477      rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
44478      if( rc!=SQLITE_OK ){
44479        assert( rc!=SQLITE_IOERR_BLOCKED );
44480        goto commit_phase_one_exit;
44481      }
44482      sqlite3PcacheCleanAll(pPager->pPCache);
44483
44484      /* If the file on disk is smaller than the database image, use
44485      ** pager_truncate to grow the file here. This can happen if the database
44486      ** image was extended as part of the current transaction and then the
44487      ** last page in the db image moved to the free-list. In this case the
44488      ** last page is never written out to disk, leaving the database file
44489      ** undersized. Fix this now if it is the case.  */
44490      if( pPager->dbSize>pPager->dbFileSize ){
44491        Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
44492        assert( pPager->eState==PAGER_WRITER_DBMOD );
44493        rc = pager_truncate(pPager, nNew);
44494        if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
44495      }
44496
44497      /* Finally, sync the database file. */
44498      if( !noSync ){
44499        rc = sqlite3PagerSync(pPager);
44500      }
44501      IOTRACE(("DBSYNC %p\n", pPager))
44502    }
44503  }
44504
44505commit_phase_one_exit:
44506  if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
44507    pPager->eState = PAGER_WRITER_FINISHED;
44508  }
44509  return rc;
44510}
44511
44512
44513/*
44514** When this function is called, the database file has been completely
44515** updated to reflect the changes made by the current transaction and
44516** synced to disk. The journal file still exists in the file-system
44517** though, and if a failure occurs at this point it will eventually
44518** be used as a hot-journal and the current transaction rolled back.
44519**
44520** This function finalizes the journal file, either by deleting,
44521** truncating or partially zeroing it, so that it cannot be used
44522** for hot-journal rollback. Once this is done the transaction is
44523** irrevocably committed.
44524**
44525** If an error occurs, an IO error code is returned and the pager
44526** moves into the error state. Otherwise, SQLITE_OK is returned.
44527*/
44528SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
44529  int rc = SQLITE_OK;                  /* Return code */
44530
44531  /* This routine should not be called if a prior error has occurred.
44532  ** But if (due to a coding error elsewhere in the system) it does get
44533  ** called, just return the same error code without doing anything. */
44534  if( NEVER(pPager->errCode) ) return pPager->errCode;
44535
44536  assert( pPager->eState==PAGER_WRITER_LOCKED
44537       || pPager->eState==PAGER_WRITER_FINISHED
44538       || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
44539  );
44540  assert( assert_pager_state(pPager) );
44541
44542  /* An optimization. If the database was not actually modified during
44543  ** this transaction, the pager is running in exclusive-mode and is
44544  ** using persistent journals, then this function is a no-op.
44545  **
44546  ** The start of the journal file currently contains a single journal
44547  ** header with the nRec field set to 0. If such a journal is used as
44548  ** a hot-journal during hot-journal rollback, 0 changes will be made
44549  ** to the database file. So there is no need to zero the journal
44550  ** header. Since the pager is in exclusive mode, there is no need
44551  ** to drop any locks either.
44552  */
44553  if( pPager->eState==PAGER_WRITER_LOCKED
44554   && pPager->exclusiveMode
44555   && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
44556  ){
44557    assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
44558    pPager->eState = PAGER_READER;
44559    return SQLITE_OK;
44560  }
44561
44562  PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
44563  rc = pager_end_transaction(pPager, pPager->setMaster, 1);
44564  return pager_error(pPager, rc);
44565}
44566
44567/*
44568** If a write transaction is open, then all changes made within the
44569** transaction are reverted and the current write-transaction is closed.
44570** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
44571** state if an error occurs.
44572**
44573** If the pager is already in PAGER_ERROR state when this function is called,
44574** it returns Pager.errCode immediately. No work is performed in this case.
44575**
44576** Otherwise, in rollback mode, this function performs two functions:
44577**
44578**   1) It rolls back the journal file, restoring all database file and
44579**      in-memory cache pages to the state they were in when the transaction
44580**      was opened, and
44581**
44582**   2) It finalizes the journal file, so that it is not used for hot
44583**      rollback at any point in the future.
44584**
44585** Finalization of the journal file (task 2) is only performed if the
44586** rollback is successful.
44587**
44588** In WAL mode, all cache-entries containing data modified within the
44589** current transaction are either expelled from the cache or reverted to
44590** their pre-transaction state by re-reading data from the database or
44591** WAL files. The WAL transaction is then closed.
44592*/
44593SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
44594  int rc = SQLITE_OK;                  /* Return code */
44595  PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
44596
44597  /* PagerRollback() is a no-op if called in READER or OPEN state. If
44598  ** the pager is already in the ERROR state, the rollback is not
44599  ** attempted here. Instead, the error code is returned to the caller.
44600  */
44601  assert( assert_pager_state(pPager) );
44602  if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
44603  if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
44604
44605  if( pagerUseWal(pPager) ){
44606    int rc2;
44607    rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
44608    rc2 = pager_end_transaction(pPager, pPager->setMaster, 0);
44609    if( rc==SQLITE_OK ) rc = rc2;
44610  }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
44611    int eState = pPager->eState;
44612    rc = pager_end_transaction(pPager, 0, 0);
44613    if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
44614      /* This can happen using journal_mode=off. Move the pager to the error
44615      ** state to indicate that the contents of the cache may not be trusted.
44616      ** Any active readers will get SQLITE_ABORT.
44617      */
44618      pPager->errCode = SQLITE_ABORT;
44619      pPager->eState = PAGER_ERROR;
44620      return rc;
44621    }
44622  }else{
44623    rc = pager_playback(pPager, 0);
44624  }
44625
44626  assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
44627  assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT
44628          || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR );
44629
44630  /* If an error occurs during a ROLLBACK, we can no longer trust the pager
44631  ** cache. So call pager_error() on the way out to make any error persistent.
44632  */
44633  return pager_error(pPager, rc);
44634}
44635
44636/*
44637** Return TRUE if the database file is opened read-only.  Return FALSE
44638** if the database is (in theory) writable.
44639*/
44640SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
44641  return pPager->readOnly;
44642}
44643
44644/*
44645** Return the number of references to the pager.
44646*/
44647SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
44648  return sqlite3PcacheRefCount(pPager->pPCache);
44649}
44650
44651/*
44652** Return the approximate number of bytes of memory currently
44653** used by the pager and its associated cache.
44654*/
44655SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
44656  int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
44657                                     + 5*sizeof(void*);
44658  return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
44659           + sqlite3MallocSize(pPager)
44660           + pPager->pageSize;
44661}
44662
44663/*
44664** Return the number of references to the specified page.
44665*/
44666SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
44667  return sqlite3PcachePageRefcount(pPage);
44668}
44669
44670#ifdef SQLITE_TEST
44671/*
44672** This routine is used for testing and analysis only.
44673*/
44674SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
44675  static int a[11];
44676  a[0] = sqlite3PcacheRefCount(pPager->pPCache);
44677  a[1] = sqlite3PcachePagecount(pPager->pPCache);
44678  a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
44679  a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
44680  a[4] = pPager->eState;
44681  a[5] = pPager->errCode;
44682  a[6] = pPager->aStat[PAGER_STAT_HIT];
44683  a[7] = pPager->aStat[PAGER_STAT_MISS];
44684  a[8] = 0;  /* Used to be pPager->nOvfl */
44685  a[9] = pPager->nRead;
44686  a[10] = pPager->aStat[PAGER_STAT_WRITE];
44687  return a;
44688}
44689#endif
44690
44691/*
44692** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or
44693** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
44694** current cache hit or miss count, according to the value of eStat. If the
44695** reset parameter is non-zero, the cache hit or miss count is zeroed before
44696** returning.
44697*/
44698SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
44699
44700  assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
44701       || eStat==SQLITE_DBSTATUS_CACHE_MISS
44702       || eStat==SQLITE_DBSTATUS_CACHE_WRITE
44703  );
44704
44705  assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
44706  assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
44707  assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 && PAGER_STAT_WRITE==2 );
44708
44709  *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT];
44710  if( reset ){
44711    pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0;
44712  }
44713}
44714
44715/*
44716** Return true if this is an in-memory pager.
44717*/
44718SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
44719  return MEMDB;
44720}
44721
44722/*
44723** Check that there are at least nSavepoint savepoints open. If there are
44724** currently less than nSavepoints open, then open one or more savepoints
44725** to make up the difference. If the number of savepoints is already
44726** equal to nSavepoint, then this function is a no-op.
44727**
44728** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
44729** occurs while opening the sub-journal file, then an IO error code is
44730** returned. Otherwise, SQLITE_OK.
44731*/
44732SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
44733  int rc = SQLITE_OK;                       /* Return code */
44734  int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
44735
44736  assert( pPager->eState>=PAGER_WRITER_LOCKED );
44737  assert( assert_pager_state(pPager) );
44738
44739  if( nSavepoint>nCurrent && pPager->useJournal ){
44740    int ii;                                 /* Iterator variable */
44741    PagerSavepoint *aNew;                   /* New Pager.aSavepoint array */
44742
44743    /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
44744    ** if the allocation fails. Otherwise, zero the new portion in case a
44745    ** malloc failure occurs while populating it in the for(...) loop below.
44746    */
44747    aNew = (PagerSavepoint *)sqlite3Realloc(
44748        pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
44749    );
44750    if( !aNew ){
44751      return SQLITE_NOMEM;
44752    }
44753    memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
44754    pPager->aSavepoint = aNew;
44755
44756    /* Populate the PagerSavepoint structures just allocated. */
44757    for(ii=nCurrent; ii<nSavepoint; ii++){
44758      aNew[ii].nOrig = pPager->dbSize;
44759      if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
44760        aNew[ii].iOffset = pPager->journalOff;
44761      }else{
44762        aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
44763      }
44764      aNew[ii].iSubRec = pPager->nSubRec;
44765      aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
44766      if( !aNew[ii].pInSavepoint ){
44767        return SQLITE_NOMEM;
44768      }
44769      if( pagerUseWal(pPager) ){
44770        sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
44771      }
44772      pPager->nSavepoint = ii+1;
44773    }
44774    assert( pPager->nSavepoint==nSavepoint );
44775    assertTruncateConstraint(pPager);
44776  }
44777
44778  return rc;
44779}
44780
44781/*
44782** This function is called to rollback or release (commit) a savepoint.
44783** The savepoint to release or rollback need not be the most recently
44784** created savepoint.
44785**
44786** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
44787** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
44788** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
44789** that have occurred since the specified savepoint was created.
44790**
44791** The savepoint to rollback or release is identified by parameter
44792** iSavepoint. A value of 0 means to operate on the outermost savepoint
44793** (the first created). A value of (Pager.nSavepoint-1) means operate
44794** on the most recently created savepoint. If iSavepoint is greater than
44795** (Pager.nSavepoint-1), then this function is a no-op.
44796**
44797** If a negative value is passed to this function, then the current
44798** transaction is rolled back. This is different to calling
44799** sqlite3PagerRollback() because this function does not terminate
44800** the transaction or unlock the database, it just restores the
44801** contents of the database to its original state.
44802**
44803** In any case, all savepoints with an index greater than iSavepoint
44804** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
44805** then savepoint iSavepoint is also destroyed.
44806**
44807** This function may return SQLITE_NOMEM if a memory allocation fails,
44808** or an IO error code if an IO error occurs while rolling back a
44809** savepoint. If no errors occur, SQLITE_OK is returned.
44810*/
44811SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
44812  int rc = pPager->errCode;       /* Return code */
44813
44814  assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
44815  assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
44816
44817  if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
44818    int ii;            /* Iterator variable */
44819    int nNew;          /* Number of remaining savepoints after this op. */
44820
44821    /* Figure out how many savepoints will still be active after this
44822    ** operation. Store this value in nNew. Then free resources associated
44823    ** with any savepoints that are destroyed by this operation.
44824    */
44825    nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
44826    for(ii=nNew; ii<pPager->nSavepoint; ii++){
44827      sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
44828    }
44829    pPager->nSavepoint = nNew;
44830
44831    /* If this is a release of the outermost savepoint, truncate
44832    ** the sub-journal to zero bytes in size. */
44833    if( op==SAVEPOINT_RELEASE ){
44834      if( nNew==0 && isOpen(pPager->sjfd) ){
44835        /* Only truncate if it is an in-memory sub-journal. */
44836        if( sqlite3IsMemJournal(pPager->sjfd) ){
44837          rc = sqlite3OsTruncate(pPager->sjfd, 0);
44838          assert( rc==SQLITE_OK );
44839        }
44840        pPager->nSubRec = 0;
44841      }
44842    }
44843    /* Else this is a rollback operation, playback the specified savepoint.
44844    ** If this is a temp-file, it is possible that the journal file has
44845    ** not yet been opened. In this case there have been no changes to
44846    ** the database file, so the playback operation can be skipped.
44847    */
44848    else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
44849      PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
44850      rc = pagerPlaybackSavepoint(pPager, pSavepoint);
44851      assert(rc!=SQLITE_DONE);
44852    }
44853  }
44854
44855  return rc;
44856}
44857
44858/*
44859** Return the full pathname of the database file.
44860**
44861** Except, if the pager is in-memory only, then return an empty string if
44862** nullIfMemDb is true.  This routine is called with nullIfMemDb==1 when
44863** used to report the filename to the user, for compatibility with legacy
44864** behavior.  But when the Btree needs to know the filename for matching to
44865** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
44866** participate in shared-cache.
44867*/
44868SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
44869  return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
44870}
44871
44872/*
44873** Return the VFS structure for the pager.
44874*/
44875SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
44876  return pPager->pVfs;
44877}
44878
44879/*
44880** Return the file handle for the database file associated
44881** with the pager.  This might return NULL if the file has
44882** not yet been opened.
44883*/
44884SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
44885  return pPager->fd;
44886}
44887
44888/*
44889** Return the full pathname of the journal file.
44890*/
44891SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
44892  return pPager->zJournal;
44893}
44894
44895/*
44896** Return true if fsync() calls are disabled for this pager.  Return FALSE
44897** if fsync()s are executed normally.
44898*/
44899SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
44900  return pPager->noSync;
44901}
44902
44903#ifdef SQLITE_HAS_CODEC
44904/*
44905** Set or retrieve the codec for this pager
44906*/
44907SQLITE_PRIVATE void sqlite3PagerSetCodec(
44908  Pager *pPager,
44909  void *(*xCodec)(void*,void*,Pgno,int),
44910  void (*xCodecSizeChng)(void*,int,int),
44911  void (*xCodecFree)(void*),
44912  void *pCodec
44913){
44914  if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
44915  pPager->xCodec = pPager->memDb ? 0 : xCodec;
44916  pPager->xCodecSizeChng = xCodecSizeChng;
44917  pPager->xCodecFree = xCodecFree;
44918  pPager->pCodec = pCodec;
44919  pagerReportSize(pPager);
44920}
44921SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
44922  return pPager->pCodec;
44923}
44924#endif
44925
44926#ifndef SQLITE_OMIT_AUTOVACUUM
44927/*
44928** Move the page pPg to location pgno in the file.
44929**
44930** There must be no references to the page previously located at
44931** pgno (which we call pPgOld) though that page is allowed to be
44932** in cache.  If the page previously located at pgno is not already
44933** in the rollback journal, it is not put there by by this routine.
44934**
44935** References to the page pPg remain valid. Updating any
44936** meta-data associated with pPg (i.e. data stored in the nExtra bytes
44937** allocated along with the page) is the responsibility of the caller.
44938**
44939** A transaction must be active when this routine is called. It used to be
44940** required that a statement transaction was not active, but this restriction
44941** has been removed (CREATE INDEX needs to move a page when a statement
44942** transaction is active).
44943**
44944** If the fourth argument, isCommit, is non-zero, then this page is being
44945** moved as part of a database reorganization just before the transaction
44946** is being committed. In this case, it is guaranteed that the database page
44947** pPg refers to will not be written to again within this transaction.
44948**
44949** This function may return SQLITE_NOMEM or an IO error code if an error
44950** occurs. Otherwise, it returns SQLITE_OK.
44951*/
44952SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
44953  PgHdr *pPgOld;               /* The page being overwritten. */
44954  Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
44955  int rc;                      /* Return code */
44956  Pgno origPgno;               /* The original page number */
44957
44958  assert( pPg->nRef>0 );
44959  assert( pPager->eState==PAGER_WRITER_CACHEMOD
44960       || pPager->eState==PAGER_WRITER_DBMOD
44961  );
44962  assert( assert_pager_state(pPager) );
44963
44964  /* In order to be able to rollback, an in-memory database must journal
44965  ** the page we are moving from.
44966  */
44967  if( MEMDB ){
44968    rc = sqlite3PagerWrite(pPg);
44969    if( rc ) return rc;
44970  }
44971
44972  /* If the page being moved is dirty and has not been saved by the latest
44973  ** savepoint, then save the current contents of the page into the
44974  ** sub-journal now. This is required to handle the following scenario:
44975  **
44976  **   BEGIN;
44977  **     <journal page X, then modify it in memory>
44978  **     SAVEPOINT one;
44979  **       <Move page X to location Y>
44980  **     ROLLBACK TO one;
44981  **
44982  ** If page X were not written to the sub-journal here, it would not
44983  ** be possible to restore its contents when the "ROLLBACK TO one"
44984  ** statement were is processed.
44985  **
44986  ** subjournalPage() may need to allocate space to store pPg->pgno into
44987  ** one or more savepoint bitvecs. This is the reason this function
44988  ** may return SQLITE_NOMEM.
44989  */
44990  if( pPg->flags&PGHDR_DIRTY
44991   && subjRequiresPage(pPg)
44992   && SQLITE_OK!=(rc = subjournalPage(pPg))
44993  ){
44994    return rc;
44995  }
44996
44997  PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
44998      PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
44999  IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
45000
45001  /* If the journal needs to be sync()ed before page pPg->pgno can
45002  ** be written to, store pPg->pgno in local variable needSyncPgno.
45003  **
45004  ** If the isCommit flag is set, there is no need to remember that
45005  ** the journal needs to be sync()ed before database page pPg->pgno
45006  ** can be written to. The caller has already promised not to write to it.
45007  */
45008  if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
45009    needSyncPgno = pPg->pgno;
45010    assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
45011            pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
45012    assert( pPg->flags&PGHDR_DIRTY );
45013  }
45014
45015  /* If the cache contains a page with page-number pgno, remove it
45016  ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
45017  ** page pgno before the 'move' operation, it needs to be retained
45018  ** for the page moved there.
45019  */
45020  pPg->flags &= ~PGHDR_NEED_SYNC;
45021  pPgOld = pager_lookup(pPager, pgno);
45022  assert( !pPgOld || pPgOld->nRef==1 );
45023  if( pPgOld ){
45024    pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
45025    if( MEMDB ){
45026      /* Do not discard pages from an in-memory database since we might
45027      ** need to rollback later.  Just move the page out of the way. */
45028      sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
45029    }else{
45030      sqlite3PcacheDrop(pPgOld);
45031    }
45032  }
45033
45034  origPgno = pPg->pgno;
45035  sqlite3PcacheMove(pPg, pgno);
45036  sqlite3PcacheMakeDirty(pPg);
45037
45038  /* For an in-memory database, make sure the original page continues
45039  ** to exist, in case the transaction needs to roll back.  Use pPgOld
45040  ** as the original page since it has already been allocated.
45041  */
45042  if( MEMDB ){
45043    assert( pPgOld );
45044    sqlite3PcacheMove(pPgOld, origPgno);
45045    sqlite3PagerUnref(pPgOld);
45046  }
45047
45048  if( needSyncPgno ){
45049    /* If needSyncPgno is non-zero, then the journal file needs to be
45050    ** sync()ed before any data is written to database file page needSyncPgno.
45051    ** Currently, no such page exists in the page-cache and the
45052    ** "is journaled" bitvec flag has been set. This needs to be remedied by
45053    ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
45054    ** flag.
45055    **
45056    ** If the attempt to load the page into the page-cache fails, (due
45057    ** to a malloc() or IO failure), clear the bit in the pInJournal[]
45058    ** array. Otherwise, if the page is loaded and written again in
45059    ** this transaction, it may be written to the database file before
45060    ** it is synced into the journal file. This way, it may end up in
45061    ** the journal file twice, but that is not a problem.
45062    */
45063    PgHdr *pPgHdr;
45064    rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
45065    if( rc!=SQLITE_OK ){
45066      if( needSyncPgno<=pPager->dbOrigSize ){
45067        assert( pPager->pTmpSpace!=0 );
45068        sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
45069      }
45070      return rc;
45071    }
45072    pPgHdr->flags |= PGHDR_NEED_SYNC;
45073    sqlite3PcacheMakeDirty(pPgHdr);
45074    sqlite3PagerUnref(pPgHdr);
45075  }
45076
45077  return SQLITE_OK;
45078}
45079#endif
45080
45081/*
45082** Return a pointer to the data for the specified page.
45083*/
45084SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
45085  assert( pPg->nRef>0 || pPg->pPager->memDb );
45086  return pPg->pData;
45087}
45088
45089/*
45090** Return a pointer to the Pager.nExtra bytes of "extra" space
45091** allocated along with the specified page.
45092*/
45093SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
45094  return pPg->pExtra;
45095}
45096
45097/*
45098** Get/set the locking-mode for this pager. Parameter eMode must be one
45099** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
45100** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
45101** the locking-mode is set to the value specified.
45102**
45103** The returned value is either PAGER_LOCKINGMODE_NORMAL or
45104** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
45105** locking-mode.
45106*/
45107SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
45108  assert( eMode==PAGER_LOCKINGMODE_QUERY
45109            || eMode==PAGER_LOCKINGMODE_NORMAL
45110            || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
45111  assert( PAGER_LOCKINGMODE_QUERY<0 );
45112  assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
45113  assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
45114  if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
45115    pPager->exclusiveMode = (u8)eMode;
45116  }
45117  return (int)pPager->exclusiveMode;
45118}
45119
45120/*
45121** Set the journal-mode for this pager. Parameter eMode must be one of:
45122**
45123**    PAGER_JOURNALMODE_DELETE
45124**    PAGER_JOURNALMODE_TRUNCATE
45125**    PAGER_JOURNALMODE_PERSIST
45126**    PAGER_JOURNALMODE_OFF
45127**    PAGER_JOURNALMODE_MEMORY
45128**    PAGER_JOURNALMODE_WAL
45129**
45130** The journalmode is set to the value specified if the change is allowed.
45131** The change may be disallowed for the following reasons:
45132**
45133**   *  An in-memory database can only have its journal_mode set to _OFF
45134**      or _MEMORY.
45135**
45136**   *  Temporary databases cannot have _WAL journalmode.
45137**
45138** The returned indicate the current (possibly updated) journal-mode.
45139*/
45140SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
45141  u8 eOld = pPager->journalMode;    /* Prior journalmode */
45142
45143#ifdef SQLITE_DEBUG
45144  /* The print_pager_state() routine is intended to be used by the debugger
45145  ** only.  We invoke it once here to suppress a compiler warning. */
45146  print_pager_state(pPager);
45147#endif
45148
45149
45150  /* The eMode parameter is always valid */
45151  assert(      eMode==PAGER_JOURNALMODE_DELETE
45152            || eMode==PAGER_JOURNALMODE_TRUNCATE
45153            || eMode==PAGER_JOURNALMODE_PERSIST
45154            || eMode==PAGER_JOURNALMODE_OFF
45155            || eMode==PAGER_JOURNALMODE_WAL
45156            || eMode==PAGER_JOURNALMODE_MEMORY );
45157
45158  /* This routine is only called from the OP_JournalMode opcode, and
45159  ** the logic there will never allow a temporary file to be changed
45160  ** to WAL mode.
45161  */
45162  assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
45163
45164  /* Do allow the journalmode of an in-memory database to be set to
45165  ** anything other than MEMORY or OFF
45166  */
45167  if( MEMDB ){
45168    assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
45169    if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
45170      eMode = eOld;
45171    }
45172  }
45173
45174  if( eMode!=eOld ){
45175
45176    /* Change the journal mode. */
45177    assert( pPager->eState!=PAGER_ERROR );
45178    pPager->journalMode = (u8)eMode;
45179
45180    /* When transistioning from TRUNCATE or PERSIST to any other journal
45181    ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
45182    ** delete the journal file.
45183    */
45184    assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
45185    assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
45186    assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
45187    assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
45188    assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
45189    assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
45190
45191    assert( isOpen(pPager->fd) || pPager->exclusiveMode );
45192    if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
45193
45194      /* In this case we would like to delete the journal file. If it is
45195      ** not possible, then that is not a problem. Deleting the journal file
45196      ** here is an optimization only.
45197      **
45198      ** Before deleting the journal file, obtain a RESERVED lock on the
45199      ** database file. This ensures that the journal file is not deleted
45200      ** while it is in use by some other client.
45201      */
45202      sqlite3OsClose(pPager->jfd);
45203      if( pPager->eLock>=RESERVED_LOCK ){
45204        sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
45205      }else{
45206        int rc = SQLITE_OK;
45207        int state = pPager->eState;
45208        assert( state==PAGER_OPEN || state==PAGER_READER );
45209        if( state==PAGER_OPEN ){
45210          rc = sqlite3PagerSharedLock(pPager);
45211        }
45212        if( pPager->eState==PAGER_READER ){
45213          assert( rc==SQLITE_OK );
45214          rc = pagerLockDb(pPager, RESERVED_LOCK);
45215        }
45216        if( rc==SQLITE_OK ){
45217          sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
45218        }
45219        if( rc==SQLITE_OK && state==PAGER_READER ){
45220          pagerUnlockDb(pPager, SHARED_LOCK);
45221        }else if( state==PAGER_OPEN ){
45222          pager_unlock(pPager);
45223        }
45224        assert( state==pPager->eState );
45225      }
45226    }
45227  }
45228
45229  /* Return the new journal mode */
45230  return (int)pPager->journalMode;
45231}
45232
45233/*
45234** Return the current journal mode.
45235*/
45236SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
45237  return (int)pPager->journalMode;
45238}
45239
45240/*
45241** Return TRUE if the pager is in a state where it is OK to change the
45242** journalmode.  Journalmode changes can only happen when the database
45243** is unmodified.
45244*/
45245SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
45246  assert( assert_pager_state(pPager) );
45247  if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
45248  if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
45249  return 1;
45250}
45251
45252/*
45253** Get/set the size-limit used for persistent journal files.
45254**
45255** Setting the size limit to -1 means no limit is enforced.
45256** An attempt to set a limit smaller than -1 is a no-op.
45257*/
45258SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
45259  if( iLimit>=-1 ){
45260    pPager->journalSizeLimit = iLimit;
45261    sqlite3WalLimit(pPager->pWal, iLimit);
45262  }
45263  return pPager->journalSizeLimit;
45264}
45265
45266/*
45267** Return a pointer to the pPager->pBackup variable. The backup module
45268** in backup.c maintains the content of this variable. This module
45269** uses it opaquely as an argument to sqlite3BackupRestart() and
45270** sqlite3BackupUpdate() only.
45271*/
45272SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
45273  return &pPager->pBackup;
45274}
45275
45276#ifndef SQLITE_OMIT_VACUUM
45277/*
45278** Unless this is an in-memory or temporary database, clear the pager cache.
45279*/
45280SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
45281  if( !MEMDB && pPager->tempFile==0 ) pager_reset(pPager);
45282}
45283#endif
45284
45285#ifndef SQLITE_OMIT_WAL
45286/*
45287** This function is called when the user invokes "PRAGMA wal_checkpoint",
45288** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
45289** or wal_blocking_checkpoint() API functions.
45290**
45291** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
45292*/
45293SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
45294  int rc = SQLITE_OK;
45295  if( pPager->pWal ){
45296    rc = sqlite3WalCheckpoint(pPager->pWal, eMode,
45297        pPager->xBusyHandler, pPager->pBusyHandlerArg,
45298        pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
45299        pnLog, pnCkpt
45300    );
45301  }
45302  return rc;
45303}
45304
45305SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
45306  return sqlite3WalCallback(pPager->pWal);
45307}
45308
45309/*
45310** Return true if the underlying VFS for the given pager supports the
45311** primitives necessary for write-ahead logging.
45312*/
45313SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
45314  const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
45315  return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
45316}
45317
45318/*
45319** Attempt to take an exclusive lock on the database file. If a PENDING lock
45320** is obtained instead, immediately release it.
45321*/
45322static int pagerExclusiveLock(Pager *pPager){
45323  int rc;                         /* Return code */
45324
45325  assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
45326  rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
45327  if( rc!=SQLITE_OK ){
45328    /* If the attempt to grab the exclusive lock failed, release the
45329    ** pending lock that may have been obtained instead.  */
45330    pagerUnlockDb(pPager, SHARED_LOCK);
45331  }
45332
45333  return rc;
45334}
45335
45336/*
45337** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
45338** exclusive-locking mode when this function is called, take an EXCLUSIVE
45339** lock on the database file and use heap-memory to store the wal-index
45340** in. Otherwise, use the normal shared-memory.
45341*/
45342static int pagerOpenWal(Pager *pPager){
45343  int rc = SQLITE_OK;
45344
45345  assert( pPager->pWal==0 && pPager->tempFile==0 );
45346  assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
45347
45348  /* If the pager is already in exclusive-mode, the WAL module will use
45349  ** heap-memory for the wal-index instead of the VFS shared-memory
45350  ** implementation. Take the exclusive lock now, before opening the WAL
45351  ** file, to make sure this is safe.
45352  */
45353  if( pPager->exclusiveMode ){
45354    rc = pagerExclusiveLock(pPager);
45355  }
45356
45357  /* Open the connection to the log file. If this operation fails,
45358  ** (e.g. due to malloc() failure), return an error code.
45359  */
45360  if( rc==SQLITE_OK ){
45361    rc = sqlite3WalOpen(pPager->pVfs,
45362        pPager->fd, pPager->zWal, pPager->exclusiveMode,
45363        pPager->journalSizeLimit, &pPager->pWal
45364    );
45365  }
45366  pagerFixMaplimit(pPager);
45367
45368  return rc;
45369}
45370
45371
45372/*
45373** The caller must be holding a SHARED lock on the database file to call
45374** this function.
45375**
45376** If the pager passed as the first argument is open on a real database
45377** file (not a temp file or an in-memory database), and the WAL file
45378** is not already open, make an attempt to open it now. If successful,
45379** return SQLITE_OK. If an error occurs or the VFS used by the pager does
45380** not support the xShmXXX() methods, return an error code. *pbOpen is
45381** not modified in either case.
45382**
45383** If the pager is open on a temp-file (or in-memory database), or if
45384** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
45385** without doing anything.
45386*/
45387SQLITE_PRIVATE int sqlite3PagerOpenWal(
45388  Pager *pPager,                  /* Pager object */
45389  int *pbOpen                     /* OUT: Set to true if call is a no-op */
45390){
45391  int rc = SQLITE_OK;             /* Return code */
45392
45393  assert( assert_pager_state(pPager) );
45394  assert( pPager->eState==PAGER_OPEN   || pbOpen );
45395  assert( pPager->eState==PAGER_READER || !pbOpen );
45396  assert( pbOpen==0 || *pbOpen==0 );
45397  assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
45398
45399  if( !pPager->tempFile && !pPager->pWal ){
45400    if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
45401
45402    /* Close any rollback journal previously open */
45403    sqlite3OsClose(pPager->jfd);
45404
45405    rc = pagerOpenWal(pPager);
45406    if( rc==SQLITE_OK ){
45407      pPager->journalMode = PAGER_JOURNALMODE_WAL;
45408      pPager->eState = PAGER_OPEN;
45409    }
45410  }else{
45411    *pbOpen = 1;
45412  }
45413
45414  return rc;
45415}
45416
45417/*
45418** This function is called to close the connection to the log file prior
45419** to switching from WAL to rollback mode.
45420**
45421** Before closing the log file, this function attempts to take an
45422** EXCLUSIVE lock on the database file. If this cannot be obtained, an
45423** error (SQLITE_BUSY) is returned and the log connection is not closed.
45424** If successful, the EXCLUSIVE lock is not released before returning.
45425*/
45426SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
45427  int rc = SQLITE_OK;
45428
45429  assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
45430
45431  /* If the log file is not already open, but does exist in the file-system,
45432  ** it may need to be checkpointed before the connection can switch to
45433  ** rollback mode. Open it now so this can happen.
45434  */
45435  if( !pPager->pWal ){
45436    int logexists = 0;
45437    rc = pagerLockDb(pPager, SHARED_LOCK);
45438    if( rc==SQLITE_OK ){
45439      rc = sqlite3OsAccess(
45440          pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
45441      );
45442    }
45443    if( rc==SQLITE_OK && logexists ){
45444      rc = pagerOpenWal(pPager);
45445    }
45446  }
45447
45448  /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
45449  ** the database file, the log and log-summary files will be deleted.
45450  */
45451  if( rc==SQLITE_OK && pPager->pWal ){
45452    rc = pagerExclusiveLock(pPager);
45453    if( rc==SQLITE_OK ){
45454      rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
45455                           pPager->pageSize, (u8*)pPager->pTmpSpace);
45456      pPager->pWal = 0;
45457      pagerFixMaplimit(pPager);
45458    }
45459  }
45460  return rc;
45461}
45462
45463#endif /* !SQLITE_OMIT_WAL */
45464
45465#ifdef SQLITE_ENABLE_ZIPVFS
45466/*
45467** A read-lock must be held on the pager when this function is called. If
45468** the pager is in WAL mode and the WAL file currently contains one or more
45469** frames, return the size in bytes of the page images stored within the
45470** WAL frames. Otherwise, if this is not a WAL database or the WAL file
45471** is empty, return 0.
45472*/
45473SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
45474  assert( pPager->eState==PAGER_READER );
45475  return sqlite3WalFramesize(pPager->pWal);
45476}
45477#endif
45478
45479#ifdef SQLITE_HAS_CODEC
45480/*
45481** This function is called by the wal module when writing page content
45482** into the log file.
45483**
45484** This function returns a pointer to a buffer containing the encrypted
45485** page content. If a malloc fails, this function may return NULL.
45486*/
45487SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
45488  void *aData = 0;
45489  CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
45490  return aData;
45491}
45492#endif /* SQLITE_HAS_CODEC */
45493
45494#endif /* SQLITE_OMIT_DISKIO */
45495
45496/************** End of pager.c ***********************************************/
45497/************** Begin file wal.c *********************************************/
45498/*
45499** 2010 February 1
45500**
45501** The author disclaims copyright to this source code.  In place of
45502** a legal notice, here is a blessing:
45503**
45504**    May you do good and not evil.
45505**    May you find forgiveness for yourself and forgive others.
45506**    May you share freely, never taking more than you give.
45507**
45508*************************************************************************
45509**
45510** This file contains the implementation of a write-ahead log (WAL) used in
45511** "journal_mode=WAL" mode.
45512**
45513** WRITE-AHEAD LOG (WAL) FILE FORMAT
45514**
45515** A WAL file consists of a header followed by zero or more "frames".
45516** Each frame records the revised content of a single page from the
45517** database file.  All changes to the database are recorded by writing
45518** frames into the WAL.  Transactions commit when a frame is written that
45519** contains a commit marker.  A single WAL can and usually does record
45520** multiple transactions.  Periodically, the content of the WAL is
45521** transferred back into the database file in an operation called a
45522** "checkpoint".
45523**
45524** A single WAL file can be used multiple times.  In other words, the
45525** WAL can fill up with frames and then be checkpointed and then new
45526** frames can overwrite the old ones.  A WAL always grows from beginning
45527** toward the end.  Checksums and counters attached to each frame are
45528** used to determine which frames within the WAL are valid and which
45529** are leftovers from prior checkpoints.
45530**
45531** The WAL header is 32 bytes in size and consists of the following eight
45532** big-endian 32-bit unsigned integer values:
45533**
45534**     0: Magic number.  0x377f0682 or 0x377f0683
45535**     4: File format version.  Currently 3007000
45536**     8: Database page size.  Example: 1024
45537**    12: Checkpoint sequence number
45538**    16: Salt-1, random integer incremented with each checkpoint
45539**    20: Salt-2, a different random integer changing with each ckpt
45540**    24: Checksum-1 (first part of checksum for first 24 bytes of header).
45541**    28: Checksum-2 (second part of checksum for first 24 bytes of header).
45542**
45543** Immediately following the wal-header are zero or more frames. Each
45544** frame consists of a 24-byte frame-header followed by a <page-size> bytes
45545** of page data. The frame-header is six big-endian 32-bit unsigned
45546** integer values, as follows:
45547**
45548**     0: Page number.
45549**     4: For commit records, the size of the database image in pages
45550**        after the commit. For all other records, zero.
45551**     8: Salt-1 (copied from the header)
45552**    12: Salt-2 (copied from the header)
45553**    16: Checksum-1.
45554**    20: Checksum-2.
45555**
45556** A frame is considered valid if and only if the following conditions are
45557** true:
45558**
45559**    (1) The salt-1 and salt-2 values in the frame-header match
45560**        salt values in the wal-header
45561**
45562**    (2) The checksum values in the final 8 bytes of the frame-header
45563**        exactly match the checksum computed consecutively on the
45564**        WAL header and the first 8 bytes and the content of all frames
45565**        up to and including the current frame.
45566**
45567** The checksum is computed using 32-bit big-endian integers if the
45568** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
45569** is computed using little-endian if the magic number is 0x377f0682.
45570** The checksum values are always stored in the frame header in a
45571** big-endian format regardless of which byte order is used to compute
45572** the checksum.  The checksum is computed by interpreting the input as
45573** an even number of unsigned 32-bit integers: x[0] through x[N].  The
45574** algorithm used for the checksum is as follows:
45575**
45576**   for i from 0 to n-1 step 2:
45577**     s0 += x[i] + s1;
45578**     s1 += x[i+1] + s0;
45579**   endfor
45580**
45581** Note that s0 and s1 are both weighted checksums using fibonacci weights
45582** in reverse order (the largest fibonacci weight occurs on the first element
45583** of the sequence being summed.)  The s1 value spans all 32-bit
45584** terms of the sequence whereas s0 omits the final term.
45585**
45586** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
45587** WAL is transferred into the database, then the database is VFS.xSync-ed.
45588** The VFS.xSync operations serve as write barriers - all writes launched
45589** before the xSync must complete before any write that launches after the
45590** xSync begins.
45591**
45592** After each checkpoint, the salt-1 value is incremented and the salt-2
45593** value is randomized.  This prevents old and new frames in the WAL from
45594** being considered valid at the same time and being checkpointing together
45595** following a crash.
45596**
45597** READER ALGORITHM
45598**
45599** To read a page from the database (call it page number P), a reader
45600** first checks the WAL to see if it contains page P.  If so, then the
45601** last valid instance of page P that is a followed by a commit frame
45602** or is a commit frame itself becomes the value read.  If the WAL
45603** contains no copies of page P that are valid and which are a commit
45604** frame or are followed by a commit frame, then page P is read from
45605** the database file.
45606**
45607** To start a read transaction, the reader records the index of the last
45608** valid frame in the WAL.  The reader uses this recorded "mxFrame" value
45609** for all subsequent read operations.  New transactions can be appended
45610** to the WAL, but as long as the reader uses its original mxFrame value
45611** and ignores the newly appended content, it will see a consistent snapshot
45612** of the database from a single point in time.  This technique allows
45613** multiple concurrent readers to view different versions of the database
45614** content simultaneously.
45615**
45616** The reader algorithm in the previous paragraphs works correctly, but
45617** because frames for page P can appear anywhere within the WAL, the
45618** reader has to scan the entire WAL looking for page P frames.  If the
45619** WAL is large (multiple megabytes is typical) that scan can be slow,
45620** and read performance suffers.  To overcome this problem, a separate
45621** data structure called the wal-index is maintained to expedite the
45622** search for frames of a particular page.
45623**
45624** WAL-INDEX FORMAT
45625**
45626** Conceptually, the wal-index is shared memory, though VFS implementations
45627** might choose to implement the wal-index using a mmapped file.  Because
45628** the wal-index is shared memory, SQLite does not support journal_mode=WAL
45629** on a network filesystem.  All users of the database must be able to
45630** share memory.
45631**
45632** The wal-index is transient.  After a crash, the wal-index can (and should
45633** be) reconstructed from the original WAL file.  In fact, the VFS is required
45634** to either truncate or zero the header of the wal-index when the last
45635** connection to it closes.  Because the wal-index is transient, it can
45636** use an architecture-specific format; it does not have to be cross-platform.
45637** Hence, unlike the database and WAL file formats which store all values
45638** as big endian, the wal-index can store multi-byte values in the native
45639** byte order of the host computer.
45640**
45641** The purpose of the wal-index is to answer this question quickly:  Given
45642** a page number P and a maximum frame index M, return the index of the
45643** last frame in the wal before frame M for page P in the WAL, or return
45644** NULL if there are no frames for page P in the WAL prior to M.
45645**
45646** The wal-index consists of a header region, followed by an one or
45647** more index blocks.
45648**
45649** The wal-index header contains the total number of frames within the WAL
45650** in the mxFrame field.
45651**
45652** Each index block except for the first contains information on
45653** HASHTABLE_NPAGE frames. The first index block contains information on
45654** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
45655** HASHTABLE_NPAGE are selected so that together the wal-index header and
45656** first index block are the same size as all other index blocks in the
45657** wal-index.
45658**
45659** Each index block contains two sections, a page-mapping that contains the
45660** database page number associated with each wal frame, and a hash-table
45661** that allows readers to query an index block for a specific page number.
45662** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
45663** for the first index block) 32-bit page numbers. The first entry in the
45664** first index-block contains the database page number corresponding to the
45665** first frame in the WAL file. The first entry in the second index block
45666** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
45667** the log, and so on.
45668**
45669** The last index block in a wal-index usually contains less than the full
45670** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
45671** depending on the contents of the WAL file. This does not change the
45672** allocated size of the page-mapping array - the page-mapping array merely
45673** contains unused entries.
45674**
45675** Even without using the hash table, the last frame for page P
45676** can be found by scanning the page-mapping sections of each index block
45677** starting with the last index block and moving toward the first, and
45678** within each index block, starting at the end and moving toward the
45679** beginning.  The first entry that equals P corresponds to the frame
45680** holding the content for that page.
45681**
45682** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
45683** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
45684** hash table for each page number in the mapping section, so the hash
45685** table is never more than half full.  The expected number of collisions
45686** prior to finding a match is 1.  Each entry of the hash table is an
45687** 1-based index of an entry in the mapping section of the same
45688** index block.   Let K be the 1-based index of the largest entry in
45689** the mapping section.  (For index blocks other than the last, K will
45690** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
45691** K will be (mxFrame%HASHTABLE_NPAGE).)  Unused slots of the hash table
45692** contain a value of 0.
45693**
45694** To look for page P in the hash table, first compute a hash iKey on
45695** P as follows:
45696**
45697**      iKey = (P * 383) % HASHTABLE_NSLOT
45698**
45699** Then start scanning entries of the hash table, starting with iKey
45700** (wrapping around to the beginning when the end of the hash table is
45701** reached) until an unused hash slot is found. Let the first unused slot
45702** be at index iUnused.  (iUnused might be less than iKey if there was
45703** wrap-around.) Because the hash table is never more than half full,
45704** the search is guaranteed to eventually hit an unused entry.  Let
45705** iMax be the value between iKey and iUnused, closest to iUnused,
45706** where aHash[iMax]==P.  If there is no iMax entry (if there exists
45707** no hash slot such that aHash[i]==p) then page P is not in the
45708** current index block.  Otherwise the iMax-th mapping entry of the
45709** current index block corresponds to the last entry that references
45710** page P.
45711**
45712** A hash search begins with the last index block and moves toward the
45713** first index block, looking for entries corresponding to page P.  On
45714** average, only two or three slots in each index block need to be
45715** examined in order to either find the last entry for page P, or to
45716** establish that no such entry exists in the block.  Each index block
45717** holds over 4000 entries.  So two or three index blocks are sufficient
45718** to cover a typical 10 megabyte WAL file, assuming 1K pages.  8 or 10
45719** comparisons (on average) suffice to either locate a frame in the
45720** WAL or to establish that the frame does not exist in the WAL.  This
45721** is much faster than scanning the entire 10MB WAL.
45722**
45723** Note that entries are added in order of increasing K.  Hence, one
45724** reader might be using some value K0 and a second reader that started
45725** at a later time (after additional transactions were added to the WAL
45726** and to the wal-index) might be using a different value K1, where K1>K0.
45727** Both readers can use the same hash table and mapping section to get
45728** the correct result.  There may be entries in the hash table with
45729** K>K0 but to the first reader, those entries will appear to be unused
45730** slots in the hash table and so the first reader will get an answer as
45731** if no values greater than K0 had ever been inserted into the hash table
45732** in the first place - which is what reader one wants.  Meanwhile, the
45733** second reader using K1 will see additional values that were inserted
45734** later, which is exactly what reader two wants.
45735**
45736** When a rollback occurs, the value of K is decreased. Hash table entries
45737** that correspond to frames greater than the new K value are removed
45738** from the hash table at this point.
45739*/
45740#ifndef SQLITE_OMIT_WAL
45741
45742
45743/*
45744** Trace output macros
45745*/
45746#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
45747SQLITE_PRIVATE int sqlite3WalTrace = 0;
45748# define WALTRACE(X)  if(sqlite3WalTrace) sqlite3DebugPrintf X
45749#else
45750# define WALTRACE(X)
45751#endif
45752
45753/*
45754** The maximum (and only) versions of the wal and wal-index formats
45755** that may be interpreted by this version of SQLite.
45756**
45757** If a client begins recovering a WAL file and finds that (a) the checksum
45758** values in the wal-header are correct and (b) the version field is not
45759** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
45760**
45761** Similarly, if a client successfully reads a wal-index header (i.e. the
45762** checksum test is successful) and finds that the version field is not
45763** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
45764** returns SQLITE_CANTOPEN.
45765*/
45766#define WAL_MAX_VERSION      3007000
45767#define WALINDEX_MAX_VERSION 3007000
45768
45769/*
45770** Indices of various locking bytes.   WAL_NREADER is the number
45771** of available reader locks and should be at least 3.
45772*/
45773#define WAL_WRITE_LOCK         0
45774#define WAL_ALL_BUT_WRITE      1
45775#define WAL_CKPT_LOCK          1
45776#define WAL_RECOVER_LOCK       2
45777#define WAL_READ_LOCK(I)       (3+(I))
45778#define WAL_NREADER            (SQLITE_SHM_NLOCK-3)
45779
45780
45781/* Object declarations */
45782typedef struct WalIndexHdr WalIndexHdr;
45783typedef struct WalIterator WalIterator;
45784typedef struct WalCkptInfo WalCkptInfo;
45785
45786
45787/*
45788** The following object holds a copy of the wal-index header content.
45789**
45790** The actual header in the wal-index consists of two copies of this
45791** object.
45792**
45793** The szPage value can be any power of 2 between 512 and 32768, inclusive.
45794** Or it can be 1 to represent a 65536-byte page.  The latter case was
45795** added in 3.7.1 when support for 64K pages was added.
45796*/
45797struct WalIndexHdr {
45798  u32 iVersion;                   /* Wal-index version */
45799  u32 unused;                     /* Unused (padding) field */
45800  u32 iChange;                    /* Counter incremented each transaction */
45801  u8 isInit;                      /* 1 when initialized */
45802  u8 bigEndCksum;                 /* True if checksums in WAL are big-endian */
45803  u16 szPage;                     /* Database page size in bytes. 1==64K */
45804  u32 mxFrame;                    /* Index of last valid frame in the WAL */
45805  u32 nPage;                      /* Size of database in pages */
45806  u32 aFrameCksum[2];             /* Checksum of last frame in log */
45807  u32 aSalt[2];                   /* Two salt values copied from WAL header */
45808  u32 aCksum[2];                  /* Checksum over all prior fields */
45809};
45810
45811/*
45812** A copy of the following object occurs in the wal-index immediately
45813** following the second copy of the WalIndexHdr.  This object stores
45814** information used by checkpoint.
45815**
45816** nBackfill is the number of frames in the WAL that have been written
45817** back into the database. (We call the act of moving content from WAL to
45818** database "backfilling".)  The nBackfill number is never greater than
45819** WalIndexHdr.mxFrame.  nBackfill can only be increased by threads
45820** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
45821** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
45822** mxFrame back to zero when the WAL is reset.
45823**
45824** There is one entry in aReadMark[] for each reader lock.  If a reader
45825** holds read-lock K, then the value in aReadMark[K] is no greater than
45826** the mxFrame for that reader.  The value READMARK_NOT_USED (0xffffffff)
45827** for any aReadMark[] means that entry is unused.  aReadMark[0] is
45828** a special case; its value is never used and it exists as a place-holder
45829** to avoid having to offset aReadMark[] indexs by one.  Readers holding
45830** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
45831** directly from the database.
45832**
45833** The value of aReadMark[K] may only be changed by a thread that
45834** is holding an exclusive lock on WAL_READ_LOCK(K).  Thus, the value of
45835** aReadMark[K] cannot changed while there is a reader is using that mark
45836** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
45837**
45838** The checkpointer may only transfer frames from WAL to database where
45839** the frame numbers are less than or equal to every aReadMark[] that is
45840** in use (that is, every aReadMark[j] for which there is a corresponding
45841** WAL_READ_LOCK(j)).  New readers (usually) pick the aReadMark[] with the
45842** largest value and will increase an unused aReadMark[] to mxFrame if there
45843** is not already an aReadMark[] equal to mxFrame.  The exception to the
45844** previous sentence is when nBackfill equals mxFrame (meaning that everything
45845** in the WAL has been backfilled into the database) then new readers
45846** will choose aReadMark[0] which has value 0 and hence such reader will
45847** get all their all content directly from the database file and ignore
45848** the WAL.
45849**
45850** Writers normally append new frames to the end of the WAL.  However,
45851** if nBackfill equals mxFrame (meaning that all WAL content has been
45852** written back into the database) and if no readers are using the WAL
45853** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
45854** the writer will first "reset" the WAL back to the beginning and start
45855** writing new content beginning at frame 1.
45856**
45857** We assume that 32-bit loads are atomic and so no locks are needed in
45858** order to read from any aReadMark[] entries.
45859*/
45860struct WalCkptInfo {
45861  u32 nBackfill;                  /* Number of WAL frames backfilled into DB */
45862  u32 aReadMark[WAL_NREADER];     /* Reader marks */
45863};
45864#define READMARK_NOT_USED  0xffffffff
45865
45866
45867/* A block of WALINDEX_LOCK_RESERVED bytes beginning at
45868** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
45869** only support mandatory file-locks, we do not read or write data
45870** from the region of the file on which locks are applied.
45871*/
45872#define WALINDEX_LOCK_OFFSET   (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
45873#define WALINDEX_LOCK_RESERVED 16
45874#define WALINDEX_HDR_SIZE      (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
45875
45876/* Size of header before each frame in wal */
45877#define WAL_FRAME_HDRSIZE 24
45878
45879/* Size of write ahead log header, including checksum. */
45880/* #define WAL_HDRSIZE 24 */
45881#define WAL_HDRSIZE 32
45882
45883/* WAL magic value. Either this value, or the same value with the least
45884** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
45885** big-endian format in the first 4 bytes of a WAL file.
45886**
45887** If the LSB is set, then the checksums for each frame within the WAL
45888** file are calculated by treating all data as an array of 32-bit
45889** big-endian words. Otherwise, they are calculated by interpreting
45890** all data as 32-bit little-endian words.
45891*/
45892#define WAL_MAGIC 0x377f0682
45893
45894/*
45895** Return the offset of frame iFrame in the write-ahead log file,
45896** assuming a database page size of szPage bytes. The offset returned
45897** is to the start of the write-ahead log frame-header.
45898*/
45899#define walFrameOffset(iFrame, szPage) (                               \
45900  WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE)         \
45901)
45902
45903/*
45904** An open write-ahead log file is represented by an instance of the
45905** following object.
45906*/
45907struct Wal {
45908  sqlite3_vfs *pVfs;         /* The VFS used to create pDbFd */
45909  sqlite3_file *pDbFd;       /* File handle for the database file */
45910  sqlite3_file *pWalFd;      /* File handle for WAL file */
45911  u32 iCallback;             /* Value to pass to log callback (or 0) */
45912  i64 mxWalSize;             /* Truncate WAL to this size upon reset */
45913  int nWiData;               /* Size of array apWiData */
45914  int szFirstBlock;          /* Size of first block written to WAL file */
45915  volatile u32 **apWiData;   /* Pointer to wal-index content in memory */
45916  u32 szPage;                /* Database page size */
45917  i16 readLock;              /* Which read lock is being held.  -1 for none */
45918  u8 syncFlags;              /* Flags to use to sync header writes */
45919  u8 exclusiveMode;          /* Non-zero if connection is in exclusive mode */
45920  u8 writeLock;              /* True if in a write transaction */
45921  u8 ckptLock;               /* True if holding a checkpoint lock */
45922  u8 readOnly;               /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
45923  u8 truncateOnCommit;       /* True to truncate WAL file on commit */
45924  u8 syncHeader;             /* Fsync the WAL header if true */
45925  u8 padToSectorBoundary;    /* Pad transactions out to the next sector */
45926  WalIndexHdr hdr;           /* Wal-index header for current transaction */
45927  const char *zWalName;      /* Name of WAL file */
45928  u32 nCkpt;                 /* Checkpoint sequence counter in the wal-header */
45929#ifdef SQLITE_DEBUG
45930  u8 lockError;              /* True if a locking error has occurred */
45931#endif
45932};
45933
45934/*
45935** Candidate values for Wal.exclusiveMode.
45936*/
45937#define WAL_NORMAL_MODE     0
45938#define WAL_EXCLUSIVE_MODE  1
45939#define WAL_HEAPMEMORY_MODE 2
45940
45941/*
45942** Possible values for WAL.readOnly
45943*/
45944#define WAL_RDWR        0    /* Normal read/write connection */
45945#define WAL_RDONLY      1    /* The WAL file is readonly */
45946#define WAL_SHM_RDONLY  2    /* The SHM file is readonly */
45947
45948/*
45949** Each page of the wal-index mapping contains a hash-table made up of
45950** an array of HASHTABLE_NSLOT elements of the following type.
45951*/
45952typedef u16 ht_slot;
45953
45954/*
45955** This structure is used to implement an iterator that loops through
45956** all frames in the WAL in database page order. Where two or more frames
45957** correspond to the same database page, the iterator visits only the
45958** frame most recently written to the WAL (in other words, the frame with
45959** the largest index).
45960**
45961** The internals of this structure are only accessed by:
45962**
45963**   walIteratorInit() - Create a new iterator,
45964**   walIteratorNext() - Step an iterator,
45965**   walIteratorFree() - Free an iterator.
45966**
45967** This functionality is used by the checkpoint code (see walCheckpoint()).
45968*/
45969struct WalIterator {
45970  int iPrior;                     /* Last result returned from the iterator */
45971  int nSegment;                   /* Number of entries in aSegment[] */
45972  struct WalSegment {
45973    int iNext;                    /* Next slot in aIndex[] not yet returned */
45974    ht_slot *aIndex;              /* i0, i1, i2... such that aPgno[iN] ascend */
45975    u32 *aPgno;                   /* Array of page numbers. */
45976    int nEntry;                   /* Nr. of entries in aPgno[] and aIndex[] */
45977    int iZero;                    /* Frame number associated with aPgno[0] */
45978  } aSegment[1];                  /* One for every 32KB page in the wal-index */
45979};
45980
45981/*
45982** Define the parameters of the hash tables in the wal-index file. There
45983** is a hash-table following every HASHTABLE_NPAGE page numbers in the
45984** wal-index.
45985**
45986** Changing any of these constants will alter the wal-index format and
45987** create incompatibilities.
45988*/
45989#define HASHTABLE_NPAGE      4096                 /* Must be power of 2 */
45990#define HASHTABLE_HASH_1     383                  /* Should be prime */
45991#define HASHTABLE_NSLOT      (HASHTABLE_NPAGE*2)  /* Must be a power of 2 */
45992
45993/*
45994** The block of page numbers associated with the first hash-table in a
45995** wal-index is smaller than usual. This is so that there is a complete
45996** hash-table on each aligned 32KB page of the wal-index.
45997*/
45998#define HASHTABLE_NPAGE_ONE  (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
45999
46000/* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
46001#define WALINDEX_PGSZ   (                                         \
46002    sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
46003)
46004
46005/*
46006** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
46007** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
46008** numbered from zero.
46009**
46010** If this call is successful, *ppPage is set to point to the wal-index
46011** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
46012** then an SQLite error code is returned and *ppPage is set to 0.
46013*/
46014static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
46015  int rc = SQLITE_OK;
46016
46017  /* Enlarge the pWal->apWiData[] array if required */
46018  if( pWal->nWiData<=iPage ){
46019    int nByte = sizeof(u32*)*(iPage+1);
46020    volatile u32 **apNew;
46021    apNew = (volatile u32 **)sqlite3_realloc((void *)pWal->apWiData, nByte);
46022    if( !apNew ){
46023      *ppPage = 0;
46024      return SQLITE_NOMEM;
46025    }
46026    memset((void*)&apNew[pWal->nWiData], 0,
46027           sizeof(u32*)*(iPage+1-pWal->nWiData));
46028    pWal->apWiData = apNew;
46029    pWal->nWiData = iPage+1;
46030  }
46031
46032  /* Request a pointer to the required page from the VFS */
46033  if( pWal->apWiData[iPage]==0 ){
46034    if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
46035      pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
46036      if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM;
46037    }else{
46038      rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
46039          pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
46040      );
46041      if( rc==SQLITE_READONLY ){
46042        pWal->readOnly |= WAL_SHM_RDONLY;
46043        rc = SQLITE_OK;
46044      }
46045    }
46046  }
46047
46048  *ppPage = pWal->apWiData[iPage];
46049  assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
46050  return rc;
46051}
46052
46053/*
46054** Return a pointer to the WalCkptInfo structure in the wal-index.
46055*/
46056static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
46057  assert( pWal->nWiData>0 && pWal->apWiData[0] );
46058  return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
46059}
46060
46061/*
46062** Return a pointer to the WalIndexHdr structure in the wal-index.
46063*/
46064static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
46065  assert( pWal->nWiData>0 && pWal->apWiData[0] );
46066  return (volatile WalIndexHdr*)pWal->apWiData[0];
46067}
46068
46069/*
46070** The argument to this macro must be of type u32. On a little-endian
46071** architecture, it returns the u32 value that results from interpreting
46072** the 4 bytes as a big-endian value. On a big-endian architecture, it
46073** returns the value that would be produced by intepreting the 4 bytes
46074** of the input value as a little-endian integer.
46075*/
46076#define BYTESWAP32(x) ( \
46077    (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8)  \
46078  + (((x)&0x00FF0000)>>8)  + (((x)&0xFF000000)>>24) \
46079)
46080
46081/*
46082** Generate or extend an 8 byte checksum based on the data in
46083** array aByte[] and the initial values of aIn[0] and aIn[1] (or
46084** initial values of 0 and 0 if aIn==NULL).
46085**
46086** The checksum is written back into aOut[] before returning.
46087**
46088** nByte must be a positive multiple of 8.
46089*/
46090static void walChecksumBytes(
46091  int nativeCksum, /* True for native byte-order, false for non-native */
46092  u8 *a,           /* Content to be checksummed */
46093  int nByte,       /* Bytes of content in a[].  Must be a multiple of 8. */
46094  const u32 *aIn,  /* Initial checksum value input */
46095  u32 *aOut        /* OUT: Final checksum value output */
46096){
46097  u32 s1, s2;
46098  u32 *aData = (u32 *)a;
46099  u32 *aEnd = (u32 *)&a[nByte];
46100
46101  if( aIn ){
46102    s1 = aIn[0];
46103    s2 = aIn[1];
46104  }else{
46105    s1 = s2 = 0;
46106  }
46107
46108  assert( nByte>=8 );
46109  assert( (nByte&0x00000007)==0 );
46110
46111  if( nativeCksum ){
46112    do {
46113      s1 += *aData++ + s2;
46114      s2 += *aData++ + s1;
46115    }while( aData<aEnd );
46116  }else{
46117    do {
46118      s1 += BYTESWAP32(aData[0]) + s2;
46119      s2 += BYTESWAP32(aData[1]) + s1;
46120      aData += 2;
46121    }while( aData<aEnd );
46122  }
46123
46124  aOut[0] = s1;
46125  aOut[1] = s2;
46126}
46127
46128static void walShmBarrier(Wal *pWal){
46129  if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
46130    sqlite3OsShmBarrier(pWal->pDbFd);
46131  }
46132}
46133
46134/*
46135** Write the header information in pWal->hdr into the wal-index.
46136**
46137** The checksum on pWal->hdr is updated before it is written.
46138*/
46139static void walIndexWriteHdr(Wal *pWal){
46140  volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
46141  const int nCksum = offsetof(WalIndexHdr, aCksum);
46142
46143  assert( pWal->writeLock );
46144  pWal->hdr.isInit = 1;
46145  pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
46146  walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
46147  memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr));
46148  walShmBarrier(pWal);
46149  memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr));
46150}
46151
46152/*
46153** This function encodes a single frame header and writes it to a buffer
46154** supplied by the caller. A frame-header is made up of a series of
46155** 4-byte big-endian integers, as follows:
46156**
46157**     0: Page number.
46158**     4: For commit records, the size of the database image in pages
46159**        after the commit. For all other records, zero.
46160**     8: Salt-1 (copied from the wal-header)
46161**    12: Salt-2 (copied from the wal-header)
46162**    16: Checksum-1.
46163**    20: Checksum-2.
46164*/
46165static void walEncodeFrame(
46166  Wal *pWal,                      /* The write-ahead log */
46167  u32 iPage,                      /* Database page number for frame */
46168  u32 nTruncate,                  /* New db size (or 0 for non-commit frames) */
46169  u8 *aData,                      /* Pointer to page data */
46170  u8 *aFrame                      /* OUT: Write encoded frame here */
46171){
46172  int nativeCksum;                /* True for native byte-order checksums */
46173  u32 *aCksum = pWal->hdr.aFrameCksum;
46174  assert( WAL_FRAME_HDRSIZE==24 );
46175  sqlite3Put4byte(&aFrame[0], iPage);
46176  sqlite3Put4byte(&aFrame[4], nTruncate);
46177  memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
46178
46179  nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
46180  walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
46181  walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
46182
46183  sqlite3Put4byte(&aFrame[16], aCksum[0]);
46184  sqlite3Put4byte(&aFrame[20], aCksum[1]);
46185}
46186
46187/*
46188** Check to see if the frame with header in aFrame[] and content
46189** in aData[] is valid.  If it is a valid frame, fill *piPage and
46190** *pnTruncate and return true.  Return if the frame is not valid.
46191*/
46192static int walDecodeFrame(
46193  Wal *pWal,                      /* The write-ahead log */
46194  u32 *piPage,                    /* OUT: Database page number for frame */
46195  u32 *pnTruncate,                /* OUT: New db size (or 0 if not commit) */
46196  u8 *aData,                      /* Pointer to page data (for checksum) */
46197  u8 *aFrame                      /* Frame data */
46198){
46199  int nativeCksum;                /* True for native byte-order checksums */
46200  u32 *aCksum = pWal->hdr.aFrameCksum;
46201  u32 pgno;                       /* Page number of the frame */
46202  assert( WAL_FRAME_HDRSIZE==24 );
46203
46204  /* A frame is only valid if the salt values in the frame-header
46205  ** match the salt values in the wal-header.
46206  */
46207  if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
46208    return 0;
46209  }
46210
46211  /* A frame is only valid if the page number is creater than zero.
46212  */
46213  pgno = sqlite3Get4byte(&aFrame[0]);
46214  if( pgno==0 ){
46215    return 0;
46216  }
46217
46218  /* A frame is only valid if a checksum of the WAL header,
46219  ** all prior frams, the first 16 bytes of this frame-header,
46220  ** and the frame-data matches the checksum in the last 8
46221  ** bytes of this frame-header.
46222  */
46223  nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
46224  walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
46225  walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
46226  if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
46227   || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
46228  ){
46229    /* Checksum failed. */
46230    return 0;
46231  }
46232
46233  /* If we reach this point, the frame is valid.  Return the page number
46234  ** and the new database size.
46235  */
46236  *piPage = pgno;
46237  *pnTruncate = sqlite3Get4byte(&aFrame[4]);
46238  return 1;
46239}
46240
46241
46242#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
46243/*
46244** Names of locks.  This routine is used to provide debugging output and is not
46245** a part of an ordinary build.
46246*/
46247static const char *walLockName(int lockIdx){
46248  if( lockIdx==WAL_WRITE_LOCK ){
46249    return "WRITE-LOCK";
46250  }else if( lockIdx==WAL_CKPT_LOCK ){
46251    return "CKPT-LOCK";
46252  }else if( lockIdx==WAL_RECOVER_LOCK ){
46253    return "RECOVER-LOCK";
46254  }else{
46255    static char zName[15];
46256    sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
46257                     lockIdx-WAL_READ_LOCK(0));
46258    return zName;
46259  }
46260}
46261#endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
46262
46263
46264/*
46265** Set or release locks on the WAL.  Locks are either shared or exclusive.
46266** A lock cannot be moved directly between shared and exclusive - it must go
46267** through the unlocked state first.
46268**
46269** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
46270*/
46271static int walLockShared(Wal *pWal, int lockIdx){
46272  int rc;
46273  if( pWal->exclusiveMode ) return SQLITE_OK;
46274  rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
46275                        SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
46276  WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
46277            walLockName(lockIdx), rc ? "failed" : "ok"));
46278  VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
46279  return rc;
46280}
46281static void walUnlockShared(Wal *pWal, int lockIdx){
46282  if( pWal->exclusiveMode ) return;
46283  (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
46284                         SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
46285  WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
46286}
46287static int walLockExclusive(Wal *pWal, int lockIdx, int n){
46288  int rc;
46289  if( pWal->exclusiveMode ) return SQLITE_OK;
46290  rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
46291                        SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
46292  WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
46293            walLockName(lockIdx), n, rc ? "failed" : "ok"));
46294  VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
46295  return rc;
46296}
46297static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
46298  if( pWal->exclusiveMode ) return;
46299  (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
46300                         SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
46301  WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
46302             walLockName(lockIdx), n));
46303}
46304
46305/*
46306** Compute a hash on a page number.  The resulting hash value must land
46307** between 0 and (HASHTABLE_NSLOT-1).  The walHashNext() function advances
46308** the hash to the next value in the event of a collision.
46309*/
46310static int walHash(u32 iPage){
46311  assert( iPage>0 );
46312  assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
46313  return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
46314}
46315static int walNextHash(int iPriorHash){
46316  return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
46317}
46318
46319/*
46320** Return pointers to the hash table and page number array stored on
46321** page iHash of the wal-index. The wal-index is broken into 32KB pages
46322** numbered starting from 0.
46323**
46324** Set output variable *paHash to point to the start of the hash table
46325** in the wal-index file. Set *piZero to one less than the frame
46326** number of the first frame indexed by this hash table. If a
46327** slot in the hash table is set to N, it refers to frame number
46328** (*piZero+N) in the log.
46329**
46330** Finally, set *paPgno so that *paPgno[1] is the page number of the
46331** first frame indexed by the hash table, frame (*piZero+1).
46332*/
46333static int walHashGet(
46334  Wal *pWal,                      /* WAL handle */
46335  int iHash,                      /* Find the iHash'th table */
46336  volatile ht_slot **paHash,      /* OUT: Pointer to hash index */
46337  volatile u32 **paPgno,          /* OUT: Pointer to page number array */
46338  u32 *piZero                     /* OUT: Frame associated with *paPgno[0] */
46339){
46340  int rc;                         /* Return code */
46341  volatile u32 *aPgno;
46342
46343  rc = walIndexPage(pWal, iHash, &aPgno);
46344  assert( rc==SQLITE_OK || iHash>0 );
46345
46346  if( rc==SQLITE_OK ){
46347    u32 iZero;
46348    volatile ht_slot *aHash;
46349
46350    aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
46351    if( iHash==0 ){
46352      aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
46353      iZero = 0;
46354    }else{
46355      iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
46356    }
46357
46358    *paPgno = &aPgno[-1];
46359    *paHash = aHash;
46360    *piZero = iZero;
46361  }
46362  return rc;
46363}
46364
46365/*
46366** Return the number of the wal-index page that contains the hash-table
46367** and page-number array that contain entries corresponding to WAL frame
46368** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
46369** are numbered starting from 0.
46370*/
46371static int walFramePage(u32 iFrame){
46372  int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
46373  assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
46374       && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
46375       && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
46376       && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
46377       && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
46378  );
46379  return iHash;
46380}
46381
46382/*
46383** Return the page number associated with frame iFrame in this WAL.
46384*/
46385static u32 walFramePgno(Wal *pWal, u32 iFrame){
46386  int iHash = walFramePage(iFrame);
46387  if( iHash==0 ){
46388    return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
46389  }
46390  return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
46391}
46392
46393/*
46394** Remove entries from the hash table that point to WAL slots greater
46395** than pWal->hdr.mxFrame.
46396**
46397** This function is called whenever pWal->hdr.mxFrame is decreased due
46398** to a rollback or savepoint.
46399**
46400** At most only the hash table containing pWal->hdr.mxFrame needs to be
46401** updated.  Any later hash tables will be automatically cleared when
46402** pWal->hdr.mxFrame advances to the point where those hash tables are
46403** actually needed.
46404*/
46405static void walCleanupHash(Wal *pWal){
46406  volatile ht_slot *aHash = 0;    /* Pointer to hash table to clear */
46407  volatile u32 *aPgno = 0;        /* Page number array for hash table */
46408  u32 iZero = 0;                  /* frame == (aHash[x]+iZero) */
46409  int iLimit = 0;                 /* Zero values greater than this */
46410  int nByte;                      /* Number of bytes to zero in aPgno[] */
46411  int i;                          /* Used to iterate through aHash[] */
46412
46413  assert( pWal->writeLock );
46414  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
46415  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
46416  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
46417
46418  if( pWal->hdr.mxFrame==0 ) return;
46419
46420  /* Obtain pointers to the hash-table and page-number array containing
46421  ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
46422  ** that the page said hash-table and array reside on is already mapped.
46423  */
46424  assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
46425  assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
46426  walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
46427
46428  /* Zero all hash-table entries that correspond to frame numbers greater
46429  ** than pWal->hdr.mxFrame.
46430  */
46431  iLimit = pWal->hdr.mxFrame - iZero;
46432  assert( iLimit>0 );
46433  for(i=0; i<HASHTABLE_NSLOT; i++){
46434    if( aHash[i]>iLimit ){
46435      aHash[i] = 0;
46436    }
46437  }
46438
46439  /* Zero the entries in the aPgno array that correspond to frames with
46440  ** frame numbers greater than pWal->hdr.mxFrame.
46441  */
46442  nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
46443  memset((void *)&aPgno[iLimit+1], 0, nByte);
46444
46445#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
46446  /* Verify that the every entry in the mapping region is still reachable
46447  ** via the hash table even after the cleanup.
46448  */
46449  if( iLimit ){
46450    int i;           /* Loop counter */
46451    int iKey;        /* Hash key */
46452    for(i=1; i<=iLimit; i++){
46453      for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
46454        if( aHash[iKey]==i ) break;
46455      }
46456      assert( aHash[iKey]==i );
46457    }
46458  }
46459#endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
46460}
46461
46462
46463/*
46464** Set an entry in the wal-index that will map database page number
46465** pPage into WAL frame iFrame.
46466*/
46467static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
46468  int rc;                         /* Return code */
46469  u32 iZero = 0;                  /* One less than frame number of aPgno[1] */
46470  volatile u32 *aPgno = 0;        /* Page number array */
46471  volatile ht_slot *aHash = 0;    /* Hash table */
46472
46473  rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
46474
46475  /* Assuming the wal-index file was successfully mapped, populate the
46476  ** page number array and hash table entry.
46477  */
46478  if( rc==SQLITE_OK ){
46479    int iKey;                     /* Hash table key */
46480    int idx;                      /* Value to write to hash-table slot */
46481    int nCollide;                 /* Number of hash collisions */
46482
46483    idx = iFrame - iZero;
46484    assert( idx <= HASHTABLE_NSLOT/2 + 1 );
46485
46486    /* If this is the first entry to be added to this hash-table, zero the
46487    ** entire hash table and aPgno[] array before proceding.
46488    */
46489    if( idx==1 ){
46490      int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
46491      memset((void*)&aPgno[1], 0, nByte);
46492    }
46493
46494    /* If the entry in aPgno[] is already set, then the previous writer
46495    ** must have exited unexpectedly in the middle of a transaction (after
46496    ** writing one or more dirty pages to the WAL to free up memory).
46497    ** Remove the remnants of that writers uncommitted transaction from
46498    ** the hash-table before writing any new entries.
46499    */
46500    if( aPgno[idx] ){
46501      walCleanupHash(pWal);
46502      assert( !aPgno[idx] );
46503    }
46504
46505    /* Write the aPgno[] array entry and the hash-table slot. */
46506    nCollide = idx;
46507    for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
46508      if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
46509    }
46510    aPgno[idx] = iPage;
46511    aHash[iKey] = (ht_slot)idx;
46512
46513#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
46514    /* Verify that the number of entries in the hash table exactly equals
46515    ** the number of entries in the mapping region.
46516    */
46517    {
46518      int i;           /* Loop counter */
46519      int nEntry = 0;  /* Number of entries in the hash table */
46520      for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
46521      assert( nEntry==idx );
46522    }
46523
46524    /* Verify that the every entry in the mapping region is reachable
46525    ** via the hash table.  This turns out to be a really, really expensive
46526    ** thing to check, so only do this occasionally - not on every
46527    ** iteration.
46528    */
46529    if( (idx&0x3ff)==0 ){
46530      int i;           /* Loop counter */
46531      for(i=1; i<=idx; i++){
46532        for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
46533          if( aHash[iKey]==i ) break;
46534        }
46535        assert( aHash[iKey]==i );
46536      }
46537    }
46538#endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
46539  }
46540
46541
46542  return rc;
46543}
46544
46545
46546/*
46547** Recover the wal-index by reading the write-ahead log file.
46548**
46549** This routine first tries to establish an exclusive lock on the
46550** wal-index to prevent other threads/processes from doing anything
46551** with the WAL or wal-index while recovery is running.  The
46552** WAL_RECOVER_LOCK is also held so that other threads will know
46553** that this thread is running recovery.  If unable to establish
46554** the necessary locks, this routine returns SQLITE_BUSY.
46555*/
46556static int walIndexRecover(Wal *pWal){
46557  int rc;                         /* Return Code */
46558  i64 nSize;                      /* Size of log file */
46559  u32 aFrameCksum[2] = {0, 0};
46560  int iLock;                      /* Lock offset to lock for checkpoint */
46561  int nLock;                      /* Number of locks to hold */
46562
46563  /* Obtain an exclusive lock on all byte in the locking range not already
46564  ** locked by the caller. The caller is guaranteed to have locked the
46565  ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
46566  ** If successful, the same bytes that are locked here are unlocked before
46567  ** this function returns.
46568  */
46569  assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
46570  assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
46571  assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
46572  assert( pWal->writeLock );
46573  iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
46574  nLock = SQLITE_SHM_NLOCK - iLock;
46575  rc = walLockExclusive(pWal, iLock, nLock);
46576  if( rc ){
46577    return rc;
46578  }
46579  WALTRACE(("WAL%p: recovery begin...\n", pWal));
46580
46581  memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
46582
46583  rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
46584  if( rc!=SQLITE_OK ){
46585    goto recovery_error;
46586  }
46587
46588  if( nSize>WAL_HDRSIZE ){
46589    u8 aBuf[WAL_HDRSIZE];         /* Buffer to load WAL header into */
46590    u8 *aFrame = 0;               /* Malloc'd buffer to load entire frame */
46591    int szFrame;                  /* Number of bytes in buffer aFrame[] */
46592    u8 *aData;                    /* Pointer to data part of aFrame buffer */
46593    int iFrame;                   /* Index of last frame read */
46594    i64 iOffset;                  /* Next offset to read from log file */
46595    int szPage;                   /* Page size according to the log */
46596    u32 magic;                    /* Magic value read from WAL header */
46597    u32 version;                  /* Magic value read from WAL header */
46598    int isValid;                  /* True if this frame is valid */
46599
46600    /* Read in the WAL header. */
46601    rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
46602    if( rc!=SQLITE_OK ){
46603      goto recovery_error;
46604    }
46605
46606    /* If the database page size is not a power of two, or is greater than
46607    ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
46608    ** data. Similarly, if the 'magic' value is invalid, ignore the whole
46609    ** WAL file.
46610    */
46611    magic = sqlite3Get4byte(&aBuf[0]);
46612    szPage = sqlite3Get4byte(&aBuf[8]);
46613    if( (magic&0xFFFFFFFE)!=WAL_MAGIC
46614     || szPage&(szPage-1)
46615     || szPage>SQLITE_MAX_PAGE_SIZE
46616     || szPage<512
46617    ){
46618      goto finished;
46619    }
46620    pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
46621    pWal->szPage = szPage;
46622    pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
46623    memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
46624
46625    /* Verify that the WAL header checksum is correct */
46626    walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
46627        aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
46628    );
46629    if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
46630     || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
46631    ){
46632      goto finished;
46633    }
46634
46635    /* Verify that the version number on the WAL format is one that
46636    ** are able to understand */
46637    version = sqlite3Get4byte(&aBuf[4]);
46638    if( version!=WAL_MAX_VERSION ){
46639      rc = SQLITE_CANTOPEN_BKPT;
46640      goto finished;
46641    }
46642
46643    /* Malloc a buffer to read frames into. */
46644    szFrame = szPage + WAL_FRAME_HDRSIZE;
46645    aFrame = (u8 *)sqlite3_malloc(szFrame);
46646    if( !aFrame ){
46647      rc = SQLITE_NOMEM;
46648      goto recovery_error;
46649    }
46650    aData = &aFrame[WAL_FRAME_HDRSIZE];
46651
46652    /* Read all frames from the log file. */
46653    iFrame = 0;
46654    for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
46655      u32 pgno;                   /* Database page number for frame */
46656      u32 nTruncate;              /* dbsize field from frame header */
46657
46658      /* Read and decode the next log frame. */
46659      iFrame++;
46660      rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
46661      if( rc!=SQLITE_OK ) break;
46662      isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
46663      if( !isValid ) break;
46664      rc = walIndexAppend(pWal, iFrame, pgno);
46665      if( rc!=SQLITE_OK ) break;
46666
46667      /* If nTruncate is non-zero, this is a commit record. */
46668      if( nTruncate ){
46669        pWal->hdr.mxFrame = iFrame;
46670        pWal->hdr.nPage = nTruncate;
46671        pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
46672        testcase( szPage<=32768 );
46673        testcase( szPage>=65536 );
46674        aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
46675        aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
46676      }
46677    }
46678
46679    sqlite3_free(aFrame);
46680  }
46681
46682finished:
46683  if( rc==SQLITE_OK ){
46684    volatile WalCkptInfo *pInfo;
46685    int i;
46686    pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
46687    pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
46688    walIndexWriteHdr(pWal);
46689
46690    /* Reset the checkpoint-header. This is safe because this thread is
46691    ** currently holding locks that exclude all other readers, writers and
46692    ** checkpointers.
46693    */
46694    pInfo = walCkptInfo(pWal);
46695    pInfo->nBackfill = 0;
46696    pInfo->aReadMark[0] = 0;
46697    for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
46698    if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
46699
46700    /* If more than one frame was recovered from the log file, report an
46701    ** event via sqlite3_log(). This is to help with identifying performance
46702    ** problems caused by applications routinely shutting down without
46703    ** checkpointing the log file.
46704    */
46705    if( pWal->hdr.nPage ){
46706      sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
46707          "recovered %d frames from WAL file %s",
46708          pWal->hdr.mxFrame, pWal->zWalName
46709      );
46710    }
46711  }
46712
46713recovery_error:
46714  WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
46715  walUnlockExclusive(pWal, iLock, nLock);
46716  return rc;
46717}
46718
46719/*
46720** Close an open wal-index.
46721*/
46722static void walIndexClose(Wal *pWal, int isDelete){
46723  if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
46724    int i;
46725    for(i=0; i<pWal->nWiData; i++){
46726      sqlite3_free((void *)pWal->apWiData[i]);
46727      pWal->apWiData[i] = 0;
46728    }
46729  }else{
46730    sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
46731  }
46732}
46733
46734/*
46735** Open a connection to the WAL file zWalName. The database file must
46736** already be opened on connection pDbFd. The buffer that zWalName points
46737** to must remain valid for the lifetime of the returned Wal* handle.
46738**
46739** A SHARED lock should be held on the database file when this function
46740** is called. The purpose of this SHARED lock is to prevent any other
46741** client from unlinking the WAL or wal-index file. If another process
46742** were to do this just after this client opened one of these files, the
46743** system would be badly broken.
46744**
46745** If the log file is successfully opened, SQLITE_OK is returned and
46746** *ppWal is set to point to a new WAL handle. If an error occurs,
46747** an SQLite error code is returned and *ppWal is left unmodified.
46748*/
46749SQLITE_PRIVATE int sqlite3WalOpen(
46750  sqlite3_vfs *pVfs,              /* vfs module to open wal and wal-index */
46751  sqlite3_file *pDbFd,            /* The open database file */
46752  const char *zWalName,           /* Name of the WAL file */
46753  int bNoShm,                     /* True to run in heap-memory mode */
46754  i64 mxWalSize,                  /* Truncate WAL to this size on reset */
46755  Wal **ppWal                     /* OUT: Allocated Wal handle */
46756){
46757  int rc;                         /* Return Code */
46758  Wal *pRet;                      /* Object to allocate and return */
46759  int flags;                      /* Flags passed to OsOpen() */
46760
46761  assert( zWalName && zWalName[0] );
46762  assert( pDbFd );
46763
46764  /* In the amalgamation, the os_unix.c and os_win.c source files come before
46765  ** this source file.  Verify that the #defines of the locking byte offsets
46766  ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
46767  */
46768#ifdef WIN_SHM_BASE
46769  assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
46770#endif
46771#ifdef UNIX_SHM_BASE
46772  assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
46773#endif
46774
46775
46776  /* Allocate an instance of struct Wal to return. */
46777  *ppWal = 0;
46778  pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
46779  if( !pRet ){
46780    return SQLITE_NOMEM;
46781  }
46782
46783  pRet->pVfs = pVfs;
46784  pRet->pWalFd = (sqlite3_file *)&pRet[1];
46785  pRet->pDbFd = pDbFd;
46786  pRet->readLock = -1;
46787  pRet->mxWalSize = mxWalSize;
46788  pRet->zWalName = zWalName;
46789  pRet->syncHeader = 1;
46790  pRet->padToSectorBoundary = 1;
46791  pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
46792
46793  /* Open file handle on the write-ahead log file. */
46794  flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
46795  rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
46796  if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
46797    pRet->readOnly = WAL_RDONLY;
46798  }
46799
46800  if( rc!=SQLITE_OK ){
46801    walIndexClose(pRet, 0);
46802    sqlite3OsClose(pRet->pWalFd);
46803    sqlite3_free(pRet);
46804  }else{
46805    int iDC = sqlite3OsDeviceCharacteristics(pRet->pWalFd);
46806    if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
46807    if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
46808      pRet->padToSectorBoundary = 0;
46809    }
46810    *ppWal = pRet;
46811    WALTRACE(("WAL%d: opened\n", pRet));
46812  }
46813  return rc;
46814}
46815
46816/*
46817** Change the size to which the WAL file is trucated on each reset.
46818*/
46819SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
46820  if( pWal ) pWal->mxWalSize = iLimit;
46821}
46822
46823/*
46824** Find the smallest page number out of all pages held in the WAL that
46825** has not been returned by any prior invocation of this method on the
46826** same WalIterator object.   Write into *piFrame the frame index where
46827** that page was last written into the WAL.  Write into *piPage the page
46828** number.
46829**
46830** Return 0 on success.  If there are no pages in the WAL with a page
46831** number larger than *piPage, then return 1.
46832*/
46833static int walIteratorNext(
46834  WalIterator *p,               /* Iterator */
46835  u32 *piPage,                  /* OUT: The page number of the next page */
46836  u32 *piFrame                  /* OUT: Wal frame index of next page */
46837){
46838  u32 iMin;                     /* Result pgno must be greater than iMin */
46839  u32 iRet = 0xFFFFFFFF;        /* 0xffffffff is never a valid page number */
46840  int i;                        /* For looping through segments */
46841
46842  iMin = p->iPrior;
46843  assert( iMin<0xffffffff );
46844  for(i=p->nSegment-1; i>=0; i--){
46845    struct WalSegment *pSegment = &p->aSegment[i];
46846    while( pSegment->iNext<pSegment->nEntry ){
46847      u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
46848      if( iPg>iMin ){
46849        if( iPg<iRet ){
46850          iRet = iPg;
46851          *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
46852        }
46853        break;
46854      }
46855      pSegment->iNext++;
46856    }
46857  }
46858
46859  *piPage = p->iPrior = iRet;
46860  return (iRet==0xFFFFFFFF);
46861}
46862
46863/*
46864** This function merges two sorted lists into a single sorted list.
46865**
46866** aLeft[] and aRight[] are arrays of indices.  The sort key is
46867** aContent[aLeft[]] and aContent[aRight[]].  Upon entry, the following
46868** is guaranteed for all J<K:
46869**
46870**        aContent[aLeft[J]] < aContent[aLeft[K]]
46871**        aContent[aRight[J]] < aContent[aRight[K]]
46872**
46873** This routine overwrites aRight[] with a new (probably longer) sequence
46874** of indices such that the aRight[] contains every index that appears in
46875** either aLeft[] or the old aRight[] and such that the second condition
46876** above is still met.
46877**
46878** The aContent[aLeft[X]] values will be unique for all X.  And the
46879** aContent[aRight[X]] values will be unique too.  But there might be
46880** one or more combinations of X and Y such that
46881**
46882**      aLeft[X]!=aRight[Y]  &&  aContent[aLeft[X]] == aContent[aRight[Y]]
46883**
46884** When that happens, omit the aLeft[X] and use the aRight[Y] index.
46885*/
46886static void walMerge(
46887  const u32 *aContent,            /* Pages in wal - keys for the sort */
46888  ht_slot *aLeft,                 /* IN: Left hand input list */
46889  int nLeft,                      /* IN: Elements in array *paLeft */
46890  ht_slot **paRight,              /* IN/OUT: Right hand input list */
46891  int *pnRight,                   /* IN/OUT: Elements in *paRight */
46892  ht_slot *aTmp                   /* Temporary buffer */
46893){
46894  int iLeft = 0;                  /* Current index in aLeft */
46895  int iRight = 0;                 /* Current index in aRight */
46896  int iOut = 0;                   /* Current index in output buffer */
46897  int nRight = *pnRight;
46898  ht_slot *aRight = *paRight;
46899
46900  assert( nLeft>0 && nRight>0 );
46901  while( iRight<nRight || iLeft<nLeft ){
46902    ht_slot logpage;
46903    Pgno dbpage;
46904
46905    if( (iLeft<nLeft)
46906     && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
46907    ){
46908      logpage = aLeft[iLeft++];
46909    }else{
46910      logpage = aRight[iRight++];
46911    }
46912    dbpage = aContent[logpage];
46913
46914    aTmp[iOut++] = logpage;
46915    if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
46916
46917    assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
46918    assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
46919  }
46920
46921  *paRight = aLeft;
46922  *pnRight = iOut;
46923  memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
46924}
46925
46926/*
46927** Sort the elements in list aList using aContent[] as the sort key.
46928** Remove elements with duplicate keys, preferring to keep the
46929** larger aList[] values.
46930**
46931** The aList[] entries are indices into aContent[].  The values in
46932** aList[] are to be sorted so that for all J<K:
46933**
46934**      aContent[aList[J]] < aContent[aList[K]]
46935**
46936** For any X and Y such that
46937**
46938**      aContent[aList[X]] == aContent[aList[Y]]
46939**
46940** Keep the larger of the two values aList[X] and aList[Y] and discard
46941** the smaller.
46942*/
46943static void walMergesort(
46944  const u32 *aContent,            /* Pages in wal */
46945  ht_slot *aBuffer,               /* Buffer of at least *pnList items to use */
46946  ht_slot *aList,                 /* IN/OUT: List to sort */
46947  int *pnList                     /* IN/OUT: Number of elements in aList[] */
46948){
46949  struct Sublist {
46950    int nList;                    /* Number of elements in aList */
46951    ht_slot *aList;               /* Pointer to sub-list content */
46952  };
46953
46954  const int nList = *pnList;      /* Size of input list */
46955  int nMerge = 0;                 /* Number of elements in list aMerge */
46956  ht_slot *aMerge = 0;            /* List to be merged */
46957  int iList;                      /* Index into input list */
46958  int iSub = 0;                   /* Index into aSub array */
46959  struct Sublist aSub[13];        /* Array of sub-lists */
46960
46961  memset(aSub, 0, sizeof(aSub));
46962  assert( nList<=HASHTABLE_NPAGE && nList>0 );
46963  assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
46964
46965  for(iList=0; iList<nList; iList++){
46966    nMerge = 1;
46967    aMerge = &aList[iList];
46968    for(iSub=0; iList & (1<<iSub); iSub++){
46969      struct Sublist *p = &aSub[iSub];
46970      assert( p->aList && p->nList<=(1<<iSub) );
46971      assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
46972      walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
46973    }
46974    aSub[iSub].aList = aMerge;
46975    aSub[iSub].nList = nMerge;
46976  }
46977
46978  for(iSub++; iSub<ArraySize(aSub); iSub++){
46979    if( nList & (1<<iSub) ){
46980      struct Sublist *p = &aSub[iSub];
46981      assert( p->nList<=(1<<iSub) );
46982      assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
46983      walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
46984    }
46985  }
46986  assert( aMerge==aList );
46987  *pnList = nMerge;
46988
46989#ifdef SQLITE_DEBUG
46990  {
46991    int i;
46992    for(i=1; i<*pnList; i++){
46993      assert( aContent[aList[i]] > aContent[aList[i-1]] );
46994    }
46995  }
46996#endif
46997}
46998
46999/*
47000** Free an iterator allocated by walIteratorInit().
47001*/
47002static void walIteratorFree(WalIterator *p){
47003  sqlite3ScratchFree(p);
47004}
47005
47006/*
47007** Construct a WalInterator object that can be used to loop over all
47008** pages in the WAL in ascending order. The caller must hold the checkpoint
47009** lock.
47010**
47011** On success, make *pp point to the newly allocated WalInterator object
47012** return SQLITE_OK. Otherwise, return an error code. If this routine
47013** returns an error, the value of *pp is undefined.
47014**
47015** The calling routine should invoke walIteratorFree() to destroy the
47016** WalIterator object when it has finished with it.
47017*/
47018static int walIteratorInit(Wal *pWal, WalIterator **pp){
47019  WalIterator *p;                 /* Return value */
47020  int nSegment;                   /* Number of segments to merge */
47021  u32 iLast;                      /* Last frame in log */
47022  int nByte;                      /* Number of bytes to allocate */
47023  int i;                          /* Iterator variable */
47024  ht_slot *aTmp;                  /* Temp space used by merge-sort */
47025  int rc = SQLITE_OK;             /* Return Code */
47026
47027  /* This routine only runs while holding the checkpoint lock. And
47028  ** it only runs if there is actually content in the log (mxFrame>0).
47029  */
47030  assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
47031  iLast = pWal->hdr.mxFrame;
47032
47033  /* Allocate space for the WalIterator object. */
47034  nSegment = walFramePage(iLast) + 1;
47035  nByte = sizeof(WalIterator)
47036        + (nSegment-1)*sizeof(struct WalSegment)
47037        + iLast*sizeof(ht_slot);
47038  p = (WalIterator *)sqlite3ScratchMalloc(nByte);
47039  if( !p ){
47040    return SQLITE_NOMEM;
47041  }
47042  memset(p, 0, nByte);
47043  p->nSegment = nSegment;
47044
47045  /* Allocate temporary space used by the merge-sort routine. This block
47046  ** of memory will be freed before this function returns.
47047  */
47048  aTmp = (ht_slot *)sqlite3ScratchMalloc(
47049      sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
47050  );
47051  if( !aTmp ){
47052    rc = SQLITE_NOMEM;
47053  }
47054
47055  for(i=0; rc==SQLITE_OK && i<nSegment; i++){
47056    volatile ht_slot *aHash;
47057    u32 iZero;
47058    volatile u32 *aPgno;
47059
47060    rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
47061    if( rc==SQLITE_OK ){
47062      int j;                      /* Counter variable */
47063      int nEntry;                 /* Number of entries in this segment */
47064      ht_slot *aIndex;            /* Sorted index for this segment */
47065
47066      aPgno++;
47067      if( (i+1)==nSegment ){
47068        nEntry = (int)(iLast - iZero);
47069      }else{
47070        nEntry = (int)((u32*)aHash - (u32*)aPgno);
47071      }
47072      aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
47073      iZero++;
47074
47075      for(j=0; j<nEntry; j++){
47076        aIndex[j] = (ht_slot)j;
47077      }
47078      walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
47079      p->aSegment[i].iZero = iZero;
47080      p->aSegment[i].nEntry = nEntry;
47081      p->aSegment[i].aIndex = aIndex;
47082      p->aSegment[i].aPgno = (u32 *)aPgno;
47083    }
47084  }
47085  sqlite3ScratchFree(aTmp);
47086
47087  if( rc!=SQLITE_OK ){
47088    walIteratorFree(p);
47089  }
47090  *pp = p;
47091  return rc;
47092}
47093
47094/*
47095** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
47096** n. If the attempt fails and parameter xBusy is not NULL, then it is a
47097** busy-handler function. Invoke it and retry the lock until either the
47098** lock is successfully obtained or the busy-handler returns 0.
47099*/
47100static int walBusyLock(
47101  Wal *pWal,                      /* WAL connection */
47102  int (*xBusy)(void*),            /* Function to call when busy */
47103  void *pBusyArg,                 /* Context argument for xBusyHandler */
47104  int lockIdx,                    /* Offset of first byte to lock */
47105  int n                           /* Number of bytes to lock */
47106){
47107  int rc;
47108  do {
47109    rc = walLockExclusive(pWal, lockIdx, n);
47110  }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
47111  return rc;
47112}
47113
47114/*
47115** The cache of the wal-index header must be valid to call this function.
47116** Return the page-size in bytes used by the database.
47117*/
47118static int walPagesize(Wal *pWal){
47119  return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
47120}
47121
47122/*
47123** Copy as much content as we can from the WAL back into the database file
47124** in response to an sqlite3_wal_checkpoint() request or the equivalent.
47125**
47126** The amount of information copies from WAL to database might be limited
47127** by active readers.  This routine will never overwrite a database page
47128** that a concurrent reader might be using.
47129**
47130** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
47131** SQLite is in WAL-mode in synchronous=NORMAL.  That means that if
47132** checkpoints are always run by a background thread or background
47133** process, foreground threads will never block on a lengthy fsync call.
47134**
47135** Fsync is called on the WAL before writing content out of the WAL and
47136** into the database.  This ensures that if the new content is persistent
47137** in the WAL and can be recovered following a power-loss or hard reset.
47138**
47139** Fsync is also called on the database file if (and only if) the entire
47140** WAL content is copied into the database file.  This second fsync makes
47141** it safe to delete the WAL since the new content will persist in the
47142** database file.
47143**
47144** This routine uses and updates the nBackfill field of the wal-index header.
47145** This is the only routine tha will increase the value of nBackfill.
47146** (A WAL reset or recovery will revert nBackfill to zero, but not increase
47147** its value.)
47148**
47149** The caller must be holding sufficient locks to ensure that no other
47150** checkpoint is running (in any other thread or process) at the same
47151** time.
47152*/
47153static int walCheckpoint(
47154  Wal *pWal,                      /* Wal connection */
47155  int eMode,                      /* One of PASSIVE, FULL or RESTART */
47156  int (*xBusyCall)(void*),        /* Function to call when busy */
47157  void *pBusyArg,                 /* Context argument for xBusyHandler */
47158  int sync_flags,                 /* Flags for OsSync() (or 0) */
47159  u8 *zBuf                        /* Temporary buffer to use */
47160){
47161  int rc;                         /* Return code */
47162  int szPage;                     /* Database page-size */
47163  WalIterator *pIter = 0;         /* Wal iterator context */
47164  u32 iDbpage = 0;                /* Next database page to write */
47165  u32 iFrame = 0;                 /* Wal frame containing data for iDbpage */
47166  u32 mxSafeFrame;                /* Max frame that can be backfilled */
47167  u32 mxPage;                     /* Max database page to write */
47168  int i;                          /* Loop counter */
47169  volatile WalCkptInfo *pInfo;    /* The checkpoint status information */
47170  int (*xBusy)(void*) = 0;        /* Function to call when waiting for locks */
47171
47172  szPage = walPagesize(pWal);
47173  testcase( szPage<=32768 );
47174  testcase( szPage>=65536 );
47175  pInfo = walCkptInfo(pWal);
47176  if( pInfo->nBackfill>=pWal->hdr.mxFrame ) return SQLITE_OK;
47177
47178  /* Allocate the iterator */
47179  rc = walIteratorInit(pWal, &pIter);
47180  if( rc!=SQLITE_OK ){
47181    return rc;
47182  }
47183  assert( pIter );
47184
47185  if( eMode!=SQLITE_CHECKPOINT_PASSIVE ) xBusy = xBusyCall;
47186
47187  /* Compute in mxSafeFrame the index of the last frame of the WAL that is
47188  ** safe to write into the database.  Frames beyond mxSafeFrame might
47189  ** overwrite database pages that are in use by active readers and thus
47190  ** cannot be backfilled from the WAL.
47191  */
47192  mxSafeFrame = pWal->hdr.mxFrame;
47193  mxPage = pWal->hdr.nPage;
47194  for(i=1; i<WAL_NREADER; i++){
47195    u32 y = pInfo->aReadMark[i];
47196    if( mxSafeFrame>y ){
47197      assert( y<=pWal->hdr.mxFrame );
47198      rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
47199      if( rc==SQLITE_OK ){
47200        pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
47201        walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
47202      }else if( rc==SQLITE_BUSY ){
47203        mxSafeFrame = y;
47204        xBusy = 0;
47205      }else{
47206        goto walcheckpoint_out;
47207      }
47208    }
47209  }
47210
47211  if( pInfo->nBackfill<mxSafeFrame
47212   && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0), 1))==SQLITE_OK
47213  ){
47214    i64 nSize;                    /* Current size of database file */
47215    u32 nBackfill = pInfo->nBackfill;
47216
47217    /* Sync the WAL to disk */
47218    if( sync_flags ){
47219      rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
47220    }
47221
47222    /* If the database may grow as a result of this checkpoint, hint
47223    ** about the eventual size of the db file to the VFS layer.
47224    */
47225    if( rc==SQLITE_OK ){
47226      i64 nReq = ((i64)mxPage * szPage);
47227      rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
47228      if( rc==SQLITE_OK && nSize<nReq ){
47229        sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
47230      }
47231    }
47232
47233
47234    /* Iterate through the contents of the WAL, copying data to the db file. */
47235    while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
47236      i64 iOffset;
47237      assert( walFramePgno(pWal, iFrame)==iDbpage );
47238      if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ) continue;
47239      iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
47240      /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
47241      rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
47242      if( rc!=SQLITE_OK ) break;
47243      iOffset = (iDbpage-1)*(i64)szPage;
47244      testcase( IS_BIG_INT(iOffset) );
47245      rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
47246      if( rc!=SQLITE_OK ) break;
47247    }
47248
47249    /* If work was actually accomplished... */
47250    if( rc==SQLITE_OK ){
47251      if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
47252        i64 szDb = pWal->hdr.nPage*(i64)szPage;
47253        testcase( IS_BIG_INT(szDb) );
47254        rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
47255        if( rc==SQLITE_OK && sync_flags ){
47256          rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
47257        }
47258      }
47259      if( rc==SQLITE_OK ){
47260        pInfo->nBackfill = mxSafeFrame;
47261      }
47262    }
47263
47264    /* Release the reader lock held while backfilling */
47265    walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
47266  }
47267
47268  if( rc==SQLITE_BUSY ){
47269    /* Reset the return code so as not to report a checkpoint failure
47270    ** just because there are active readers.  */
47271    rc = SQLITE_OK;
47272  }
47273
47274  /* If this is an SQLITE_CHECKPOINT_RESTART operation, and the entire wal
47275  ** file has been copied into the database file, then block until all
47276  ** readers have finished using the wal file. This ensures that the next
47277  ** process to write to the database restarts the wal file.
47278  */
47279  if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
47280    assert( pWal->writeLock );
47281    if( pInfo->nBackfill<pWal->hdr.mxFrame ){
47282      rc = SQLITE_BUSY;
47283    }else if( eMode==SQLITE_CHECKPOINT_RESTART ){
47284      assert( mxSafeFrame==pWal->hdr.mxFrame );
47285      rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
47286      if( rc==SQLITE_OK ){
47287        walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
47288      }
47289    }
47290  }
47291
47292 walcheckpoint_out:
47293  walIteratorFree(pIter);
47294  return rc;
47295}
47296
47297/*
47298** If the WAL file is currently larger than nMax bytes in size, truncate
47299** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
47300*/
47301static void walLimitSize(Wal *pWal, i64 nMax){
47302  i64 sz;
47303  int rx;
47304  sqlite3BeginBenignMalloc();
47305  rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
47306  if( rx==SQLITE_OK && (sz > nMax ) ){
47307    rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
47308  }
47309  sqlite3EndBenignMalloc();
47310  if( rx ){
47311    sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
47312  }
47313}
47314
47315/*
47316** Close a connection to a log file.
47317*/
47318SQLITE_PRIVATE int sqlite3WalClose(
47319  Wal *pWal,                      /* Wal to close */
47320  int sync_flags,                 /* Flags to pass to OsSync() (or 0) */
47321  int nBuf,
47322  u8 *zBuf                        /* Buffer of at least nBuf bytes */
47323){
47324  int rc = SQLITE_OK;
47325  if( pWal ){
47326    int isDelete = 0;             /* True to unlink wal and wal-index files */
47327
47328    /* If an EXCLUSIVE lock can be obtained on the database file (using the
47329    ** ordinary, rollback-mode locking methods, this guarantees that the
47330    ** connection associated with this log file is the only connection to
47331    ** the database. In this case checkpoint the database and unlink both
47332    ** the wal and wal-index files.
47333    **
47334    ** The EXCLUSIVE lock is not released before returning.
47335    */
47336    rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
47337    if( rc==SQLITE_OK ){
47338      if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
47339        pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
47340      }
47341      rc = sqlite3WalCheckpoint(
47342          pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
47343      );
47344      if( rc==SQLITE_OK ){
47345        int bPersist = -1;
47346        sqlite3OsFileControlHint(
47347            pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
47348        );
47349        if( bPersist!=1 ){
47350          /* Try to delete the WAL file if the checkpoint completed and
47351          ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
47352          ** mode (!bPersist) */
47353          isDelete = 1;
47354        }else if( pWal->mxWalSize>=0 ){
47355          /* Try to truncate the WAL file to zero bytes if the checkpoint
47356          ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
47357          ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
47358          ** non-negative value (pWal->mxWalSize>=0).  Note that we truncate
47359          ** to zero bytes as truncating to the journal_size_limit might
47360          ** leave a corrupt WAL file on disk. */
47361          walLimitSize(pWal, 0);
47362        }
47363      }
47364    }
47365
47366    walIndexClose(pWal, isDelete);
47367    sqlite3OsClose(pWal->pWalFd);
47368    if( isDelete ){
47369      sqlite3BeginBenignMalloc();
47370      sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
47371      sqlite3EndBenignMalloc();
47372    }
47373    WALTRACE(("WAL%p: closed\n", pWal));
47374    sqlite3_free((void *)pWal->apWiData);
47375    sqlite3_free(pWal);
47376  }
47377  return rc;
47378}
47379
47380/*
47381** Try to read the wal-index header.  Return 0 on success and 1 if
47382** there is a problem.
47383**
47384** The wal-index is in shared memory.  Another thread or process might
47385** be writing the header at the same time this procedure is trying to
47386** read it, which might result in inconsistency.  A dirty read is detected
47387** by verifying that both copies of the header are the same and also by
47388** a checksum on the header.
47389**
47390** If and only if the read is consistent and the header is different from
47391** pWal->hdr, then pWal->hdr is updated to the content of the new header
47392** and *pChanged is set to 1.
47393**
47394** If the checksum cannot be verified return non-zero. If the header
47395** is read successfully and the checksum verified, return zero.
47396*/
47397static int walIndexTryHdr(Wal *pWal, int *pChanged){
47398  u32 aCksum[2];                  /* Checksum on the header content */
47399  WalIndexHdr h1, h2;             /* Two copies of the header content */
47400  WalIndexHdr volatile *aHdr;     /* Header in shared memory */
47401
47402  /* The first page of the wal-index must be mapped at this point. */
47403  assert( pWal->nWiData>0 && pWal->apWiData[0] );
47404
47405  /* Read the header. This might happen concurrently with a write to the
47406  ** same area of shared memory on a different CPU in a SMP,
47407  ** meaning it is possible that an inconsistent snapshot is read
47408  ** from the file. If this happens, return non-zero.
47409  **
47410  ** There are two copies of the header at the beginning of the wal-index.
47411  ** When reading, read [0] first then [1].  Writes are in the reverse order.
47412  ** Memory barriers are used to prevent the compiler or the hardware from
47413  ** reordering the reads and writes.
47414  */
47415  aHdr = walIndexHdr(pWal);
47416  memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
47417  walShmBarrier(pWal);
47418  memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
47419
47420  if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
47421    return 1;   /* Dirty read */
47422  }
47423  if( h1.isInit==0 ){
47424    return 1;   /* Malformed header - probably all zeros */
47425  }
47426  walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
47427  if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
47428    return 1;   /* Checksum does not match */
47429  }
47430
47431  if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
47432    *pChanged = 1;
47433    memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
47434    pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
47435    testcase( pWal->szPage<=32768 );
47436    testcase( pWal->szPage>=65536 );
47437  }
47438
47439  /* The header was successfully read. Return zero. */
47440  return 0;
47441}
47442
47443/*
47444** Read the wal-index header from the wal-index and into pWal->hdr.
47445** If the wal-header appears to be corrupt, try to reconstruct the
47446** wal-index from the WAL before returning.
47447**
47448** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
47449** changed by this opertion.  If pWal->hdr is unchanged, set *pChanged
47450** to 0.
47451**
47452** If the wal-index header is successfully read, return SQLITE_OK.
47453** Otherwise an SQLite error code.
47454*/
47455static int walIndexReadHdr(Wal *pWal, int *pChanged){
47456  int rc;                         /* Return code */
47457  int badHdr;                     /* True if a header read failed */
47458  volatile u32 *page0;            /* Chunk of wal-index containing header */
47459
47460  /* Ensure that page 0 of the wal-index (the page that contains the
47461  ** wal-index header) is mapped. Return early if an error occurs here.
47462  */
47463  assert( pChanged );
47464  rc = walIndexPage(pWal, 0, &page0);
47465  if( rc!=SQLITE_OK ){
47466    return rc;
47467  };
47468  assert( page0 || pWal->writeLock==0 );
47469
47470  /* If the first page of the wal-index has been mapped, try to read the
47471  ** wal-index header immediately, without holding any lock. This usually
47472  ** works, but may fail if the wal-index header is corrupt or currently
47473  ** being modified by another thread or process.
47474  */
47475  badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
47476
47477  /* If the first attempt failed, it might have been due to a race
47478  ** with a writer.  So get a WRITE lock and try again.
47479  */
47480  assert( badHdr==0 || pWal->writeLock==0 );
47481  if( badHdr ){
47482    if( pWal->readOnly & WAL_SHM_RDONLY ){
47483      if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
47484        walUnlockShared(pWal, WAL_WRITE_LOCK);
47485        rc = SQLITE_READONLY_RECOVERY;
47486      }
47487    }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
47488      pWal->writeLock = 1;
47489      if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
47490        badHdr = walIndexTryHdr(pWal, pChanged);
47491        if( badHdr ){
47492          /* If the wal-index header is still malformed even while holding
47493          ** a WRITE lock, it can only mean that the header is corrupted and
47494          ** needs to be reconstructed.  So run recovery to do exactly that.
47495          */
47496          rc = walIndexRecover(pWal);
47497          *pChanged = 1;
47498        }
47499      }
47500      pWal->writeLock = 0;
47501      walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
47502    }
47503  }
47504
47505  /* If the header is read successfully, check the version number to make
47506  ** sure the wal-index was not constructed with some future format that
47507  ** this version of SQLite cannot understand.
47508  */
47509  if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
47510    rc = SQLITE_CANTOPEN_BKPT;
47511  }
47512
47513  return rc;
47514}
47515
47516/*
47517** This is the value that walTryBeginRead returns when it needs to
47518** be retried.
47519*/
47520#define WAL_RETRY  (-1)
47521
47522/*
47523** Attempt to start a read transaction.  This might fail due to a race or
47524** other transient condition.  When that happens, it returns WAL_RETRY to
47525** indicate to the caller that it is safe to retry immediately.
47526**
47527** On success return SQLITE_OK.  On a permanent failure (such an
47528** I/O error or an SQLITE_BUSY because another process is running
47529** recovery) return a positive error code.
47530**
47531** The useWal parameter is true to force the use of the WAL and disable
47532** the case where the WAL is bypassed because it has been completely
47533** checkpointed.  If useWal==0 then this routine calls walIndexReadHdr()
47534** to make a copy of the wal-index header into pWal->hdr.  If the
47535** wal-index header has changed, *pChanged is set to 1 (as an indication
47536** to the caller that the local paget cache is obsolete and needs to be
47537** flushed.)  When useWal==1, the wal-index header is assumed to already
47538** be loaded and the pChanged parameter is unused.
47539**
47540** The caller must set the cnt parameter to the number of prior calls to
47541** this routine during the current read attempt that returned WAL_RETRY.
47542** This routine will start taking more aggressive measures to clear the
47543** race conditions after multiple WAL_RETRY returns, and after an excessive
47544** number of errors will ultimately return SQLITE_PROTOCOL.  The
47545** SQLITE_PROTOCOL return indicates that some other process has gone rogue
47546** and is not honoring the locking protocol.  There is a vanishingly small
47547** chance that SQLITE_PROTOCOL could be returned because of a run of really
47548** bad luck when there is lots of contention for the wal-index, but that
47549** possibility is so small that it can be safely neglected, we believe.
47550**
47551** On success, this routine obtains a read lock on
47552** WAL_READ_LOCK(pWal->readLock).  The pWal->readLock integer is
47553** in the range 0 <= pWal->readLock < WAL_NREADER.  If pWal->readLock==(-1)
47554** that means the Wal does not hold any read lock.  The reader must not
47555** access any database page that is modified by a WAL frame up to and
47556** including frame number aReadMark[pWal->readLock].  The reader will
47557** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
47558** Or if pWal->readLock==0, then the reader will ignore the WAL
47559** completely and get all content directly from the database file.
47560** If the useWal parameter is 1 then the WAL will never be ignored and
47561** this routine will always set pWal->readLock>0 on success.
47562** When the read transaction is completed, the caller must release the
47563** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
47564**
47565** This routine uses the nBackfill and aReadMark[] fields of the header
47566** to select a particular WAL_READ_LOCK() that strives to let the
47567** checkpoint process do as much work as possible.  This routine might
47568** update values of the aReadMark[] array in the header, but if it does
47569** so it takes care to hold an exclusive lock on the corresponding
47570** WAL_READ_LOCK() while changing values.
47571*/
47572static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
47573  volatile WalCkptInfo *pInfo;    /* Checkpoint information in wal-index */
47574  u32 mxReadMark;                 /* Largest aReadMark[] value */
47575  int mxI;                        /* Index of largest aReadMark[] value */
47576  int i;                          /* Loop counter */
47577  int rc = SQLITE_OK;             /* Return code  */
47578
47579  assert( pWal->readLock<0 );     /* Not currently locked */
47580
47581  /* Take steps to avoid spinning forever if there is a protocol error.
47582  **
47583  ** Circumstances that cause a RETRY should only last for the briefest
47584  ** instances of time.  No I/O or other system calls are done while the
47585  ** locks are held, so the locks should not be held for very long. But
47586  ** if we are unlucky, another process that is holding a lock might get
47587  ** paged out or take a page-fault that is time-consuming to resolve,
47588  ** during the few nanoseconds that it is holding the lock.  In that case,
47589  ** it might take longer than normal for the lock to free.
47590  **
47591  ** After 5 RETRYs, we begin calling sqlite3OsSleep().  The first few
47592  ** calls to sqlite3OsSleep() have a delay of 1 microsecond.  Really this
47593  ** is more of a scheduler yield than an actual delay.  But on the 10th
47594  ** an subsequent retries, the delays start becoming longer and longer,
47595  ** so that on the 100th (and last) RETRY we delay for 21 milliseconds.
47596  ** The total delay time before giving up is less than 1 second.
47597  */
47598  if( cnt>5 ){
47599    int nDelay = 1;                      /* Pause time in microseconds */
47600    if( cnt>100 ){
47601      VVA_ONLY( pWal->lockError = 1; )
47602      return SQLITE_PROTOCOL;
47603    }
47604    if( cnt>=10 ) nDelay = (cnt-9)*238;  /* Max delay 21ms. Total delay 996ms */
47605    sqlite3OsSleep(pWal->pVfs, nDelay);
47606  }
47607
47608  if( !useWal ){
47609    rc = walIndexReadHdr(pWal, pChanged);
47610    if( rc==SQLITE_BUSY ){
47611      /* If there is not a recovery running in another thread or process
47612      ** then convert BUSY errors to WAL_RETRY.  If recovery is known to
47613      ** be running, convert BUSY to BUSY_RECOVERY.  There is a race here
47614      ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
47615      ** would be technically correct.  But the race is benign since with
47616      ** WAL_RETRY this routine will be called again and will probably be
47617      ** right on the second iteration.
47618      */
47619      if( pWal->apWiData[0]==0 ){
47620        /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
47621        ** We assume this is a transient condition, so return WAL_RETRY. The
47622        ** xShmMap() implementation used by the default unix and win32 VFS
47623        ** modules may return SQLITE_BUSY due to a race condition in the
47624        ** code that determines whether or not the shared-memory region
47625        ** must be zeroed before the requested page is returned.
47626        */
47627        rc = WAL_RETRY;
47628      }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
47629        walUnlockShared(pWal, WAL_RECOVER_LOCK);
47630        rc = WAL_RETRY;
47631      }else if( rc==SQLITE_BUSY ){
47632        rc = SQLITE_BUSY_RECOVERY;
47633      }
47634    }
47635    if( rc!=SQLITE_OK ){
47636      return rc;
47637    }
47638  }
47639
47640  pInfo = walCkptInfo(pWal);
47641  if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
47642    /* The WAL has been completely backfilled (or it is empty).
47643    ** and can be safely ignored.
47644    */
47645    rc = walLockShared(pWal, WAL_READ_LOCK(0));
47646    walShmBarrier(pWal);
47647    if( rc==SQLITE_OK ){
47648      if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
47649        /* It is not safe to allow the reader to continue here if frames
47650        ** may have been appended to the log before READ_LOCK(0) was obtained.
47651        ** When holding READ_LOCK(0), the reader ignores the entire log file,
47652        ** which implies that the database file contains a trustworthy
47653        ** snapshoT. Since holding READ_LOCK(0) prevents a checkpoint from
47654        ** happening, this is usually correct.
47655        **
47656        ** However, if frames have been appended to the log (or if the log
47657        ** is wrapped and written for that matter) before the READ_LOCK(0)
47658        ** is obtained, that is not necessarily true. A checkpointer may
47659        ** have started to backfill the appended frames but crashed before
47660        ** it finished. Leaving a corrupt image in the database file.
47661        */
47662        walUnlockShared(pWal, WAL_READ_LOCK(0));
47663        return WAL_RETRY;
47664      }
47665      pWal->readLock = 0;
47666      return SQLITE_OK;
47667    }else if( rc!=SQLITE_BUSY ){
47668      return rc;
47669    }
47670  }
47671
47672  /* If we get this far, it means that the reader will want to use
47673  ** the WAL to get at content from recent commits.  The job now is
47674  ** to select one of the aReadMark[] entries that is closest to
47675  ** but not exceeding pWal->hdr.mxFrame and lock that entry.
47676  */
47677  mxReadMark = 0;
47678  mxI = 0;
47679  for(i=1; i<WAL_NREADER; i++){
47680    u32 thisMark = pInfo->aReadMark[i];
47681    if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
47682      assert( thisMark!=READMARK_NOT_USED );
47683      mxReadMark = thisMark;
47684      mxI = i;
47685    }
47686  }
47687  /* There was once an "if" here. The extra "{" is to preserve indentation. */
47688  {
47689    if( (pWal->readOnly & WAL_SHM_RDONLY)==0
47690     && (mxReadMark<pWal->hdr.mxFrame || mxI==0)
47691    ){
47692      for(i=1; i<WAL_NREADER; i++){
47693        rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
47694        if( rc==SQLITE_OK ){
47695          mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
47696          mxI = i;
47697          walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
47698          break;
47699        }else if( rc!=SQLITE_BUSY ){
47700          return rc;
47701        }
47702      }
47703    }
47704    if( mxI==0 ){
47705      assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
47706      return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;
47707    }
47708
47709    rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
47710    if( rc ){
47711      return rc==SQLITE_BUSY ? WAL_RETRY : rc;
47712    }
47713    /* Now that the read-lock has been obtained, check that neither the
47714    ** value in the aReadMark[] array or the contents of the wal-index
47715    ** header have changed.
47716    **
47717    ** It is necessary to check that the wal-index header did not change
47718    ** between the time it was read and when the shared-lock was obtained
47719    ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
47720    ** that the log file may have been wrapped by a writer, or that frames
47721    ** that occur later in the log than pWal->hdr.mxFrame may have been
47722    ** copied into the database by a checkpointer. If either of these things
47723    ** happened, then reading the database with the current value of
47724    ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
47725    ** instead.
47726    **
47727    ** This does not guarantee that the copy of the wal-index header is up to
47728    ** date before proceeding. That would not be possible without somehow
47729    ** blocking writers. It only guarantees that a dangerous checkpoint or
47730    ** log-wrap (either of which would require an exclusive lock on
47731    ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
47732    */
47733    walShmBarrier(pWal);
47734    if( pInfo->aReadMark[mxI]!=mxReadMark
47735     || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
47736    ){
47737      walUnlockShared(pWal, WAL_READ_LOCK(mxI));
47738      return WAL_RETRY;
47739    }else{
47740      assert( mxReadMark<=pWal->hdr.mxFrame );
47741      pWal->readLock = (i16)mxI;
47742    }
47743  }
47744  return rc;
47745}
47746
47747/*
47748** Begin a read transaction on the database.
47749**
47750** This routine used to be called sqlite3OpenSnapshot() and with good reason:
47751** it takes a snapshot of the state of the WAL and wal-index for the current
47752** instant in time.  The current thread will continue to use this snapshot.
47753** Other threads might append new content to the WAL and wal-index but
47754** that extra content is ignored by the current thread.
47755**
47756** If the database contents have changes since the previous read
47757** transaction, then *pChanged is set to 1 before returning.  The
47758** Pager layer will use this to know that is cache is stale and
47759** needs to be flushed.
47760*/
47761SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
47762  int rc;                         /* Return code */
47763  int cnt = 0;                    /* Number of TryBeginRead attempts */
47764
47765  do{
47766    rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
47767  }while( rc==WAL_RETRY );
47768  testcase( (rc&0xff)==SQLITE_BUSY );
47769  testcase( (rc&0xff)==SQLITE_IOERR );
47770  testcase( rc==SQLITE_PROTOCOL );
47771  testcase( rc==SQLITE_OK );
47772  return rc;
47773}
47774
47775/*
47776** Finish with a read transaction.  All this does is release the
47777** read-lock.
47778*/
47779SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
47780  sqlite3WalEndWriteTransaction(pWal);
47781  if( pWal->readLock>=0 ){
47782    walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
47783    pWal->readLock = -1;
47784  }
47785}
47786
47787/*
47788** Search the wal file for page pgno. If found, set *piRead to the frame that
47789** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
47790** to zero.
47791**
47792** Return SQLITE_OK if successful, or an error code if an error occurs. If an
47793** error does occur, the final value of *piRead is undefined.
47794*/
47795SQLITE_PRIVATE int sqlite3WalFindFrame(
47796  Wal *pWal,                      /* WAL handle */
47797  Pgno pgno,                      /* Database page number to read data for */
47798  u32 *piRead                     /* OUT: Frame number (or zero) */
47799){
47800  u32 iRead = 0;                  /* If !=0, WAL frame to return data from */
47801  u32 iLast = pWal->hdr.mxFrame;  /* Last page in WAL for this reader */
47802  int iHash;                      /* Used to loop through N hash tables */
47803
47804  /* This routine is only be called from within a read transaction. */
47805  assert( pWal->readLock>=0 || pWal->lockError );
47806
47807  /* If the "last page" field of the wal-index header snapshot is 0, then
47808  ** no data will be read from the wal under any circumstances. Return early
47809  ** in this case as an optimization.  Likewise, if pWal->readLock==0,
47810  ** then the WAL is ignored by the reader so return early, as if the
47811  ** WAL were empty.
47812  */
47813  if( iLast==0 || pWal->readLock==0 ){
47814    *piRead = 0;
47815    return SQLITE_OK;
47816  }
47817
47818  /* Search the hash table or tables for an entry matching page number
47819  ** pgno. Each iteration of the following for() loop searches one
47820  ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
47821  **
47822  ** This code might run concurrently to the code in walIndexAppend()
47823  ** that adds entries to the wal-index (and possibly to this hash
47824  ** table). This means the value just read from the hash
47825  ** slot (aHash[iKey]) may have been added before or after the
47826  ** current read transaction was opened. Values added after the
47827  ** read transaction was opened may have been written incorrectly -
47828  ** i.e. these slots may contain garbage data. However, we assume
47829  ** that any slots written before the current read transaction was
47830  ** opened remain unmodified.
47831  **
47832  ** For the reasons above, the if(...) condition featured in the inner
47833  ** loop of the following block is more stringent that would be required
47834  ** if we had exclusive access to the hash-table:
47835  **
47836  **   (aPgno[iFrame]==pgno):
47837  **     This condition filters out normal hash-table collisions.
47838  **
47839  **   (iFrame<=iLast):
47840  **     This condition filters out entries that were added to the hash
47841  **     table after the current read-transaction had started.
47842  */
47843  for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
47844    volatile ht_slot *aHash;      /* Pointer to hash table */
47845    volatile u32 *aPgno;          /* Pointer to array of page numbers */
47846    u32 iZero;                    /* Frame number corresponding to aPgno[0] */
47847    int iKey;                     /* Hash slot index */
47848    int nCollide;                 /* Number of hash collisions remaining */
47849    int rc;                       /* Error code */
47850
47851    rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
47852    if( rc!=SQLITE_OK ){
47853      return rc;
47854    }
47855    nCollide = HASHTABLE_NSLOT;
47856    for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
47857      u32 iFrame = aHash[iKey] + iZero;
47858      if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
47859        /* assert( iFrame>iRead ); -- not true if there is corruption */
47860        iRead = iFrame;
47861      }
47862      if( (nCollide--)==0 ){
47863        return SQLITE_CORRUPT_BKPT;
47864      }
47865    }
47866  }
47867
47868#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
47869  /* If expensive assert() statements are available, do a linear search
47870  ** of the wal-index file content. Make sure the results agree with the
47871  ** result obtained using the hash indexes above.  */
47872  {
47873    u32 iRead2 = 0;
47874    u32 iTest;
47875    for(iTest=iLast; iTest>0; iTest--){
47876      if( walFramePgno(pWal, iTest)==pgno ){
47877        iRead2 = iTest;
47878        break;
47879      }
47880    }
47881    assert( iRead==iRead2 );
47882  }
47883#endif
47884
47885  *piRead = iRead;
47886  return SQLITE_OK;
47887}
47888
47889/*
47890** Read the contents of frame iRead from the wal file into buffer pOut
47891** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
47892** error code otherwise.
47893*/
47894SQLITE_PRIVATE int sqlite3WalReadFrame(
47895  Wal *pWal,                      /* WAL handle */
47896  u32 iRead,                      /* Frame to read */
47897  int nOut,                       /* Size of buffer pOut in bytes */
47898  u8 *pOut                        /* Buffer to write page data to */
47899){
47900  int sz;
47901  i64 iOffset;
47902  sz = pWal->hdr.szPage;
47903  sz = (sz&0xfe00) + ((sz&0x0001)<<16);
47904  testcase( sz<=32768 );
47905  testcase( sz>=65536 );
47906  iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
47907  /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
47908  return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
47909}
47910
47911/*
47912** Return the size of the database in pages (or zero, if unknown).
47913*/
47914SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
47915  if( pWal && ALWAYS(pWal->readLock>=0) ){
47916    return pWal->hdr.nPage;
47917  }
47918  return 0;
47919}
47920
47921
47922/*
47923** This function starts a write transaction on the WAL.
47924**
47925** A read transaction must have already been started by a prior call
47926** to sqlite3WalBeginReadTransaction().
47927**
47928** If another thread or process has written into the database since
47929** the read transaction was started, then it is not possible for this
47930** thread to write as doing so would cause a fork.  So this routine
47931** returns SQLITE_BUSY in that case and no write transaction is started.
47932**
47933** There can only be a single writer active at a time.
47934*/
47935SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
47936  int rc;
47937
47938  /* Cannot start a write transaction without first holding a read
47939  ** transaction. */
47940  assert( pWal->readLock>=0 );
47941
47942  if( pWal->readOnly ){
47943    return SQLITE_READONLY;
47944  }
47945
47946  /* Only one writer allowed at a time.  Get the write lock.  Return
47947  ** SQLITE_BUSY if unable.
47948  */
47949  rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
47950  if( rc ){
47951    return rc;
47952  }
47953  pWal->writeLock = 1;
47954
47955  /* If another connection has written to the database file since the
47956  ** time the read transaction on this connection was started, then
47957  ** the write is disallowed.
47958  */
47959  if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
47960    walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
47961    pWal->writeLock = 0;
47962    rc = SQLITE_BUSY;
47963  }
47964
47965  return rc;
47966}
47967
47968/*
47969** End a write transaction.  The commit has already been done.  This
47970** routine merely releases the lock.
47971*/
47972SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
47973  if( pWal->writeLock ){
47974    walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
47975    pWal->writeLock = 0;
47976    pWal->truncateOnCommit = 0;
47977  }
47978  return SQLITE_OK;
47979}
47980
47981/*
47982** If any data has been written (but not committed) to the log file, this
47983** function moves the write-pointer back to the start of the transaction.
47984**
47985** Additionally, the callback function is invoked for each frame written
47986** to the WAL since the start of the transaction. If the callback returns
47987** other than SQLITE_OK, it is not invoked again and the error code is
47988** returned to the caller.
47989**
47990** Otherwise, if the callback function does not return an error, this
47991** function returns SQLITE_OK.
47992*/
47993SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
47994  int rc = SQLITE_OK;
47995  if( ALWAYS(pWal->writeLock) ){
47996    Pgno iMax = pWal->hdr.mxFrame;
47997    Pgno iFrame;
47998
47999    /* Restore the clients cache of the wal-index header to the state it
48000    ** was in before the client began writing to the database.
48001    */
48002    memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
48003
48004    for(iFrame=pWal->hdr.mxFrame+1;
48005        ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
48006        iFrame++
48007    ){
48008      /* This call cannot fail. Unless the page for which the page number
48009      ** is passed as the second argument is (a) in the cache and
48010      ** (b) has an outstanding reference, then xUndo is either a no-op
48011      ** (if (a) is false) or simply expels the page from the cache (if (b)
48012      ** is false).
48013      **
48014      ** If the upper layer is doing a rollback, it is guaranteed that there
48015      ** are no outstanding references to any page other than page 1. And
48016      ** page 1 is never written to the log until the transaction is
48017      ** committed. As a result, the call to xUndo may not fail.
48018      */
48019      assert( walFramePgno(pWal, iFrame)!=1 );
48020      rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
48021    }
48022    if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
48023  }
48024  assert( rc==SQLITE_OK );
48025  return rc;
48026}
48027
48028/*
48029** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
48030** values. This function populates the array with values required to
48031** "rollback" the write position of the WAL handle back to the current
48032** point in the event of a savepoint rollback (via WalSavepointUndo()).
48033*/
48034SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
48035  assert( pWal->writeLock );
48036  aWalData[0] = pWal->hdr.mxFrame;
48037  aWalData[1] = pWal->hdr.aFrameCksum[0];
48038  aWalData[2] = pWal->hdr.aFrameCksum[1];
48039  aWalData[3] = pWal->nCkpt;
48040}
48041
48042/*
48043** Move the write position of the WAL back to the point identified by
48044** the values in the aWalData[] array. aWalData must point to an array
48045** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
48046** by a call to WalSavepoint().
48047*/
48048SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
48049  int rc = SQLITE_OK;
48050
48051  assert( pWal->writeLock );
48052  assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
48053
48054  if( aWalData[3]!=pWal->nCkpt ){
48055    /* This savepoint was opened immediately after the write-transaction
48056    ** was started. Right after that, the writer decided to wrap around
48057    ** to the start of the log. Update the savepoint values to match.
48058    */
48059    aWalData[0] = 0;
48060    aWalData[3] = pWal->nCkpt;
48061  }
48062
48063  if( aWalData[0]<pWal->hdr.mxFrame ){
48064    pWal->hdr.mxFrame = aWalData[0];
48065    pWal->hdr.aFrameCksum[0] = aWalData[1];
48066    pWal->hdr.aFrameCksum[1] = aWalData[2];
48067    walCleanupHash(pWal);
48068  }
48069
48070  return rc;
48071}
48072
48073
48074/*
48075** This function is called just before writing a set of frames to the log
48076** file (see sqlite3WalFrames()). It checks to see if, instead of appending
48077** to the current log file, it is possible to overwrite the start of the
48078** existing log file with the new frames (i.e. "reset" the log). If so,
48079** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
48080** unchanged.
48081**
48082** SQLITE_OK is returned if no error is encountered (regardless of whether
48083** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
48084** if an error occurs.
48085*/
48086static int walRestartLog(Wal *pWal){
48087  int rc = SQLITE_OK;
48088  int cnt;
48089
48090  if( pWal->readLock==0 ){
48091    volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
48092    assert( pInfo->nBackfill==pWal->hdr.mxFrame );
48093    if( pInfo->nBackfill>0 ){
48094      u32 salt1;
48095      sqlite3_randomness(4, &salt1);
48096      rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
48097      if( rc==SQLITE_OK ){
48098        /* If all readers are using WAL_READ_LOCK(0) (in other words if no
48099        ** readers are currently using the WAL), then the transactions
48100        ** frames will overwrite the start of the existing log. Update the
48101        ** wal-index header to reflect this.
48102        **
48103        ** In theory it would be Ok to update the cache of the header only
48104        ** at this point. But updating the actual wal-index header is also
48105        ** safe and means there is no special case for sqlite3WalUndo()
48106        ** to handle if this transaction is rolled back.
48107        */
48108        int i;                    /* Loop counter */
48109        u32 *aSalt = pWal->hdr.aSalt;       /* Big-endian salt values */
48110
48111        pWal->nCkpt++;
48112        pWal->hdr.mxFrame = 0;
48113        sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
48114        aSalt[1] = salt1;
48115        walIndexWriteHdr(pWal);
48116        pInfo->nBackfill = 0;
48117        pInfo->aReadMark[1] = 0;
48118        for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
48119        assert( pInfo->aReadMark[0]==0 );
48120        walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
48121      }else if( rc!=SQLITE_BUSY ){
48122        return rc;
48123      }
48124    }
48125    walUnlockShared(pWal, WAL_READ_LOCK(0));
48126    pWal->readLock = -1;
48127    cnt = 0;
48128    do{
48129      int notUsed;
48130      rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
48131    }while( rc==WAL_RETRY );
48132    assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
48133    testcase( (rc&0xff)==SQLITE_IOERR );
48134    testcase( rc==SQLITE_PROTOCOL );
48135    testcase( rc==SQLITE_OK );
48136  }
48137  return rc;
48138}
48139
48140/*
48141** Information about the current state of the WAL file and where
48142** the next fsync should occur - passed from sqlite3WalFrames() into
48143** walWriteToLog().
48144*/
48145typedef struct WalWriter {
48146  Wal *pWal;                   /* The complete WAL information */
48147  sqlite3_file *pFd;           /* The WAL file to which we write */
48148  sqlite3_int64 iSyncPoint;    /* Fsync at this offset */
48149  int syncFlags;               /* Flags for the fsync */
48150  int szPage;                  /* Size of one page */
48151} WalWriter;
48152
48153/*
48154** Write iAmt bytes of content into the WAL file beginning at iOffset.
48155** Do a sync when crossing the p->iSyncPoint boundary.
48156**
48157** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
48158** first write the part before iSyncPoint, then sync, then write the
48159** rest.
48160*/
48161static int walWriteToLog(
48162  WalWriter *p,              /* WAL to write to */
48163  void *pContent,            /* Content to be written */
48164  int iAmt,                  /* Number of bytes to write */
48165  sqlite3_int64 iOffset      /* Start writing at this offset */
48166){
48167  int rc;
48168  if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
48169    int iFirstAmt = (int)(p->iSyncPoint - iOffset);
48170    rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
48171    if( rc ) return rc;
48172    iOffset += iFirstAmt;
48173    iAmt -= iFirstAmt;
48174    pContent = (void*)(iFirstAmt + (char*)pContent);
48175    assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) );
48176    rc = sqlite3OsSync(p->pFd, p->syncFlags);
48177    if( iAmt==0 || rc ) return rc;
48178  }
48179  rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
48180  return rc;
48181}
48182
48183/*
48184** Write out a single frame of the WAL
48185*/
48186static int walWriteOneFrame(
48187  WalWriter *p,               /* Where to write the frame */
48188  PgHdr *pPage,               /* The page of the frame to be written */
48189  int nTruncate,              /* The commit flag.  Usually 0.  >0 for commit */
48190  sqlite3_int64 iOffset       /* Byte offset at which to write */
48191){
48192  int rc;                         /* Result code from subfunctions */
48193  void *pData;                    /* Data actually written */
48194  u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-header in */
48195#if defined(SQLITE_HAS_CODEC)
48196  if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM;
48197#else
48198  pData = pPage->pData;
48199#endif
48200  walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
48201  rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
48202  if( rc ) return rc;
48203  /* Write the page data */
48204  rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
48205  return rc;
48206}
48207
48208/*
48209** Write a set of frames to the log. The caller must hold the write-lock
48210** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
48211*/
48212SQLITE_PRIVATE int sqlite3WalFrames(
48213  Wal *pWal,                      /* Wal handle to write to */
48214  int szPage,                     /* Database page-size in bytes */
48215  PgHdr *pList,                   /* List of dirty pages to write */
48216  Pgno nTruncate,                 /* Database size after this commit */
48217  int isCommit,                   /* True if this is a commit */
48218  int sync_flags                  /* Flags to pass to OsSync() (or 0) */
48219){
48220  int rc;                         /* Used to catch return codes */
48221  u32 iFrame;                     /* Next frame address */
48222  PgHdr *p;                       /* Iterator to run through pList with. */
48223  PgHdr *pLast = 0;               /* Last frame in list */
48224  int nExtra = 0;                 /* Number of extra copies of last page */
48225  int szFrame;                    /* The size of a single frame */
48226  i64 iOffset;                    /* Next byte to write in WAL file */
48227  WalWriter w;                    /* The writer */
48228
48229  assert( pList );
48230  assert( pWal->writeLock );
48231
48232  /* If this frame set completes a transaction, then nTruncate>0.  If
48233  ** nTruncate==0 then this frame set does not complete the transaction. */
48234  assert( (isCommit!=0)==(nTruncate!=0) );
48235
48236#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
48237  { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
48238    WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
48239              pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
48240  }
48241#endif
48242
48243  /* See if it is possible to write these frames into the start of the
48244  ** log file, instead of appending to it at pWal->hdr.mxFrame.
48245  */
48246  if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
48247    return rc;
48248  }
48249
48250  /* If this is the first frame written into the log, write the WAL
48251  ** header to the start of the WAL file. See comments at the top of
48252  ** this source file for a description of the WAL header format.
48253  */
48254  iFrame = pWal->hdr.mxFrame;
48255  if( iFrame==0 ){
48256    u8 aWalHdr[WAL_HDRSIZE];      /* Buffer to assemble wal-header in */
48257    u32 aCksum[2];                /* Checksum for wal-header */
48258
48259    sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
48260    sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
48261    sqlite3Put4byte(&aWalHdr[8], szPage);
48262    sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
48263    if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
48264    memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
48265    walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
48266    sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
48267    sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
48268
48269    pWal->szPage = szPage;
48270    pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
48271    pWal->hdr.aFrameCksum[0] = aCksum[0];
48272    pWal->hdr.aFrameCksum[1] = aCksum[1];
48273    pWal->truncateOnCommit = 1;
48274
48275    rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
48276    WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
48277    if( rc!=SQLITE_OK ){
48278      return rc;
48279    }
48280
48281    /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
48282    ** all syncing is turned off by PRAGMA synchronous=OFF).  Otherwise
48283    ** an out-of-order write following a WAL restart could result in
48284    ** database corruption.  See the ticket:
48285    **
48286    **     http://localhost:591/sqlite/info/ff5be73dee
48287    */
48288    if( pWal->syncHeader && sync_flags ){
48289      rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK);
48290      if( rc ) return rc;
48291    }
48292  }
48293  assert( (int)pWal->szPage==szPage );
48294
48295  /* Setup information needed to write frames into the WAL */
48296  w.pWal = pWal;
48297  w.pFd = pWal->pWalFd;
48298  w.iSyncPoint = 0;
48299  w.syncFlags = sync_flags;
48300  w.szPage = szPage;
48301  iOffset = walFrameOffset(iFrame+1, szPage);
48302  szFrame = szPage + WAL_FRAME_HDRSIZE;
48303
48304  /* Write all frames into the log file exactly once */
48305  for(p=pList; p; p=p->pDirty){
48306    int nDbSize;   /* 0 normally.  Positive == commit flag */
48307    iFrame++;
48308    assert( iOffset==walFrameOffset(iFrame, szPage) );
48309    nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
48310    rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
48311    if( rc ) return rc;
48312    pLast = p;
48313    iOffset += szFrame;
48314  }
48315
48316  /* If this is the end of a transaction, then we might need to pad
48317  ** the transaction and/or sync the WAL file.
48318  **
48319  ** Padding and syncing only occur if this set of frames complete a
48320  ** transaction and if PRAGMA synchronous=FULL.  If synchronous==NORMAL
48321  ** or synchonous==OFF, then no padding or syncing are needed.
48322  **
48323  ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
48324  ** needed and only the sync is done.  If padding is needed, then the
48325  ** final frame is repeated (with its commit mark) until the next sector
48326  ** boundary is crossed.  Only the part of the WAL prior to the last
48327  ** sector boundary is synced; the part of the last frame that extends
48328  ** past the sector boundary is written after the sync.
48329  */
48330  if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){
48331    if( pWal->padToSectorBoundary ){
48332      int sectorSize = sqlite3SectorSize(pWal->pWalFd);
48333      w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
48334      while( iOffset<w.iSyncPoint ){
48335        rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
48336        if( rc ) return rc;
48337        iOffset += szFrame;
48338        nExtra++;
48339      }
48340    }else{
48341      rc = sqlite3OsSync(w.pFd, sync_flags & SQLITE_SYNC_MASK);
48342    }
48343  }
48344
48345  /* If this frame set completes the first transaction in the WAL and
48346  ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
48347  ** journal size limit, if possible.
48348  */
48349  if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
48350    i64 sz = pWal->mxWalSize;
48351    if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
48352      sz = walFrameOffset(iFrame+nExtra+1, szPage);
48353    }
48354    walLimitSize(pWal, sz);
48355    pWal->truncateOnCommit = 0;
48356  }
48357
48358  /* Append data to the wal-index. It is not necessary to lock the
48359  ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
48360  ** guarantees that there are no other writers, and no data that may
48361  ** be in use by existing readers is being overwritten.
48362  */
48363  iFrame = pWal->hdr.mxFrame;
48364  for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
48365    iFrame++;
48366    rc = walIndexAppend(pWal, iFrame, p->pgno);
48367  }
48368  while( rc==SQLITE_OK && nExtra>0 ){
48369    iFrame++;
48370    nExtra--;
48371    rc = walIndexAppend(pWal, iFrame, pLast->pgno);
48372  }
48373
48374  if( rc==SQLITE_OK ){
48375    /* Update the private copy of the header. */
48376    pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
48377    testcase( szPage<=32768 );
48378    testcase( szPage>=65536 );
48379    pWal->hdr.mxFrame = iFrame;
48380    if( isCommit ){
48381      pWal->hdr.iChange++;
48382      pWal->hdr.nPage = nTruncate;
48383    }
48384    /* If this is a commit, update the wal-index header too. */
48385    if( isCommit ){
48386      walIndexWriteHdr(pWal);
48387      pWal->iCallback = iFrame;
48388    }
48389  }
48390
48391  WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
48392  return rc;
48393}
48394
48395/*
48396** This routine is called to implement sqlite3_wal_checkpoint() and
48397** related interfaces.
48398**
48399** Obtain a CHECKPOINT lock and then backfill as much information as
48400** we can from WAL into the database.
48401**
48402** If parameter xBusy is not NULL, it is a pointer to a busy-handler
48403** callback. In this case this function runs a blocking checkpoint.
48404*/
48405SQLITE_PRIVATE int sqlite3WalCheckpoint(
48406  Wal *pWal,                      /* Wal connection */
48407  int eMode,                      /* PASSIVE, FULL or RESTART */
48408  int (*xBusy)(void*),            /* Function to call when busy */
48409  void *pBusyArg,                 /* Context argument for xBusyHandler */
48410  int sync_flags,                 /* Flags to sync db file with (or 0) */
48411  int nBuf,                       /* Size of temporary buffer */
48412  u8 *zBuf,                       /* Temporary buffer to use */
48413  int *pnLog,                     /* OUT: Number of frames in WAL */
48414  int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
48415){
48416  int rc;                         /* Return code */
48417  int isChanged = 0;              /* True if a new wal-index header is loaded */
48418  int eMode2 = eMode;             /* Mode to pass to walCheckpoint() */
48419
48420  assert( pWal->ckptLock==0 );
48421  assert( pWal->writeLock==0 );
48422
48423  if( pWal->readOnly ) return SQLITE_READONLY;
48424  WALTRACE(("WAL%p: checkpoint begins\n", pWal));
48425  rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
48426  if( rc ){
48427    /* Usually this is SQLITE_BUSY meaning that another thread or process
48428    ** is already running a checkpoint, or maybe a recovery.  But it might
48429    ** also be SQLITE_IOERR. */
48430    return rc;
48431  }
48432  pWal->ckptLock = 1;
48433
48434  /* If this is a blocking-checkpoint, then obtain the write-lock as well
48435  ** to prevent any writers from running while the checkpoint is underway.
48436  ** This has to be done before the call to walIndexReadHdr() below.
48437  **
48438  ** If the writer lock cannot be obtained, then a passive checkpoint is
48439  ** run instead. Since the checkpointer is not holding the writer lock,
48440  ** there is no point in blocking waiting for any readers. Assuming no
48441  ** other error occurs, this function will return SQLITE_BUSY to the caller.
48442  */
48443  if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
48444    rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
48445    if( rc==SQLITE_OK ){
48446      pWal->writeLock = 1;
48447    }else if( rc==SQLITE_BUSY ){
48448      eMode2 = SQLITE_CHECKPOINT_PASSIVE;
48449      rc = SQLITE_OK;
48450    }
48451  }
48452
48453  /* Read the wal-index header. */
48454  if( rc==SQLITE_OK ){
48455    rc = walIndexReadHdr(pWal, &isChanged);
48456    if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
48457      sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
48458    }
48459  }
48460
48461  /* Copy data from the log to the database file. */
48462  if( rc==SQLITE_OK ){
48463    if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
48464      rc = SQLITE_CORRUPT_BKPT;
48465    }else{
48466      rc = walCheckpoint(pWal, eMode2, xBusy, pBusyArg, sync_flags, zBuf);
48467    }
48468
48469    /* If no error occurred, set the output variables. */
48470    if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
48471      if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
48472      if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
48473    }
48474  }
48475
48476  if( isChanged ){
48477    /* If a new wal-index header was loaded before the checkpoint was
48478    ** performed, then the pager-cache associated with pWal is now
48479    ** out of date. So zero the cached wal-index header to ensure that
48480    ** next time the pager opens a snapshot on this database it knows that
48481    ** the cache needs to be reset.
48482    */
48483    memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
48484  }
48485
48486  /* Release the locks. */
48487  sqlite3WalEndWriteTransaction(pWal);
48488  walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
48489  pWal->ckptLock = 0;
48490  WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
48491  return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
48492}
48493
48494/* Return the value to pass to a sqlite3_wal_hook callback, the
48495** number of frames in the WAL at the point of the last commit since
48496** sqlite3WalCallback() was called.  If no commits have occurred since
48497** the last call, then return 0.
48498*/
48499SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
48500  u32 ret = 0;
48501  if( pWal ){
48502    ret = pWal->iCallback;
48503    pWal->iCallback = 0;
48504  }
48505  return (int)ret;
48506}
48507
48508/*
48509** This function is called to change the WAL subsystem into or out
48510** of locking_mode=EXCLUSIVE.
48511**
48512** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
48513** into locking_mode=NORMAL.  This means that we must acquire a lock
48514** on the pWal->readLock byte.  If the WAL is already in locking_mode=NORMAL
48515** or if the acquisition of the lock fails, then return 0.  If the
48516** transition out of exclusive-mode is successful, return 1.  This
48517** operation must occur while the pager is still holding the exclusive
48518** lock on the main database file.
48519**
48520** If op is one, then change from locking_mode=NORMAL into
48521** locking_mode=EXCLUSIVE.  This means that the pWal->readLock must
48522** be released.  Return 1 if the transition is made and 0 if the
48523** WAL is already in exclusive-locking mode - meaning that this
48524** routine is a no-op.  The pager must already hold the exclusive lock
48525** on the main database file before invoking this operation.
48526**
48527** If op is negative, then do a dry-run of the op==1 case but do
48528** not actually change anything. The pager uses this to see if it
48529** should acquire the database exclusive lock prior to invoking
48530** the op==1 case.
48531*/
48532SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
48533  int rc;
48534  assert( pWal->writeLock==0 );
48535  assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
48536
48537  /* pWal->readLock is usually set, but might be -1 if there was a
48538  ** prior error while attempting to acquire are read-lock. This cannot
48539  ** happen if the connection is actually in exclusive mode (as no xShmLock
48540  ** locks are taken in this case). Nor should the pager attempt to
48541  ** upgrade to exclusive-mode following such an error.
48542  */
48543  assert( pWal->readLock>=0 || pWal->lockError );
48544  assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
48545
48546  if( op==0 ){
48547    if( pWal->exclusiveMode ){
48548      pWal->exclusiveMode = 0;
48549      if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
48550        pWal->exclusiveMode = 1;
48551      }
48552      rc = pWal->exclusiveMode==0;
48553    }else{
48554      /* Already in locking_mode=NORMAL */
48555      rc = 0;
48556    }
48557  }else if( op>0 ){
48558    assert( pWal->exclusiveMode==0 );
48559    assert( pWal->readLock>=0 );
48560    walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
48561    pWal->exclusiveMode = 1;
48562    rc = 1;
48563  }else{
48564    rc = pWal->exclusiveMode==0;
48565  }
48566  return rc;
48567}
48568
48569/*
48570** Return true if the argument is non-NULL and the WAL module is using
48571** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
48572** WAL module is using shared-memory, return false.
48573*/
48574SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
48575  return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
48576}
48577
48578#ifdef SQLITE_ENABLE_ZIPVFS
48579/*
48580** If the argument is not NULL, it points to a Wal object that holds a
48581** read-lock. This function returns the database page-size if it is known,
48582** or zero if it is not (or if pWal is NULL).
48583*/
48584SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
48585  assert( pWal==0 || pWal->readLock>=0 );
48586  return (pWal ? pWal->szPage : 0);
48587}
48588#endif
48589
48590#endif /* #ifndef SQLITE_OMIT_WAL */
48591
48592/************** End of wal.c *************************************************/
48593/************** Begin file btmutex.c *****************************************/
48594/*
48595** 2007 August 27
48596**
48597** The author disclaims copyright to this source code.  In place of
48598** a legal notice, here is a blessing:
48599**
48600**    May you do good and not evil.
48601**    May you find forgiveness for yourself and forgive others.
48602**    May you share freely, never taking more than you give.
48603**
48604*************************************************************************
48605**
48606** This file contains code used to implement mutexes on Btree objects.
48607** This code really belongs in btree.c.  But btree.c is getting too
48608** big and we want to break it down some.  This packaged seemed like
48609** a good breakout.
48610*/
48611/************** Include btreeInt.h in the middle of btmutex.c ****************/
48612/************** Begin file btreeInt.h ****************************************/
48613/*
48614** 2004 April 6
48615**
48616** The author disclaims copyright to this source code.  In place of
48617** a legal notice, here is a blessing:
48618**
48619**    May you do good and not evil.
48620**    May you find forgiveness for yourself and forgive others.
48621**    May you share freely, never taking more than you give.
48622**
48623*************************************************************************
48624** This file implements a external (disk-based) database using BTrees.
48625** For a detailed discussion of BTrees, refer to
48626**
48627**     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
48628**     "Sorting And Searching", pages 473-480. Addison-Wesley
48629**     Publishing Company, Reading, Massachusetts.
48630**
48631** The basic idea is that each page of the file contains N database
48632** entries and N+1 pointers to subpages.
48633**
48634**   ----------------------------------------------------------------
48635**   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
48636**   ----------------------------------------------------------------
48637**
48638** All of the keys on the page that Ptr(0) points to have values less
48639** than Key(0).  All of the keys on page Ptr(1) and its subpages have
48640** values greater than Key(0) and less than Key(1).  All of the keys
48641** on Ptr(N) and its subpages have values greater than Key(N-1).  And
48642** so forth.
48643**
48644** Finding a particular key requires reading O(log(M)) pages from the
48645** disk where M is the number of entries in the tree.
48646**
48647** In this implementation, a single file can hold one or more separate
48648** BTrees.  Each BTree is identified by the index of its root page.  The
48649** key and data for any entry are combined to form the "payload".  A
48650** fixed amount of payload can be carried directly on the database
48651** page.  If the payload is larger than the preset amount then surplus
48652** bytes are stored on overflow pages.  The payload for an entry
48653** and the preceding pointer are combined to form a "Cell".  Each
48654** page has a small header which contains the Ptr(N) pointer and other
48655** information such as the size of key and data.
48656**
48657** FORMAT DETAILS
48658**
48659** The file is divided into pages.  The first page is called page 1,
48660** the second is page 2, and so forth.  A page number of zero indicates
48661** "no such page".  The page size can be any power of 2 between 512 and 65536.
48662** Each page can be either a btree page, a freelist page, an overflow
48663** page, or a pointer-map page.
48664**
48665** The first page is always a btree page.  The first 100 bytes of the first
48666** page contain a special header (the "file header") that describes the file.
48667** The format of the file header is as follows:
48668**
48669**   OFFSET   SIZE    DESCRIPTION
48670**      0      16     Header string: "SQLite format 3\000"
48671**     16       2     Page size in bytes.
48672**     18       1     File format write version
48673**     19       1     File format read version
48674**     20       1     Bytes of unused space at the end of each page
48675**     21       1     Max embedded payload fraction
48676**     22       1     Min embedded payload fraction
48677**     23       1     Min leaf payload fraction
48678**     24       4     File change counter
48679**     28       4     Reserved for future use
48680**     32       4     First freelist page
48681**     36       4     Number of freelist pages in the file
48682**     40      60     15 4-byte meta values passed to higher layers
48683**
48684**     40       4     Schema cookie
48685**     44       4     File format of schema layer
48686**     48       4     Size of page cache
48687**     52       4     Largest root-page (auto/incr_vacuum)
48688**     56       4     1=UTF-8 2=UTF16le 3=UTF16be
48689**     60       4     User version
48690**     64       4     Incremental vacuum mode
48691**     68       4     unused
48692**     72       4     unused
48693**     76       4     unused
48694**
48695** All of the integer values are big-endian (most significant byte first).
48696**
48697** The file change counter is incremented when the database is changed
48698** This counter allows other processes to know when the file has changed
48699** and thus when they need to flush their cache.
48700**
48701** The max embedded payload fraction is the amount of the total usable
48702** space in a page that can be consumed by a single cell for standard
48703** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
48704** is to limit the maximum cell size so that at least 4 cells will fit
48705** on one page.  Thus the default max embedded payload fraction is 64.
48706**
48707** If the payload for a cell is larger than the max payload, then extra
48708** payload is spilled to overflow pages.  Once an overflow page is allocated,
48709** as many bytes as possible are moved into the overflow pages without letting
48710** the cell size drop below the min embedded payload fraction.
48711**
48712** The min leaf payload fraction is like the min embedded payload fraction
48713** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
48714** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
48715** not specified in the header.
48716**
48717** Each btree pages is divided into three sections:  The header, the
48718** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
48719** file header that occurs before the page header.
48720**
48721**      |----------------|
48722**      | file header    |   100 bytes.  Page 1 only.
48723**      |----------------|
48724**      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
48725**      |----------------|
48726**      | cell pointer   |   |  2 bytes per cell.  Sorted order.
48727**      | array          |   |  Grows downward
48728**      |                |   v
48729**      |----------------|
48730**      | unallocated    |
48731**      | space          |
48732**      |----------------|   ^  Grows upwards
48733**      | cell content   |   |  Arbitrary order interspersed with freeblocks.
48734**      | area           |   |  and free space fragments.
48735**      |----------------|
48736**
48737** The page headers looks like this:
48738**
48739**   OFFSET   SIZE     DESCRIPTION
48740**      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
48741**      1       2      byte offset to the first freeblock
48742**      3       2      number of cells on this page
48743**      5       2      first byte of the cell content area
48744**      7       1      number of fragmented free bytes
48745**      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
48746**
48747** The flags define the format of this btree page.  The leaf flag means that
48748** this page has no children.  The zerodata flag means that this page carries
48749** only keys and no data.  The intkey flag means that the key is a integer
48750** which is stored in the key size entry of the cell header rather than in
48751** the payload area.
48752**
48753** The cell pointer array begins on the first byte after the page header.
48754** The cell pointer array contains zero or more 2-byte numbers which are
48755** offsets from the beginning of the page to the cell content in the cell
48756** content area.  The cell pointers occur in sorted order.  The system strives
48757** to keep free space after the last cell pointer so that new cells can
48758** be easily added without having to defragment the page.
48759**
48760** Cell content is stored at the very end of the page and grows toward the
48761** beginning of the page.
48762**
48763** Unused space within the cell content area is collected into a linked list of
48764** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
48765** to the first freeblock is given in the header.  Freeblocks occur in
48766** increasing order.  Because a freeblock must be at least 4 bytes in size,
48767** any group of 3 or fewer unused bytes in the cell content area cannot
48768** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
48769** a fragment.  The total number of bytes in all fragments is recorded.
48770** in the page header at offset 7.
48771**
48772**    SIZE    DESCRIPTION
48773**      2     Byte offset of the next freeblock
48774**      2     Bytes in this freeblock
48775**
48776** Cells are of variable length.  Cells are stored in the cell content area at
48777** the end of the page.  Pointers to the cells are in the cell pointer array
48778** that immediately follows the page header.  Cells is not necessarily
48779** contiguous or in order, but cell pointers are contiguous and in order.
48780**
48781** Cell content makes use of variable length integers.  A variable
48782** length integer is 1 to 9 bytes where the lower 7 bits of each
48783** byte are used.  The integer consists of all bytes that have bit 8 set and
48784** the first byte with bit 8 clear.  The most significant byte of the integer
48785** appears first.  A variable-length integer may not be more than 9 bytes long.
48786** As a special case, all 8 bytes of the 9th byte are used as data.  This
48787** allows a 64-bit integer to be encoded in 9 bytes.
48788**
48789**    0x00                      becomes  0x00000000
48790**    0x7f                      becomes  0x0000007f
48791**    0x81 0x00                 becomes  0x00000080
48792**    0x82 0x00                 becomes  0x00000100
48793**    0x80 0x7f                 becomes  0x0000007f
48794**    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
48795**    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
48796**
48797** Variable length integers are used for rowids and to hold the number of
48798** bytes of key and data in a btree cell.
48799**
48800** The content of a cell looks like this:
48801**
48802**    SIZE    DESCRIPTION
48803**      4     Page number of the left child. Omitted if leaf flag is set.
48804**     var    Number of bytes of data. Omitted if the zerodata flag is set.
48805**     var    Number of bytes of key. Or the key itself if intkey flag is set.
48806**      *     Payload
48807**      4     First page of the overflow chain.  Omitted if no overflow
48808**
48809** Overflow pages form a linked list.  Each page except the last is completely
48810** filled with data (pagesize - 4 bytes).  The last page can have as little
48811** as 1 byte of data.
48812**
48813**    SIZE    DESCRIPTION
48814**      4     Page number of next overflow page
48815**      *     Data
48816**
48817** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
48818** file header points to the first in a linked list of trunk page.  Each trunk
48819** page points to multiple leaf pages.  The content of a leaf page is
48820** unspecified.  A trunk page looks like this:
48821**
48822**    SIZE    DESCRIPTION
48823**      4     Page number of next trunk page
48824**      4     Number of leaf pointers on this page
48825**      *     zero or more pages numbers of leaves
48826*/
48827
48828
48829/* The following value is the maximum cell size assuming a maximum page
48830** size give above.
48831*/
48832#define MX_CELL_SIZE(pBt)  ((int)(pBt->pageSize-8))
48833
48834/* The maximum number of cells on a single page of the database.  This
48835** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
48836** plus 2 bytes for the index to the cell in the page header).  Such
48837** small cells will be rare, but they are possible.
48838*/
48839#define MX_CELL(pBt) ((pBt->pageSize-8)/6)
48840
48841/* Forward declarations */
48842typedef struct MemPage MemPage;
48843typedef struct BtLock BtLock;
48844
48845/*
48846** This is a magic string that appears at the beginning of every
48847** SQLite database in order to identify the file as a real database.
48848**
48849** You can change this value at compile-time by specifying a
48850** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
48851** header must be exactly 16 bytes including the zero-terminator so
48852** the string itself should be 15 characters long.  If you change
48853** the header, then your custom library will not be able to read
48854** databases generated by the standard tools and the standard tools
48855** will not be able to read databases created by your custom library.
48856*/
48857#ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
48858#  define SQLITE_FILE_HEADER "SQLite format 3"
48859#endif
48860
48861/*
48862** Page type flags.  An ORed combination of these flags appear as the
48863** first byte of on-disk image of every BTree page.
48864*/
48865#define PTF_INTKEY    0x01
48866#define PTF_ZERODATA  0x02
48867#define PTF_LEAFDATA  0x04
48868#define PTF_LEAF      0x08
48869
48870/*
48871** As each page of the file is loaded into memory, an instance of the following
48872** structure is appended and initialized to zero.  This structure stores
48873** information about the page that is decoded from the raw file page.
48874**
48875** The pParent field points back to the parent page.  This allows us to
48876** walk up the BTree from any leaf to the root.  Care must be taken to
48877** unref() the parent page pointer when this page is no longer referenced.
48878** The pageDestructor() routine handles that chore.
48879**
48880** Access to all fields of this structure is controlled by the mutex
48881** stored in MemPage.pBt->mutex.
48882*/
48883struct MemPage {
48884  u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
48885  u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
48886  u8 intKey;           /* True if intkey flag is set */
48887  u8 leaf;             /* True if leaf flag is set */
48888  u8 hasData;          /* True if this page stores data */
48889  u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
48890  u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
48891  u8 max1bytePayload;  /* min(maxLocal,127) */
48892  u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
48893  u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
48894  u16 cellOffset;      /* Index in aData of first cell pointer */
48895  u16 nFree;           /* Number of free bytes on the page */
48896  u16 nCell;           /* Number of cells on this page, local and ovfl */
48897  u16 maskPage;        /* Mask for page offset */
48898  u16 aiOvfl[5];       /* Insert the i-th overflow cell before the aiOvfl-th
48899                       ** non-overflow cell */
48900  u8 *apOvfl[5];       /* Pointers to the body of overflow cells */
48901  BtShared *pBt;       /* Pointer to BtShared that this page is part of */
48902  u8 *aData;           /* Pointer to disk image of the page data */
48903  u8 *aDataEnd;        /* One byte past the end of usable data */
48904  u8 *aCellIdx;        /* The cell index area */
48905  DbPage *pDbPage;     /* Pager page handle */
48906  Pgno pgno;           /* Page number for this page */
48907};
48908
48909/*
48910** The in-memory image of a disk page has the auxiliary information appended
48911** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
48912** that extra information.
48913*/
48914#define EXTRA_SIZE sizeof(MemPage)
48915
48916/*
48917** A linked list of the following structures is stored at BtShared.pLock.
48918** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
48919** is opened on the table with root page BtShared.iTable. Locks are removed
48920** from this list when a transaction is committed or rolled back, or when
48921** a btree handle is closed.
48922*/
48923struct BtLock {
48924  Btree *pBtree;        /* Btree handle holding this lock */
48925  Pgno iTable;          /* Root page of table */
48926  u8 eLock;             /* READ_LOCK or WRITE_LOCK */
48927  BtLock *pNext;        /* Next in BtShared.pLock list */
48928};
48929
48930/* Candidate values for BtLock.eLock */
48931#define READ_LOCK     1
48932#define WRITE_LOCK    2
48933
48934/* A Btree handle
48935**
48936** A database connection contains a pointer to an instance of
48937** this object for every database file that it has open.  This structure
48938** is opaque to the database connection.  The database connection cannot
48939** see the internals of this structure and only deals with pointers to
48940** this structure.
48941**
48942** For some database files, the same underlying database cache might be
48943** shared between multiple connections.  In that case, each connection
48944** has it own instance of this object.  But each instance of this object
48945** points to the same BtShared object.  The database cache and the
48946** schema associated with the database file are all contained within
48947** the BtShared object.
48948**
48949** All fields in this structure are accessed under sqlite3.mutex.
48950** The pBt pointer itself may not be changed while there exists cursors
48951** in the referenced BtShared that point back to this Btree since those
48952** cursors have to go through this Btree to find their BtShared and
48953** they often do so without holding sqlite3.mutex.
48954*/
48955struct Btree {
48956  sqlite3 *db;       /* The database connection holding this btree */
48957  BtShared *pBt;     /* Sharable content of this btree */
48958  u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
48959  u8 sharable;       /* True if we can share pBt with another db */
48960  u8 locked;         /* True if db currently has pBt locked */
48961  int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
48962  int nBackup;       /* Number of backup operations reading this btree */
48963  Btree *pNext;      /* List of other sharable Btrees from the same db */
48964  Btree *pPrev;      /* Back pointer of the same list */
48965#ifndef SQLITE_OMIT_SHARED_CACHE
48966  BtLock lock;       /* Object used to lock page 1 */
48967#endif
48968};
48969
48970/*
48971** Btree.inTrans may take one of the following values.
48972**
48973** If the shared-data extension is enabled, there may be multiple users
48974** of the Btree structure. At most one of these may open a write transaction,
48975** but any number may have active read transactions.
48976*/
48977#define TRANS_NONE  0
48978#define TRANS_READ  1
48979#define TRANS_WRITE 2
48980
48981/*
48982** An instance of this object represents a single database file.
48983**
48984** A single database file can be in use at the same time by two
48985** or more database connections.  When two or more connections are
48986** sharing the same database file, each connection has it own
48987** private Btree object for the file and each of those Btrees points
48988** to this one BtShared object.  BtShared.nRef is the number of
48989** connections currently sharing this database file.
48990**
48991** Fields in this structure are accessed under the BtShared.mutex
48992** mutex, except for nRef and pNext which are accessed under the
48993** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
48994** may not be modified once it is initially set as long as nRef>0.
48995** The pSchema field may be set once under BtShared.mutex and
48996** thereafter is unchanged as long as nRef>0.
48997**
48998** isPending:
48999**
49000**   If a BtShared client fails to obtain a write-lock on a database
49001**   table (because there exists one or more read-locks on the table),
49002**   the shared-cache enters 'pending-lock' state and isPending is
49003**   set to true.
49004**
49005**   The shared-cache leaves the 'pending lock' state when either of
49006**   the following occur:
49007**
49008**     1) The current writer (BtShared.pWriter) concludes its transaction, OR
49009**     2) The number of locks held by other connections drops to zero.
49010**
49011**   while in the 'pending-lock' state, no connection may start a new
49012**   transaction.
49013**
49014**   This feature is included to help prevent writer-starvation.
49015*/
49016struct BtShared {
49017  Pager *pPager;        /* The page cache */
49018  sqlite3 *db;          /* Database connection currently using this Btree */
49019  BtCursor *pCursor;    /* A list of all open cursors */
49020  MemPage *pPage1;      /* First page of the database */
49021  u8 openFlags;         /* Flags to sqlite3BtreeOpen() */
49022#ifndef SQLITE_OMIT_AUTOVACUUM
49023  u8 autoVacuum;        /* True if auto-vacuum is enabled */
49024  u8 incrVacuum;        /* True if incr-vacuum is enabled */
49025  u8 bDoTruncate;       /* True to truncate db on commit */
49026#endif
49027  u8 inTransaction;     /* Transaction state */
49028  u8 max1bytePayload;   /* Maximum first byte of cell for a 1-byte payload */
49029  u16 btsFlags;         /* Boolean parameters.  See BTS_* macros below */
49030  u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
49031  u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
49032  u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
49033  u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
49034  u32 pageSize;         /* Total number of bytes on a page */
49035  u32 usableSize;       /* Number of usable bytes on each page */
49036  int nTransaction;     /* Number of open transactions (read + write) */
49037  u32 nPage;            /* Number of pages in the database */
49038  void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
49039  void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
49040  sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
49041  Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
49042#ifndef SQLITE_OMIT_SHARED_CACHE
49043  int nRef;             /* Number of references to this structure */
49044  BtShared *pNext;      /* Next on a list of sharable BtShared structs */
49045  BtLock *pLock;        /* List of locks held on this shared-btree struct */
49046  Btree *pWriter;       /* Btree with currently open write transaction */
49047#endif
49048  u8 *pTmpSpace;        /* BtShared.pageSize bytes of space for tmp use */
49049};
49050
49051/*
49052** Allowed values for BtShared.btsFlags
49053*/
49054#define BTS_READ_ONLY        0x0001   /* Underlying file is readonly */
49055#define BTS_PAGESIZE_FIXED   0x0002   /* Page size can no longer be changed */
49056#define BTS_SECURE_DELETE    0x0004   /* PRAGMA secure_delete is enabled */
49057#define BTS_INITIALLY_EMPTY  0x0008   /* Database was empty at trans start */
49058#define BTS_NO_WAL           0x0010   /* Do not open write-ahead-log files */
49059#define BTS_EXCLUSIVE        0x0020   /* pWriter has an exclusive lock */
49060#define BTS_PENDING          0x0040   /* Waiting for read-locks to clear */
49061
49062/*
49063** An instance of the following structure is used to hold information
49064** about a cell.  The parseCellPtr() function fills in this structure
49065** based on information extract from the raw disk page.
49066*/
49067typedef struct CellInfo CellInfo;
49068struct CellInfo {
49069  i64 nKey;      /* The key for INTKEY tables, or number of bytes in key */
49070  u8 *pCell;     /* Pointer to the start of cell content */
49071  u32 nData;     /* Number of bytes of data */
49072  u32 nPayload;  /* Total amount of payload */
49073  u16 nHeader;   /* Size of the cell content header in bytes */
49074  u16 nLocal;    /* Amount of payload held locally */
49075  u16 iOverflow; /* Offset to overflow page number.  Zero if no overflow */
49076  u16 nSize;     /* Size of the cell content on the main b-tree page */
49077};
49078
49079/*
49080** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
49081** this will be declared corrupt. This value is calculated based on a
49082** maximum database size of 2^31 pages a minimum fanout of 2 for a
49083** root-node and 3 for all other internal nodes.
49084**
49085** If a tree that appears to be taller than this is encountered, it is
49086** assumed that the database is corrupt.
49087*/
49088#define BTCURSOR_MAX_DEPTH 20
49089
49090/*
49091** A cursor is a pointer to a particular entry within a particular
49092** b-tree within a database file.
49093**
49094** The entry is identified by its MemPage and the index in
49095** MemPage.aCell[] of the entry.
49096**
49097** A single database file can be shared by two more database connections,
49098** but cursors cannot be shared.  Each cursor is associated with a
49099** particular database connection identified BtCursor.pBtree.db.
49100**
49101** Fields in this structure are accessed under the BtShared.mutex
49102** found at self->pBt->mutex.
49103*/
49104struct BtCursor {
49105  Btree *pBtree;            /* The Btree to which this cursor belongs */
49106  BtShared *pBt;            /* The BtShared this cursor points to */
49107  BtCursor *pNext, *pPrev;  /* Forms a linked list of all cursors */
49108  struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
49109#ifndef SQLITE_OMIT_INCRBLOB
49110  Pgno *aOverflow;          /* Cache of overflow page locations */
49111#endif
49112  Pgno pgnoRoot;            /* The root page of this tree */
49113  sqlite3_int64 cachedRowid; /* Next rowid cache.  0 means not valid */
49114  CellInfo info;            /* A parse of the cell we are pointing at */
49115  i64 nKey;        /* Size of pKey, or last integer key */
49116  void *pKey;      /* Saved key that was cursor's last known position */
49117  int skipNext;    /* Prev() is noop if negative. Next() is noop if positive */
49118  u8 wrFlag;                /* True if writable */
49119  u8 atLast;                /* Cursor pointing to the last entry */
49120  u8 validNKey;             /* True if info.nKey is valid */
49121  u8 eState;                /* One of the CURSOR_XXX constants (see below) */
49122#ifndef SQLITE_OMIT_INCRBLOB
49123  u8 isIncrblobHandle;      /* True if this cursor is an incr. io handle */
49124#endif
49125  u8 hints;                             /* As configured by CursorSetHints() */
49126  i16 iPage;                            /* Index of current page in apPage */
49127  u16 aiIdx[BTCURSOR_MAX_DEPTH];        /* Current index in apPage[i] */
49128  MemPage *apPage[BTCURSOR_MAX_DEPTH];  /* Pages from root to current page */
49129};
49130
49131/*
49132** Potential values for BtCursor.eState.
49133**
49134** CURSOR_VALID:
49135**   Cursor points to a valid entry. getPayload() etc. may be called.
49136**
49137** CURSOR_INVALID:
49138**   Cursor does not point to a valid entry. This can happen (for example)
49139**   because the table is empty or because BtreeCursorFirst() has not been
49140**   called.
49141**
49142** CURSOR_REQUIRESEEK:
49143**   The table that this cursor was opened on still exists, but has been
49144**   modified since the cursor was last used. The cursor position is saved
49145**   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
49146**   this state, restoreCursorPosition() can be called to attempt to
49147**   seek the cursor to the saved position.
49148**
49149** CURSOR_FAULT:
49150**   A unrecoverable error (an I/O error or a malloc failure) has occurred
49151**   on a different connection that shares the BtShared cache with this
49152**   cursor.  The error has left the cache in an inconsistent state.
49153**   Do nothing else with this cursor.  Any attempt to use the cursor
49154**   should return the error code stored in BtCursor.skip
49155*/
49156#define CURSOR_INVALID           0
49157#define CURSOR_VALID             1
49158#define CURSOR_REQUIRESEEK       2
49159#define CURSOR_FAULT             3
49160
49161/*
49162** The database page the PENDING_BYTE occupies. This page is never used.
49163*/
49164# define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
49165
49166/*
49167** These macros define the location of the pointer-map entry for a
49168** database page. The first argument to each is the number of usable
49169** bytes on each page of the database (often 1024). The second is the
49170** page number to look up in the pointer map.
49171**
49172** PTRMAP_PAGENO returns the database page number of the pointer-map
49173** page that stores the required pointer. PTRMAP_PTROFFSET returns
49174** the offset of the requested map entry.
49175**
49176** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
49177** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
49178** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
49179** this test.
49180*/
49181#define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
49182#define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
49183#define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
49184
49185/*
49186** The pointer map is a lookup table that identifies the parent page for
49187** each child page in the database file.  The parent page is the page that
49188** contains a pointer to the child.  Every page in the database contains
49189** 0 or 1 parent pages.  (In this context 'database page' refers
49190** to any page that is not part of the pointer map itself.)  Each pointer map
49191** entry consists of a single byte 'type' and a 4 byte parent page number.
49192** The PTRMAP_XXX identifiers below are the valid types.
49193**
49194** The purpose of the pointer map is to facility moving pages from one
49195** position in the file to another as part of autovacuum.  When a page
49196** is moved, the pointer in its parent must be updated to point to the
49197** new location.  The pointer map is used to locate the parent page quickly.
49198**
49199** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
49200**                  used in this case.
49201**
49202** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
49203**                  is not used in this case.
49204**
49205** PTRMAP_OVERFLOW1: The database page is the first page in a list of
49206**                   overflow pages. The page number identifies the page that
49207**                   contains the cell with a pointer to this overflow page.
49208**
49209** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
49210**                   overflow pages. The page-number identifies the previous
49211**                   page in the overflow page list.
49212**
49213** PTRMAP_BTREE: The database page is a non-root btree page. The page number
49214**               identifies the parent page in the btree.
49215*/
49216#define PTRMAP_ROOTPAGE 1
49217#define PTRMAP_FREEPAGE 2
49218#define PTRMAP_OVERFLOW1 3
49219#define PTRMAP_OVERFLOW2 4
49220#define PTRMAP_BTREE 5
49221
49222/* A bunch of assert() statements to check the transaction state variables
49223** of handle p (type Btree*) are internally consistent.
49224*/
49225#define btreeIntegrity(p) \
49226  assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
49227  assert( p->pBt->inTransaction>=p->inTrans );
49228
49229
49230/*
49231** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
49232** if the database supports auto-vacuum or not. Because it is used
49233** within an expression that is an argument to another macro
49234** (sqliteMallocRaw), it is not possible to use conditional compilation.
49235** So, this macro is defined instead.
49236*/
49237#ifndef SQLITE_OMIT_AUTOVACUUM
49238#define ISAUTOVACUUM (pBt->autoVacuum)
49239#else
49240#define ISAUTOVACUUM 0
49241#endif
49242
49243
49244/*
49245** This structure is passed around through all the sanity checking routines
49246** in order to keep track of some global state information.
49247**
49248** The aRef[] array is allocated so that there is 1 bit for each page in
49249** the database. As the integrity-check proceeds, for each page used in
49250** the database the corresponding bit is set. This allows integrity-check to
49251** detect pages that are used twice and orphaned pages (both of which
49252** indicate corruption).
49253*/
49254typedef struct IntegrityCk IntegrityCk;
49255struct IntegrityCk {
49256  BtShared *pBt;    /* The tree being checked out */
49257  Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
49258  u8 *aPgRef;       /* 1 bit per page in the db (see above) */
49259  Pgno nPage;       /* Number of pages in the database */
49260  int mxErr;        /* Stop accumulating errors when this reaches zero */
49261  int nErr;         /* Number of messages written to zErrMsg so far */
49262  int mallocFailed; /* A memory allocation error has occurred */
49263  StrAccum errMsg;  /* Accumulate the error message text here */
49264};
49265
49266/*
49267** Routines to read or write a two- and four-byte big-endian integer values.
49268*/
49269#define get2byte(x)   ((x)[0]<<8 | (x)[1])
49270#define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
49271#define get4byte sqlite3Get4byte
49272#define put4byte sqlite3Put4byte
49273
49274/************** End of btreeInt.h ********************************************/
49275/************** Continuing where we left off in btmutex.c ********************/
49276#ifndef SQLITE_OMIT_SHARED_CACHE
49277#if SQLITE_THREADSAFE
49278
49279/*
49280** Obtain the BtShared mutex associated with B-Tree handle p. Also,
49281** set BtShared.db to the database handle associated with p and the
49282** p->locked boolean to true.
49283*/
49284static void lockBtreeMutex(Btree *p){
49285  assert( p->locked==0 );
49286  assert( sqlite3_mutex_notheld(p->pBt->mutex) );
49287  assert( sqlite3_mutex_held(p->db->mutex) );
49288
49289  sqlite3_mutex_enter(p->pBt->mutex);
49290  p->pBt->db = p->db;
49291  p->locked = 1;
49292}
49293
49294/*
49295** Release the BtShared mutex associated with B-Tree handle p and
49296** clear the p->locked boolean.
49297*/
49298static void unlockBtreeMutex(Btree *p){
49299  BtShared *pBt = p->pBt;
49300  assert( p->locked==1 );
49301  assert( sqlite3_mutex_held(pBt->mutex) );
49302  assert( sqlite3_mutex_held(p->db->mutex) );
49303  assert( p->db==pBt->db );
49304
49305  sqlite3_mutex_leave(pBt->mutex);
49306  p->locked = 0;
49307}
49308
49309/*
49310** Enter a mutex on the given BTree object.
49311**
49312** If the object is not sharable, then no mutex is ever required
49313** and this routine is a no-op.  The underlying mutex is non-recursive.
49314** But we keep a reference count in Btree.wantToLock so the behavior
49315** of this interface is recursive.
49316**
49317** To avoid deadlocks, multiple Btrees are locked in the same order
49318** by all database connections.  The p->pNext is a list of other
49319** Btrees belonging to the same database connection as the p Btree
49320** which need to be locked after p.  If we cannot get a lock on
49321** p, then first unlock all of the others on p->pNext, then wait
49322** for the lock to become available on p, then relock all of the
49323** subsequent Btrees that desire a lock.
49324*/
49325SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
49326  Btree *pLater;
49327
49328  /* Some basic sanity checking on the Btree.  The list of Btrees
49329  ** connected by pNext and pPrev should be in sorted order by
49330  ** Btree.pBt value. All elements of the list should belong to
49331  ** the same connection. Only shared Btrees are on the list. */
49332  assert( p->pNext==0 || p->pNext->pBt>p->pBt );
49333  assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
49334  assert( p->pNext==0 || p->pNext->db==p->db );
49335  assert( p->pPrev==0 || p->pPrev->db==p->db );
49336  assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
49337
49338  /* Check for locking consistency */
49339  assert( !p->locked || p->wantToLock>0 );
49340  assert( p->sharable || p->wantToLock==0 );
49341
49342  /* We should already hold a lock on the database connection */
49343  assert( sqlite3_mutex_held(p->db->mutex) );
49344
49345  /* Unless the database is sharable and unlocked, then BtShared.db
49346  ** should already be set correctly. */
49347  assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
49348
49349  if( !p->sharable ) return;
49350  p->wantToLock++;
49351  if( p->locked ) return;
49352
49353  /* In most cases, we should be able to acquire the lock we
49354  ** want without having to go throught the ascending lock
49355  ** procedure that follows.  Just be sure not to block.
49356  */
49357  if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
49358    p->pBt->db = p->db;
49359    p->locked = 1;
49360    return;
49361  }
49362
49363  /* To avoid deadlock, first release all locks with a larger
49364  ** BtShared address.  Then acquire our lock.  Then reacquire
49365  ** the other BtShared locks that we used to hold in ascending
49366  ** order.
49367  */
49368  for(pLater=p->pNext; pLater; pLater=pLater->pNext){
49369    assert( pLater->sharable );
49370    assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
49371    assert( !pLater->locked || pLater->wantToLock>0 );
49372    if( pLater->locked ){
49373      unlockBtreeMutex(pLater);
49374    }
49375  }
49376  lockBtreeMutex(p);
49377  for(pLater=p->pNext; pLater; pLater=pLater->pNext){
49378    if( pLater->wantToLock ){
49379      lockBtreeMutex(pLater);
49380    }
49381  }
49382}
49383
49384/*
49385** Exit the recursive mutex on a Btree.
49386*/
49387SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
49388  if( p->sharable ){
49389    assert( p->wantToLock>0 );
49390    p->wantToLock--;
49391    if( p->wantToLock==0 ){
49392      unlockBtreeMutex(p);
49393    }
49394  }
49395}
49396
49397#ifndef NDEBUG
49398/*
49399** Return true if the BtShared mutex is held on the btree, or if the
49400** B-Tree is not marked as sharable.
49401**
49402** This routine is used only from within assert() statements.
49403*/
49404SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
49405  assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
49406  assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
49407  assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
49408  assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
49409
49410  return (p->sharable==0 || p->locked);
49411}
49412#endif
49413
49414
49415#ifndef SQLITE_OMIT_INCRBLOB
49416/*
49417** Enter and leave a mutex on a Btree given a cursor owned by that
49418** Btree.  These entry points are used by incremental I/O and can be
49419** omitted if that module is not used.
49420*/
49421SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
49422  sqlite3BtreeEnter(pCur->pBtree);
49423}
49424SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
49425  sqlite3BtreeLeave(pCur->pBtree);
49426}
49427#endif /* SQLITE_OMIT_INCRBLOB */
49428
49429
49430/*
49431** Enter the mutex on every Btree associated with a database
49432** connection.  This is needed (for example) prior to parsing
49433** a statement since we will be comparing table and column names
49434** against all schemas and we do not want those schemas being
49435** reset out from under us.
49436**
49437** There is a corresponding leave-all procedures.
49438**
49439** Enter the mutexes in accending order by BtShared pointer address
49440** to avoid the possibility of deadlock when two threads with
49441** two or more btrees in common both try to lock all their btrees
49442** at the same instant.
49443*/
49444SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
49445  int i;
49446  Btree *p;
49447  assert( sqlite3_mutex_held(db->mutex) );
49448  for(i=0; i<db->nDb; i++){
49449    p = db->aDb[i].pBt;
49450    if( p ) sqlite3BtreeEnter(p);
49451  }
49452}
49453SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
49454  int i;
49455  Btree *p;
49456  assert( sqlite3_mutex_held(db->mutex) );
49457  for(i=0; i<db->nDb; i++){
49458    p = db->aDb[i].pBt;
49459    if( p ) sqlite3BtreeLeave(p);
49460  }
49461}
49462
49463/*
49464** Return true if a particular Btree requires a lock.  Return FALSE if
49465** no lock is ever required since it is not sharable.
49466*/
49467SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
49468  return p->sharable;
49469}
49470
49471#ifndef NDEBUG
49472/*
49473** Return true if the current thread holds the database connection
49474** mutex and all required BtShared mutexes.
49475**
49476** This routine is used inside assert() statements only.
49477*/
49478SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
49479  int i;
49480  if( !sqlite3_mutex_held(db->mutex) ){
49481    return 0;
49482  }
49483  for(i=0; i<db->nDb; i++){
49484    Btree *p;
49485    p = db->aDb[i].pBt;
49486    if( p && p->sharable &&
49487         (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
49488      return 0;
49489    }
49490  }
49491  return 1;
49492}
49493#endif /* NDEBUG */
49494
49495#ifndef NDEBUG
49496/*
49497** Return true if the correct mutexes are held for accessing the
49498** db->aDb[iDb].pSchema structure.  The mutexes required for schema
49499** access are:
49500**
49501**   (1) The mutex on db
49502**   (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
49503**
49504** If pSchema is not NULL, then iDb is computed from pSchema and
49505** db using sqlite3SchemaToIndex().
49506*/
49507SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
49508  Btree *p;
49509  assert( db!=0 );
49510  if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
49511  assert( iDb>=0 && iDb<db->nDb );
49512  if( !sqlite3_mutex_held(db->mutex) ) return 0;
49513  if( iDb==1 ) return 1;
49514  p = db->aDb[iDb].pBt;
49515  assert( p!=0 );
49516  return p->sharable==0 || p->locked==1;
49517}
49518#endif /* NDEBUG */
49519
49520#else /* SQLITE_THREADSAFE>0 above.  SQLITE_THREADSAFE==0 below */
49521/*
49522** The following are special cases for mutex enter routines for use
49523** in single threaded applications that use shared cache.  Except for
49524** these two routines, all mutex operations are no-ops in that case and
49525** are null #defines in btree.h.
49526**
49527** If shared cache is disabled, then all btree mutex routines, including
49528** the ones below, are no-ops and are null #defines in btree.h.
49529*/
49530
49531SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
49532  p->pBt->db = p->db;
49533}
49534SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
49535  int i;
49536  for(i=0; i<db->nDb; i++){
49537    Btree *p = db->aDb[i].pBt;
49538    if( p ){
49539      p->pBt->db = p->db;
49540    }
49541  }
49542}
49543#endif /* if SQLITE_THREADSAFE */
49544#endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
49545
49546/************** End of btmutex.c *********************************************/
49547/************** Begin file btree.c *******************************************/
49548/*
49549** 2004 April 6
49550**
49551** The author disclaims copyright to this source code.  In place of
49552** a legal notice, here is a blessing:
49553**
49554**    May you do good and not evil.
49555**    May you find forgiveness for yourself and forgive others.
49556**    May you share freely, never taking more than you give.
49557**
49558*************************************************************************
49559** This file implements a external (disk-based) database using BTrees.
49560** See the header comment on "btreeInt.h" for additional information.
49561** Including a description of file format and an overview of operation.
49562*/
49563
49564/*
49565** The header string that appears at the beginning of every
49566** SQLite database.
49567*/
49568static const char zMagicHeader[] = SQLITE_FILE_HEADER;
49569
49570/*
49571** Set this global variable to 1 to enable tracing using the TRACE
49572** macro.
49573*/
49574#if 0
49575int sqlite3BtreeTrace=1;  /* True to enable tracing */
49576# define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
49577#else
49578# define TRACE(X)
49579#endif
49580
49581/*
49582** Extract a 2-byte big-endian integer from an array of unsigned bytes.
49583** But if the value is zero, make it 65536.
49584**
49585** This routine is used to extract the "offset to cell content area" value
49586** from the header of a btree page.  If the page size is 65536 and the page
49587** is empty, the offset should be 65536, but the 2-byte value stores zero.
49588** This routine makes the necessary adjustment to 65536.
49589*/
49590#define get2byteNotZero(X)  (((((int)get2byte(X))-1)&0xffff)+1)
49591
49592/*
49593** Values passed as the 5th argument to allocateBtreePage()
49594*/
49595#define BTALLOC_ANY   0           /* Allocate any page */
49596#define BTALLOC_EXACT 1           /* Allocate exact page if possible */
49597#define BTALLOC_LE    2           /* Allocate any page <= the parameter */
49598
49599/*
49600** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
49601** defined, or 0 if it is. For example:
49602**
49603**   bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
49604*/
49605#ifndef SQLITE_OMIT_AUTOVACUUM
49606#define IfNotOmitAV(expr) (expr)
49607#else
49608#define IfNotOmitAV(expr) 0
49609#endif
49610
49611#ifndef SQLITE_OMIT_SHARED_CACHE
49612/*
49613** A list of BtShared objects that are eligible for participation
49614** in shared cache.  This variable has file scope during normal builds,
49615** but the test harness needs to access it so we make it global for
49616** test builds.
49617**
49618** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
49619*/
49620#ifdef SQLITE_TEST
49621SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
49622#else
49623static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
49624#endif
49625#endif /* SQLITE_OMIT_SHARED_CACHE */
49626
49627#ifndef SQLITE_OMIT_SHARED_CACHE
49628/*
49629** Enable or disable the shared pager and schema features.
49630**
49631** This routine has no effect on existing database connections.
49632** The shared cache setting effects only future calls to
49633** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
49634*/
49635SQLITE_API int sqlite3_enable_shared_cache(int enable){
49636  sqlite3GlobalConfig.sharedCacheEnabled = enable;
49637  return SQLITE_OK;
49638}
49639#endif
49640
49641
49642
49643#ifdef SQLITE_OMIT_SHARED_CACHE
49644  /*
49645  ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
49646  ** and clearAllSharedCacheTableLocks()
49647  ** manipulate entries in the BtShared.pLock linked list used to store
49648  ** shared-cache table level locks. If the library is compiled with the
49649  ** shared-cache feature disabled, then there is only ever one user
49650  ** of each BtShared structure and so this locking is not necessary.
49651  ** So define the lock related functions as no-ops.
49652  */
49653  #define querySharedCacheTableLock(a,b,c) SQLITE_OK
49654  #define setSharedCacheTableLock(a,b,c) SQLITE_OK
49655  #define clearAllSharedCacheTableLocks(a)
49656  #define downgradeAllSharedCacheTableLocks(a)
49657  #define hasSharedCacheTableLock(a,b,c,d) 1
49658  #define hasReadConflicts(a, b) 0
49659#endif
49660
49661#ifndef SQLITE_OMIT_SHARED_CACHE
49662
49663#ifdef SQLITE_DEBUG
49664/*
49665**** This function is only used as part of an assert() statement. ***
49666**
49667** Check to see if pBtree holds the required locks to read or write to the
49668** table with root page iRoot.   Return 1 if it does and 0 if not.
49669**
49670** For example, when writing to a table with root-page iRoot via
49671** Btree connection pBtree:
49672**
49673**    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
49674**
49675** When writing to an index that resides in a sharable database, the
49676** caller should have first obtained a lock specifying the root page of
49677** the corresponding table. This makes things a bit more complicated,
49678** as this module treats each table as a separate structure. To determine
49679** the table corresponding to the index being written, this
49680** function has to search through the database schema.
49681**
49682** Instead of a lock on the table/index rooted at page iRoot, the caller may
49683** hold a write-lock on the schema table (root page 1). This is also
49684** acceptable.
49685*/
49686static int hasSharedCacheTableLock(
49687  Btree *pBtree,         /* Handle that must hold lock */
49688  Pgno iRoot,            /* Root page of b-tree */
49689  int isIndex,           /* True if iRoot is the root of an index b-tree */
49690  int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
49691){
49692  Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
49693  Pgno iTab = 0;
49694  BtLock *pLock;
49695
49696  /* If this database is not shareable, or if the client is reading
49697  ** and has the read-uncommitted flag set, then no lock is required.
49698  ** Return true immediately.
49699  */
49700  if( (pBtree->sharable==0)
49701   || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
49702  ){
49703    return 1;
49704  }
49705
49706  /* If the client is reading  or writing an index and the schema is
49707  ** not loaded, then it is too difficult to actually check to see if
49708  ** the correct locks are held.  So do not bother - just return true.
49709  ** This case does not come up very often anyhow.
49710  */
49711  if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){
49712    return 1;
49713  }
49714
49715  /* Figure out the root-page that the lock should be held on. For table
49716  ** b-trees, this is just the root page of the b-tree being read or
49717  ** written. For index b-trees, it is the root page of the associated
49718  ** table.  */
49719  if( isIndex ){
49720    HashElem *p;
49721    for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
49722      Index *pIdx = (Index *)sqliteHashData(p);
49723      if( pIdx->tnum==(int)iRoot ){
49724        iTab = pIdx->pTable->tnum;
49725      }
49726    }
49727  }else{
49728    iTab = iRoot;
49729  }
49730
49731  /* Search for the required lock. Either a write-lock on root-page iTab, a
49732  ** write-lock on the schema table, or (if the client is reading) a
49733  ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
49734  for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
49735    if( pLock->pBtree==pBtree
49736     && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
49737     && pLock->eLock>=eLockType
49738    ){
49739      return 1;
49740    }
49741  }
49742
49743  /* Failed to find the required lock. */
49744  return 0;
49745}
49746#endif /* SQLITE_DEBUG */
49747
49748#ifdef SQLITE_DEBUG
49749/*
49750**** This function may be used as part of assert() statements only. ****
49751**
49752** Return true if it would be illegal for pBtree to write into the
49753** table or index rooted at iRoot because other shared connections are
49754** simultaneously reading that same table or index.
49755**
49756** It is illegal for pBtree to write if some other Btree object that
49757** shares the same BtShared object is currently reading or writing
49758** the iRoot table.  Except, if the other Btree object has the
49759** read-uncommitted flag set, then it is OK for the other object to
49760** have a read cursor.
49761**
49762** For example, before writing to any part of the table or index
49763** rooted at page iRoot, one should call:
49764**
49765**    assert( !hasReadConflicts(pBtree, iRoot) );
49766*/
49767static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
49768  BtCursor *p;
49769  for(p=pBtree->pBt->pCursor; p; p=p->pNext){
49770    if( p->pgnoRoot==iRoot
49771     && p->pBtree!=pBtree
49772     && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
49773    ){
49774      return 1;
49775    }
49776  }
49777  return 0;
49778}
49779#endif    /* #ifdef SQLITE_DEBUG */
49780
49781/*
49782** Query to see if Btree handle p may obtain a lock of type eLock
49783** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
49784** SQLITE_OK if the lock may be obtained (by calling
49785** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
49786*/
49787static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
49788  BtShared *pBt = p->pBt;
49789  BtLock *pIter;
49790
49791  assert( sqlite3BtreeHoldsMutex(p) );
49792  assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
49793  assert( p->db!=0 );
49794  assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
49795
49796  /* If requesting a write-lock, then the Btree must have an open write
49797  ** transaction on this file. And, obviously, for this to be so there
49798  ** must be an open write transaction on the file itself.
49799  */
49800  assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
49801  assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
49802
49803  /* This routine is a no-op if the shared-cache is not enabled */
49804  if( !p->sharable ){
49805    return SQLITE_OK;
49806  }
49807
49808  /* If some other connection is holding an exclusive lock, the
49809  ** requested lock may not be obtained.
49810  */
49811  if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
49812    sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
49813    return SQLITE_LOCKED_SHAREDCACHE;
49814  }
49815
49816  for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
49817    /* The condition (pIter->eLock!=eLock) in the following if(...)
49818    ** statement is a simplification of:
49819    **
49820    **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
49821    **
49822    ** since we know that if eLock==WRITE_LOCK, then no other connection
49823    ** may hold a WRITE_LOCK on any table in this file (since there can
49824    ** only be a single writer).
49825    */
49826    assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
49827    assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
49828    if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
49829      sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
49830      if( eLock==WRITE_LOCK ){
49831        assert( p==pBt->pWriter );
49832        pBt->btsFlags |= BTS_PENDING;
49833      }
49834      return SQLITE_LOCKED_SHAREDCACHE;
49835    }
49836  }
49837  return SQLITE_OK;
49838}
49839#endif /* !SQLITE_OMIT_SHARED_CACHE */
49840
49841#ifndef SQLITE_OMIT_SHARED_CACHE
49842/*
49843** Add a lock on the table with root-page iTable to the shared-btree used
49844** by Btree handle p. Parameter eLock must be either READ_LOCK or
49845** WRITE_LOCK.
49846**
49847** This function assumes the following:
49848**
49849**   (a) The specified Btree object p is connected to a sharable
49850**       database (one with the BtShared.sharable flag set), and
49851**
49852**   (b) No other Btree objects hold a lock that conflicts
49853**       with the requested lock (i.e. querySharedCacheTableLock() has
49854**       already been called and returned SQLITE_OK).
49855**
49856** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
49857** is returned if a malloc attempt fails.
49858*/
49859static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
49860  BtShared *pBt = p->pBt;
49861  BtLock *pLock = 0;
49862  BtLock *pIter;
49863
49864  assert( sqlite3BtreeHoldsMutex(p) );
49865  assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
49866  assert( p->db!=0 );
49867
49868  /* A connection with the read-uncommitted flag set will never try to
49869  ** obtain a read-lock using this function. The only read-lock obtained
49870  ** by a connection in read-uncommitted mode is on the sqlite_master
49871  ** table, and that lock is obtained in BtreeBeginTrans().  */
49872  assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
49873
49874  /* This function should only be called on a sharable b-tree after it
49875  ** has been determined that no other b-tree holds a conflicting lock.  */
49876  assert( p->sharable );
49877  assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
49878
49879  /* First search the list for an existing lock on this table. */
49880  for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
49881    if( pIter->iTable==iTable && pIter->pBtree==p ){
49882      pLock = pIter;
49883      break;
49884    }
49885  }
49886
49887  /* If the above search did not find a BtLock struct associating Btree p
49888  ** with table iTable, allocate one and link it into the list.
49889  */
49890  if( !pLock ){
49891    pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
49892    if( !pLock ){
49893      return SQLITE_NOMEM;
49894    }
49895    pLock->iTable = iTable;
49896    pLock->pBtree = p;
49897    pLock->pNext = pBt->pLock;
49898    pBt->pLock = pLock;
49899  }
49900
49901  /* Set the BtLock.eLock variable to the maximum of the current lock
49902  ** and the requested lock. This means if a write-lock was already held
49903  ** and a read-lock requested, we don't incorrectly downgrade the lock.
49904  */
49905  assert( WRITE_LOCK>READ_LOCK );
49906  if( eLock>pLock->eLock ){
49907    pLock->eLock = eLock;
49908  }
49909
49910  return SQLITE_OK;
49911}
49912#endif /* !SQLITE_OMIT_SHARED_CACHE */
49913
49914#ifndef SQLITE_OMIT_SHARED_CACHE
49915/*
49916** Release all the table locks (locks obtained via calls to
49917** the setSharedCacheTableLock() procedure) held by Btree object p.
49918**
49919** This function assumes that Btree p has an open read or write
49920** transaction. If it does not, then the BTS_PENDING flag
49921** may be incorrectly cleared.
49922*/
49923static void clearAllSharedCacheTableLocks(Btree *p){
49924  BtShared *pBt = p->pBt;
49925  BtLock **ppIter = &pBt->pLock;
49926
49927  assert( sqlite3BtreeHoldsMutex(p) );
49928  assert( p->sharable || 0==*ppIter );
49929  assert( p->inTrans>0 );
49930
49931  while( *ppIter ){
49932    BtLock *pLock = *ppIter;
49933    assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
49934    assert( pLock->pBtree->inTrans>=pLock->eLock );
49935    if( pLock->pBtree==p ){
49936      *ppIter = pLock->pNext;
49937      assert( pLock->iTable!=1 || pLock==&p->lock );
49938      if( pLock->iTable!=1 ){
49939        sqlite3_free(pLock);
49940      }
49941    }else{
49942      ppIter = &pLock->pNext;
49943    }
49944  }
49945
49946  assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
49947  if( pBt->pWriter==p ){
49948    pBt->pWriter = 0;
49949    pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
49950  }else if( pBt->nTransaction==2 ){
49951    /* This function is called when Btree p is concluding its
49952    ** transaction. If there currently exists a writer, and p is not
49953    ** that writer, then the number of locks held by connections other
49954    ** than the writer must be about to drop to zero. In this case
49955    ** set the BTS_PENDING flag to 0.
49956    **
49957    ** If there is not currently a writer, then BTS_PENDING must
49958    ** be zero already. So this next line is harmless in that case.
49959    */
49960    pBt->btsFlags &= ~BTS_PENDING;
49961  }
49962}
49963
49964/*
49965** This function changes all write-locks held by Btree p into read-locks.
49966*/
49967static void downgradeAllSharedCacheTableLocks(Btree *p){
49968  BtShared *pBt = p->pBt;
49969  if( pBt->pWriter==p ){
49970    BtLock *pLock;
49971    pBt->pWriter = 0;
49972    pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
49973    for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
49974      assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
49975      pLock->eLock = READ_LOCK;
49976    }
49977  }
49978}
49979
49980#endif /* SQLITE_OMIT_SHARED_CACHE */
49981
49982static void releasePage(MemPage *pPage);  /* Forward reference */
49983
49984/*
49985***** This routine is used inside of assert() only ****
49986**
49987** Verify that the cursor holds the mutex on its BtShared
49988*/
49989#ifdef SQLITE_DEBUG
49990static int cursorHoldsMutex(BtCursor *p){
49991  return sqlite3_mutex_held(p->pBt->mutex);
49992}
49993#endif
49994
49995
49996#ifndef SQLITE_OMIT_INCRBLOB
49997/*
49998** Invalidate the overflow page-list cache for cursor pCur, if any.
49999*/
50000static void invalidateOverflowCache(BtCursor *pCur){
50001  assert( cursorHoldsMutex(pCur) );
50002  sqlite3_free(pCur->aOverflow);
50003  pCur->aOverflow = 0;
50004}
50005
50006/*
50007** Invalidate the overflow page-list cache for all cursors opened
50008** on the shared btree structure pBt.
50009*/
50010static void invalidateAllOverflowCache(BtShared *pBt){
50011  BtCursor *p;
50012  assert( sqlite3_mutex_held(pBt->mutex) );
50013  for(p=pBt->pCursor; p; p=p->pNext){
50014    invalidateOverflowCache(p);
50015  }
50016}
50017
50018/*
50019** This function is called before modifying the contents of a table
50020** to invalidate any incrblob cursors that are open on the
50021** row or one of the rows being modified.
50022**
50023** If argument isClearTable is true, then the entire contents of the
50024** table is about to be deleted. In this case invalidate all incrblob
50025** cursors open on any row within the table with root-page pgnoRoot.
50026**
50027** Otherwise, if argument isClearTable is false, then the row with
50028** rowid iRow is being replaced or deleted. In this case invalidate
50029** only those incrblob cursors open on that specific row.
50030*/
50031static void invalidateIncrblobCursors(
50032  Btree *pBtree,          /* The database file to check */
50033  i64 iRow,               /* The rowid that might be changing */
50034  int isClearTable        /* True if all rows are being deleted */
50035){
50036  BtCursor *p;
50037  BtShared *pBt = pBtree->pBt;
50038  assert( sqlite3BtreeHoldsMutex(pBtree) );
50039  for(p=pBt->pCursor; p; p=p->pNext){
50040    if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){
50041      p->eState = CURSOR_INVALID;
50042    }
50043  }
50044}
50045
50046#else
50047  /* Stub functions when INCRBLOB is omitted */
50048  #define invalidateOverflowCache(x)
50049  #define invalidateAllOverflowCache(x)
50050  #define invalidateIncrblobCursors(x,y,z)
50051#endif /* SQLITE_OMIT_INCRBLOB */
50052
50053/*
50054** Set bit pgno of the BtShared.pHasContent bitvec. This is called
50055** when a page that previously contained data becomes a free-list leaf
50056** page.
50057**
50058** The BtShared.pHasContent bitvec exists to work around an obscure
50059** bug caused by the interaction of two useful IO optimizations surrounding
50060** free-list leaf pages:
50061**
50062**   1) When all data is deleted from a page and the page becomes
50063**      a free-list leaf page, the page is not written to the database
50064**      (as free-list leaf pages contain no meaningful data). Sometimes
50065**      such a page is not even journalled (as it will not be modified,
50066**      why bother journalling it?).
50067**
50068**   2) When a free-list leaf page is reused, its content is not read
50069**      from the database or written to the journal file (why should it
50070**      be, if it is not at all meaningful?).
50071**
50072** By themselves, these optimizations work fine and provide a handy
50073** performance boost to bulk delete or insert operations. However, if
50074** a page is moved to the free-list and then reused within the same
50075** transaction, a problem comes up. If the page is not journalled when
50076** it is moved to the free-list and it is also not journalled when it
50077** is extracted from the free-list and reused, then the original data
50078** may be lost. In the event of a rollback, it may not be possible
50079** to restore the database to its original configuration.
50080**
50081** The solution is the BtShared.pHasContent bitvec. Whenever a page is
50082** moved to become a free-list leaf page, the corresponding bit is
50083** set in the bitvec. Whenever a leaf page is extracted from the free-list,
50084** optimization 2 above is omitted if the corresponding bit is already
50085** set in BtShared.pHasContent. The contents of the bitvec are cleared
50086** at the end of every transaction.
50087*/
50088static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
50089  int rc = SQLITE_OK;
50090  if( !pBt->pHasContent ){
50091    assert( pgno<=pBt->nPage );
50092    pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
50093    if( !pBt->pHasContent ){
50094      rc = SQLITE_NOMEM;
50095    }
50096  }
50097  if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
50098    rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
50099  }
50100  return rc;
50101}
50102
50103/*
50104** Query the BtShared.pHasContent vector.
50105**
50106** This function is called when a free-list leaf page is removed from the
50107** free-list for reuse. It returns false if it is safe to retrieve the
50108** page from the pager layer with the 'no-content' flag set. True otherwise.
50109*/
50110static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
50111  Bitvec *p = pBt->pHasContent;
50112  return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
50113}
50114
50115/*
50116** Clear (destroy) the BtShared.pHasContent bitvec. This should be
50117** invoked at the conclusion of each write-transaction.
50118*/
50119static void btreeClearHasContent(BtShared *pBt){
50120  sqlite3BitvecDestroy(pBt->pHasContent);
50121  pBt->pHasContent = 0;
50122}
50123
50124/*
50125** Release all of the apPage[] pages for a cursor.
50126*/
50127static void btreeReleaseAllCursorPages(BtCursor *pCur){
50128  int i;
50129  for(i=0; i<=pCur->iPage; i++){
50130    releasePage(pCur->apPage[i]);
50131    pCur->apPage[i] = 0;
50132  }
50133  pCur->iPage = -1;
50134}
50135
50136
50137/*
50138** Save the current cursor position in the variables BtCursor.nKey
50139** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
50140**
50141** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
50142** prior to calling this routine.
50143*/
50144static int saveCursorPosition(BtCursor *pCur){
50145  int rc;
50146
50147  assert( CURSOR_VALID==pCur->eState );
50148  assert( 0==pCur->pKey );
50149  assert( cursorHoldsMutex(pCur) );
50150
50151  rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
50152  assert( rc==SQLITE_OK );  /* KeySize() cannot fail */
50153
50154  /* If this is an intKey table, then the above call to BtreeKeySize()
50155  ** stores the integer key in pCur->nKey. In this case this value is
50156  ** all that is required. Otherwise, if pCur is not open on an intKey
50157  ** table, then malloc space for and store the pCur->nKey bytes of key
50158  ** data.
50159  */
50160  if( 0==pCur->apPage[0]->intKey ){
50161    void *pKey = sqlite3Malloc( (int)pCur->nKey );
50162    if( pKey ){
50163      rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
50164      if( rc==SQLITE_OK ){
50165        pCur->pKey = pKey;
50166      }else{
50167        sqlite3_free(pKey);
50168      }
50169    }else{
50170      rc = SQLITE_NOMEM;
50171    }
50172  }
50173  assert( !pCur->apPage[0]->intKey || !pCur->pKey );
50174
50175  if( rc==SQLITE_OK ){
50176    btreeReleaseAllCursorPages(pCur);
50177    pCur->eState = CURSOR_REQUIRESEEK;
50178  }
50179
50180  invalidateOverflowCache(pCur);
50181  return rc;
50182}
50183
50184/*
50185** Save the positions of all cursors (except pExcept) that are open on
50186** the table  with root-page iRoot. Usually, this is called just before cursor
50187** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
50188*/
50189static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
50190  BtCursor *p;
50191  assert( sqlite3_mutex_held(pBt->mutex) );
50192  assert( pExcept==0 || pExcept->pBt==pBt );
50193  for(p=pBt->pCursor; p; p=p->pNext){
50194    if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
50195      if( p->eState==CURSOR_VALID ){
50196        int rc = saveCursorPosition(p);
50197        if( SQLITE_OK!=rc ){
50198          return rc;
50199        }
50200      }else{
50201        testcase( p->iPage>0 );
50202        btreeReleaseAllCursorPages(p);
50203      }
50204    }
50205  }
50206  return SQLITE_OK;
50207}
50208
50209/*
50210** Clear the current cursor position.
50211*/
50212SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
50213  assert( cursorHoldsMutex(pCur) );
50214  sqlite3_free(pCur->pKey);
50215  pCur->pKey = 0;
50216  pCur->eState = CURSOR_INVALID;
50217}
50218
50219/*
50220** In this version of BtreeMoveto, pKey is a packed index record
50221** such as is generated by the OP_MakeRecord opcode.  Unpack the
50222** record and then call BtreeMovetoUnpacked() to do the work.
50223*/
50224static int btreeMoveto(
50225  BtCursor *pCur,     /* Cursor open on the btree to be searched */
50226  const void *pKey,   /* Packed key if the btree is an index */
50227  i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
50228  int bias,           /* Bias search to the high end */
50229  int *pRes           /* Write search results here */
50230){
50231  int rc;                    /* Status code */
50232  UnpackedRecord *pIdxKey;   /* Unpacked index key */
50233  char aSpace[150];          /* Temp space for pIdxKey - to avoid a malloc */
50234  char *pFree = 0;
50235
50236  if( pKey ){
50237    assert( nKey==(i64)(int)nKey );
50238    pIdxKey = sqlite3VdbeAllocUnpackedRecord(
50239        pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
50240    );
50241    if( pIdxKey==0 ) return SQLITE_NOMEM;
50242    sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
50243  }else{
50244    pIdxKey = 0;
50245  }
50246  rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
50247  if( pFree ){
50248    sqlite3DbFree(pCur->pKeyInfo->db, pFree);
50249  }
50250  return rc;
50251}
50252
50253/*
50254** Restore the cursor to the position it was in (or as close to as possible)
50255** when saveCursorPosition() was called. Note that this call deletes the
50256** saved position info stored by saveCursorPosition(), so there can be
50257** at most one effective restoreCursorPosition() call after each
50258** saveCursorPosition().
50259*/
50260static int btreeRestoreCursorPosition(BtCursor *pCur){
50261  int rc;
50262  assert( cursorHoldsMutex(pCur) );
50263  assert( pCur->eState>=CURSOR_REQUIRESEEK );
50264  if( pCur->eState==CURSOR_FAULT ){
50265    return pCur->skipNext;
50266  }
50267  pCur->eState = CURSOR_INVALID;
50268  rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
50269  if( rc==SQLITE_OK ){
50270    sqlite3_free(pCur->pKey);
50271    pCur->pKey = 0;
50272    assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
50273  }
50274  return rc;
50275}
50276
50277#define restoreCursorPosition(p) \
50278  (p->eState>=CURSOR_REQUIRESEEK ? \
50279         btreeRestoreCursorPosition(p) : \
50280         SQLITE_OK)
50281
50282/*
50283** Determine whether or not a cursor has moved from the position it
50284** was last placed at.  Cursors can move when the row they are pointing
50285** at is deleted out from under them.
50286**
50287** This routine returns an error code if something goes wrong.  The
50288** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
50289*/
50290SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
50291  int rc;
50292
50293  rc = restoreCursorPosition(pCur);
50294  if( rc ){
50295    *pHasMoved = 1;
50296    return rc;
50297  }
50298  if( pCur->eState!=CURSOR_VALID || pCur->skipNext!=0 ){
50299    *pHasMoved = 1;
50300  }else{
50301    *pHasMoved = 0;
50302  }
50303  return SQLITE_OK;
50304}
50305
50306#ifndef SQLITE_OMIT_AUTOVACUUM
50307/*
50308** Given a page number of a regular database page, return the page
50309** number for the pointer-map page that contains the entry for the
50310** input page number.
50311**
50312** Return 0 (not a valid page) for pgno==1 since there is
50313** no pointer map associated with page 1.  The integrity_check logic
50314** requires that ptrmapPageno(*,1)!=1.
50315*/
50316static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
50317  int nPagesPerMapPage;
50318  Pgno iPtrMap, ret;
50319  assert( sqlite3_mutex_held(pBt->mutex) );
50320  if( pgno<2 ) return 0;
50321  nPagesPerMapPage = (pBt->usableSize/5)+1;
50322  iPtrMap = (pgno-2)/nPagesPerMapPage;
50323  ret = (iPtrMap*nPagesPerMapPage) + 2;
50324  if( ret==PENDING_BYTE_PAGE(pBt) ){
50325    ret++;
50326  }
50327  return ret;
50328}
50329
50330/*
50331** Write an entry into the pointer map.
50332**
50333** This routine updates the pointer map entry for page number 'key'
50334** so that it maps to type 'eType' and parent page number 'pgno'.
50335**
50336** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
50337** a no-op.  If an error occurs, the appropriate error code is written
50338** into *pRC.
50339*/
50340static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
50341  DbPage *pDbPage;  /* The pointer map page */
50342  u8 *pPtrmap;      /* The pointer map data */
50343  Pgno iPtrmap;     /* The pointer map page number */
50344  int offset;       /* Offset in pointer map page */
50345  int rc;           /* Return code from subfunctions */
50346
50347  if( *pRC ) return;
50348
50349  assert( sqlite3_mutex_held(pBt->mutex) );
50350  /* The master-journal page number must never be used as a pointer map page */
50351  assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
50352
50353  assert( pBt->autoVacuum );
50354  if( key==0 ){
50355    *pRC = SQLITE_CORRUPT_BKPT;
50356    return;
50357  }
50358  iPtrmap = PTRMAP_PAGENO(pBt, key);
50359  rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
50360  if( rc!=SQLITE_OK ){
50361    *pRC = rc;
50362    return;
50363  }
50364  offset = PTRMAP_PTROFFSET(iPtrmap, key);
50365  if( offset<0 ){
50366    *pRC = SQLITE_CORRUPT_BKPT;
50367    goto ptrmap_exit;
50368  }
50369  assert( offset <= (int)pBt->usableSize-5 );
50370  pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
50371
50372  if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
50373    TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
50374    *pRC= rc = sqlite3PagerWrite(pDbPage);
50375    if( rc==SQLITE_OK ){
50376      pPtrmap[offset] = eType;
50377      put4byte(&pPtrmap[offset+1], parent);
50378    }
50379  }
50380
50381ptrmap_exit:
50382  sqlite3PagerUnref(pDbPage);
50383}
50384
50385/*
50386** Read an entry from the pointer map.
50387**
50388** This routine retrieves the pointer map entry for page 'key', writing
50389** the type and parent page number to *pEType and *pPgno respectively.
50390** An error code is returned if something goes wrong, otherwise SQLITE_OK.
50391*/
50392static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
50393  DbPage *pDbPage;   /* The pointer map page */
50394  int iPtrmap;       /* Pointer map page index */
50395  u8 *pPtrmap;       /* Pointer map page data */
50396  int offset;        /* Offset of entry in pointer map */
50397  int rc;
50398
50399  assert( sqlite3_mutex_held(pBt->mutex) );
50400
50401  iPtrmap = PTRMAP_PAGENO(pBt, key);
50402  rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
50403  if( rc!=0 ){
50404    return rc;
50405  }
50406  pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
50407
50408  offset = PTRMAP_PTROFFSET(iPtrmap, key);
50409  if( offset<0 ){
50410    sqlite3PagerUnref(pDbPage);
50411    return SQLITE_CORRUPT_BKPT;
50412  }
50413  assert( offset <= (int)pBt->usableSize-5 );
50414  assert( pEType!=0 );
50415  *pEType = pPtrmap[offset];
50416  if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
50417
50418  sqlite3PagerUnref(pDbPage);
50419  if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
50420  return SQLITE_OK;
50421}
50422
50423#else /* if defined SQLITE_OMIT_AUTOVACUUM */
50424  #define ptrmapPut(w,x,y,z,rc)
50425  #define ptrmapGet(w,x,y,z) SQLITE_OK
50426  #define ptrmapPutOvflPtr(x, y, rc)
50427#endif
50428
50429/*
50430** Given a btree page and a cell index (0 means the first cell on
50431** the page, 1 means the second cell, and so forth) return a pointer
50432** to the cell content.
50433**
50434** This routine works only for pages that do not contain overflow cells.
50435*/
50436#define findCell(P,I) \
50437  ((P)->aData + ((P)->maskPage & get2byte(&(P)->aCellIdx[2*(I)])))
50438#define findCellv2(D,M,O,I) (D+(M&get2byte(D+(O+2*(I)))))
50439
50440
50441/*
50442** This a more complex version of findCell() that works for
50443** pages that do contain overflow cells.
50444*/
50445static u8 *findOverflowCell(MemPage *pPage, int iCell){
50446  int i;
50447  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50448  for(i=pPage->nOverflow-1; i>=0; i--){
50449    int k;
50450    k = pPage->aiOvfl[i];
50451    if( k<=iCell ){
50452      if( k==iCell ){
50453        return pPage->apOvfl[i];
50454      }
50455      iCell--;
50456    }
50457  }
50458  return findCell(pPage, iCell);
50459}
50460
50461/*
50462** Parse a cell content block and fill in the CellInfo structure.  There
50463** are two versions of this function.  btreeParseCell() takes a
50464** cell index as the second argument and btreeParseCellPtr()
50465** takes a pointer to the body of the cell as its second argument.
50466**
50467** Within this file, the parseCell() macro can be called instead of
50468** btreeParseCellPtr(). Using some compilers, this will be faster.
50469*/
50470static void btreeParseCellPtr(
50471  MemPage *pPage,         /* Page containing the cell */
50472  u8 *pCell,              /* Pointer to the cell text. */
50473  CellInfo *pInfo         /* Fill in this structure */
50474){
50475  u16 n;                  /* Number bytes in cell content header */
50476  u32 nPayload;           /* Number of bytes of cell payload */
50477
50478  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50479
50480  pInfo->pCell = pCell;
50481  assert( pPage->leaf==0 || pPage->leaf==1 );
50482  n = pPage->childPtrSize;
50483  assert( n==4-4*pPage->leaf );
50484  if( pPage->intKey ){
50485    if( pPage->hasData ){
50486      n += getVarint32(&pCell[n], nPayload);
50487    }else{
50488      nPayload = 0;
50489    }
50490    n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
50491    pInfo->nData = nPayload;
50492  }else{
50493    pInfo->nData = 0;
50494    n += getVarint32(&pCell[n], nPayload);
50495    pInfo->nKey = nPayload;
50496  }
50497  pInfo->nPayload = nPayload;
50498  pInfo->nHeader = n;
50499  testcase( nPayload==pPage->maxLocal );
50500  testcase( nPayload==pPage->maxLocal+1 );
50501  if( likely(nPayload<=pPage->maxLocal) ){
50502    /* This is the (easy) common case where the entire payload fits
50503    ** on the local page.  No overflow is required.
50504    */
50505    if( (pInfo->nSize = (u16)(n+nPayload))<4 ) pInfo->nSize = 4;
50506    pInfo->nLocal = (u16)nPayload;
50507    pInfo->iOverflow = 0;
50508  }else{
50509    /* If the payload will not fit completely on the local page, we have
50510    ** to decide how much to store locally and how much to spill onto
50511    ** overflow pages.  The strategy is to minimize the amount of unused
50512    ** space on overflow pages while keeping the amount of local storage
50513    ** in between minLocal and maxLocal.
50514    **
50515    ** Warning:  changing the way overflow payload is distributed in any
50516    ** way will result in an incompatible file format.
50517    */
50518    int minLocal;  /* Minimum amount of payload held locally */
50519    int maxLocal;  /* Maximum amount of payload held locally */
50520    int surplus;   /* Overflow payload available for local storage */
50521
50522    minLocal = pPage->minLocal;
50523    maxLocal = pPage->maxLocal;
50524    surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
50525    testcase( surplus==maxLocal );
50526    testcase( surplus==maxLocal+1 );
50527    if( surplus <= maxLocal ){
50528      pInfo->nLocal = (u16)surplus;
50529    }else{
50530      pInfo->nLocal = (u16)minLocal;
50531    }
50532    pInfo->iOverflow = (u16)(pInfo->nLocal + n);
50533    pInfo->nSize = pInfo->iOverflow + 4;
50534  }
50535}
50536#define parseCell(pPage, iCell, pInfo) \
50537  btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
50538static void btreeParseCell(
50539  MemPage *pPage,         /* Page containing the cell */
50540  int iCell,              /* The cell index.  First cell is 0 */
50541  CellInfo *pInfo         /* Fill in this structure */
50542){
50543  parseCell(pPage, iCell, pInfo);
50544}
50545
50546/*
50547** Compute the total number of bytes that a Cell needs in the cell
50548** data area of the btree-page.  The return number includes the cell
50549** data header and the local payload, but not any overflow page or
50550** the space used by the cell pointer.
50551*/
50552static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
50553  u8 *pIter = &pCell[pPage->childPtrSize];
50554  u32 nSize;
50555
50556#ifdef SQLITE_DEBUG
50557  /* The value returned by this function should always be the same as
50558  ** the (CellInfo.nSize) value found by doing a full parse of the
50559  ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
50560  ** this function verifies that this invariant is not violated. */
50561  CellInfo debuginfo;
50562  btreeParseCellPtr(pPage, pCell, &debuginfo);
50563#endif
50564
50565  if( pPage->intKey ){
50566    u8 *pEnd;
50567    if( pPage->hasData ){
50568      pIter += getVarint32(pIter, nSize);
50569    }else{
50570      nSize = 0;
50571    }
50572
50573    /* pIter now points at the 64-bit integer key value, a variable length
50574    ** integer. The following block moves pIter to point at the first byte
50575    ** past the end of the key value. */
50576    pEnd = &pIter[9];
50577    while( (*pIter++)&0x80 && pIter<pEnd );
50578  }else{
50579    pIter += getVarint32(pIter, nSize);
50580  }
50581
50582  testcase( nSize==pPage->maxLocal );
50583  testcase( nSize==pPage->maxLocal+1 );
50584  if( nSize>pPage->maxLocal ){
50585    int minLocal = pPage->minLocal;
50586    nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
50587    testcase( nSize==pPage->maxLocal );
50588    testcase( nSize==pPage->maxLocal+1 );
50589    if( nSize>pPage->maxLocal ){
50590      nSize = minLocal;
50591    }
50592    nSize += 4;
50593  }
50594  nSize += (u32)(pIter - pCell);
50595
50596  /* The minimum size of any cell is 4 bytes. */
50597  if( nSize<4 ){
50598    nSize = 4;
50599  }
50600
50601  assert( nSize==debuginfo.nSize );
50602  return (u16)nSize;
50603}
50604
50605#ifdef SQLITE_DEBUG
50606/* This variation on cellSizePtr() is used inside of assert() statements
50607** only. */
50608static u16 cellSize(MemPage *pPage, int iCell){
50609  return cellSizePtr(pPage, findCell(pPage, iCell));
50610}
50611#endif
50612
50613#ifndef SQLITE_OMIT_AUTOVACUUM
50614/*
50615** If the cell pCell, part of page pPage contains a pointer
50616** to an overflow page, insert an entry into the pointer-map
50617** for the overflow page.
50618*/
50619static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
50620  CellInfo info;
50621  if( *pRC ) return;
50622  assert( pCell!=0 );
50623  btreeParseCellPtr(pPage, pCell, &info);
50624  assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
50625  if( info.iOverflow ){
50626    Pgno ovfl = get4byte(&pCell[info.iOverflow]);
50627    ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
50628  }
50629}
50630#endif
50631
50632
50633/*
50634** Defragment the page given.  All Cells are moved to the
50635** end of the page and all free space is collected into one
50636** big FreeBlk that occurs in between the header and cell
50637** pointer array and the cell content area.
50638*/
50639static int defragmentPage(MemPage *pPage){
50640  int i;                     /* Loop counter */
50641  int pc;                    /* Address of a i-th cell */
50642  int hdr;                   /* Offset to the page header */
50643  int size;                  /* Size of a cell */
50644  int usableSize;            /* Number of usable bytes on a page */
50645  int cellOffset;            /* Offset to the cell pointer array */
50646  int cbrk;                  /* Offset to the cell content area */
50647  int nCell;                 /* Number of cells on the page */
50648  unsigned char *data;       /* The page data */
50649  unsigned char *temp;       /* Temp area for cell content */
50650  int iCellFirst;            /* First allowable cell index */
50651  int iCellLast;             /* Last possible cell index */
50652
50653
50654  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
50655  assert( pPage->pBt!=0 );
50656  assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
50657  assert( pPage->nOverflow==0 );
50658  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50659  temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
50660  data = pPage->aData;
50661  hdr = pPage->hdrOffset;
50662  cellOffset = pPage->cellOffset;
50663  nCell = pPage->nCell;
50664  assert( nCell==get2byte(&data[hdr+3]) );
50665  usableSize = pPage->pBt->usableSize;
50666  cbrk = get2byte(&data[hdr+5]);
50667  memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
50668  cbrk = usableSize;
50669  iCellFirst = cellOffset + 2*nCell;
50670  iCellLast = usableSize - 4;
50671  for(i=0; i<nCell; i++){
50672    u8 *pAddr;     /* The i-th cell pointer */
50673    pAddr = &data[cellOffset + i*2];
50674    pc = get2byte(pAddr);
50675    testcase( pc==iCellFirst );
50676    testcase( pc==iCellLast );
50677#if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
50678    /* These conditions have already been verified in btreeInitPage()
50679    ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined
50680    */
50681    if( pc<iCellFirst || pc>iCellLast ){
50682      return SQLITE_CORRUPT_BKPT;
50683    }
50684#endif
50685    assert( pc>=iCellFirst && pc<=iCellLast );
50686    size = cellSizePtr(pPage, &temp[pc]);
50687    cbrk -= size;
50688#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
50689    if( cbrk<iCellFirst ){
50690      return SQLITE_CORRUPT_BKPT;
50691    }
50692#else
50693    if( cbrk<iCellFirst || pc+size>usableSize ){
50694      return SQLITE_CORRUPT_BKPT;
50695    }
50696#endif
50697    assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
50698    testcase( cbrk+size==usableSize );
50699    testcase( pc+size==usableSize );
50700    memcpy(&data[cbrk], &temp[pc], size);
50701    put2byte(pAddr, cbrk);
50702  }
50703  assert( cbrk>=iCellFirst );
50704  put2byte(&data[hdr+5], cbrk);
50705  data[hdr+1] = 0;
50706  data[hdr+2] = 0;
50707  data[hdr+7] = 0;
50708  memset(&data[iCellFirst], 0, cbrk-iCellFirst);
50709  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
50710  if( cbrk-iCellFirst!=pPage->nFree ){
50711    return SQLITE_CORRUPT_BKPT;
50712  }
50713  return SQLITE_OK;
50714}
50715
50716/*
50717** Allocate nByte bytes of space from within the B-Tree page passed
50718** as the first argument. Write into *pIdx the index into pPage->aData[]
50719** of the first byte of allocated space. Return either SQLITE_OK or
50720** an error code (usually SQLITE_CORRUPT).
50721**
50722** The caller guarantees that there is sufficient space to make the
50723** allocation.  This routine might need to defragment in order to bring
50724** all the space together, however.  This routine will avoid using
50725** the first two bytes past the cell pointer area since presumably this
50726** allocation is being made in order to insert a new cell, so we will
50727** also end up needing a new cell pointer.
50728*/
50729static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
50730  const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
50731  u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
50732  int nFrag;                           /* Number of fragmented bytes on pPage */
50733  int top;                             /* First byte of cell content area */
50734  int gap;        /* First byte of gap between cell pointers and cell content */
50735  int rc;         /* Integer return code */
50736  int usableSize; /* Usable size of the page */
50737
50738  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
50739  assert( pPage->pBt );
50740  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50741  assert( nByte>=0 );  /* Minimum cell size is 4 */
50742  assert( pPage->nFree>=nByte );
50743  assert( pPage->nOverflow==0 );
50744  usableSize = pPage->pBt->usableSize;
50745  assert( nByte < usableSize-8 );
50746
50747  nFrag = data[hdr+7];
50748  assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
50749  gap = pPage->cellOffset + 2*pPage->nCell;
50750  top = get2byteNotZero(&data[hdr+5]);
50751  if( gap>top ) return SQLITE_CORRUPT_BKPT;
50752  testcase( gap+2==top );
50753  testcase( gap+1==top );
50754  testcase( gap==top );
50755
50756  if( nFrag>=60 ){
50757    /* Always defragment highly fragmented pages */
50758    rc = defragmentPage(pPage);
50759    if( rc ) return rc;
50760    top = get2byteNotZero(&data[hdr+5]);
50761  }else if( gap+2<=top ){
50762    /* Search the freelist looking for a free slot big enough to satisfy
50763    ** the request. The allocation is made from the first free slot in
50764    ** the list that is large enough to accomadate it.
50765    */
50766    int pc, addr;
50767    for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
50768      int size;            /* Size of the free slot */
50769      if( pc>usableSize-4 || pc<addr+4 ){
50770        return SQLITE_CORRUPT_BKPT;
50771      }
50772      size = get2byte(&data[pc+2]);
50773      if( size>=nByte ){
50774        int x = size - nByte;
50775        testcase( x==4 );
50776        testcase( x==3 );
50777        if( x<4 ){
50778          /* Remove the slot from the free-list. Update the number of
50779          ** fragmented bytes within the page. */
50780          memcpy(&data[addr], &data[pc], 2);
50781          data[hdr+7] = (u8)(nFrag + x);
50782        }else if( size+pc > usableSize ){
50783          return SQLITE_CORRUPT_BKPT;
50784        }else{
50785          /* The slot remains on the free-list. Reduce its size to account
50786          ** for the portion used by the new allocation. */
50787          put2byte(&data[pc+2], x);
50788        }
50789        *pIdx = pc + x;
50790        return SQLITE_OK;
50791      }
50792    }
50793  }
50794
50795  /* Check to make sure there is enough space in the gap to satisfy
50796  ** the allocation.  If not, defragment.
50797  */
50798  testcase( gap+2+nByte==top );
50799  if( gap+2+nByte>top ){
50800    rc = defragmentPage(pPage);
50801    if( rc ) return rc;
50802    top = get2byteNotZero(&data[hdr+5]);
50803    assert( gap+nByte<=top );
50804  }
50805
50806
50807  /* Allocate memory from the gap in between the cell pointer array
50808  ** and the cell content area.  The btreeInitPage() call has already
50809  ** validated the freelist.  Given that the freelist is valid, there
50810  ** is no way that the allocation can extend off the end of the page.
50811  ** The assert() below verifies the previous sentence.
50812  */
50813  top -= nByte;
50814  put2byte(&data[hdr+5], top);
50815  assert( top+nByte <= (int)pPage->pBt->usableSize );
50816  *pIdx = top;
50817  return SQLITE_OK;
50818}
50819
50820/*
50821** Return a section of the pPage->aData to the freelist.
50822** The first byte of the new free block is pPage->aDisk[start]
50823** and the size of the block is "size" bytes.
50824**
50825** Most of the effort here is involved in coalesing adjacent
50826** free blocks into a single big free block.
50827*/
50828static int freeSpace(MemPage *pPage, int start, int size){
50829  int addr, pbegin, hdr;
50830  int iLast;                        /* Largest possible freeblock offset */
50831  unsigned char *data = pPage->aData;
50832
50833  assert( pPage->pBt!=0 );
50834  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
50835  assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
50836  assert( (start + size) <= (int)pPage->pBt->usableSize );
50837  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50838  assert( size>=0 );   /* Minimum cell size is 4 */
50839
50840  if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){
50841    /* Overwrite deleted information with zeros when the secure_delete
50842    ** option is enabled */
50843    memset(&data[start], 0, size);
50844  }
50845
50846  /* Add the space back into the linked list of freeblocks.  Note that
50847  ** even though the freeblock list was checked by btreeInitPage(),
50848  ** btreeInitPage() did not detect overlapping cells or
50849  ** freeblocks that overlapped cells.   Nor does it detect when the
50850  ** cell content area exceeds the value in the page header.  If these
50851  ** situations arise, then subsequent insert operations might corrupt
50852  ** the freelist.  So we do need to check for corruption while scanning
50853  ** the freelist.
50854  */
50855  hdr = pPage->hdrOffset;
50856  addr = hdr + 1;
50857  iLast = pPage->pBt->usableSize - 4;
50858  assert( start<=iLast );
50859  while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
50860    if( pbegin<addr+4 ){
50861      return SQLITE_CORRUPT_BKPT;
50862    }
50863    addr = pbegin;
50864  }
50865  if( pbegin>iLast ){
50866    return SQLITE_CORRUPT_BKPT;
50867  }
50868  assert( pbegin>addr || pbegin==0 );
50869  put2byte(&data[addr], start);
50870  put2byte(&data[start], pbegin);
50871  put2byte(&data[start+2], size);
50872  pPage->nFree = pPage->nFree + (u16)size;
50873
50874  /* Coalesce adjacent free blocks */
50875  addr = hdr + 1;
50876  while( (pbegin = get2byte(&data[addr]))>0 ){
50877    int pnext, psize, x;
50878    assert( pbegin>addr );
50879    assert( pbegin <= (int)pPage->pBt->usableSize-4 );
50880    pnext = get2byte(&data[pbegin]);
50881    psize = get2byte(&data[pbegin+2]);
50882    if( pbegin + psize + 3 >= pnext && pnext>0 ){
50883      int frag = pnext - (pbegin+psize);
50884      if( (frag<0) || (frag>(int)data[hdr+7]) ){
50885        return SQLITE_CORRUPT_BKPT;
50886      }
50887      data[hdr+7] -= (u8)frag;
50888      x = get2byte(&data[pnext]);
50889      put2byte(&data[pbegin], x);
50890      x = pnext + get2byte(&data[pnext+2]) - pbegin;
50891      put2byte(&data[pbegin+2], x);
50892    }else{
50893      addr = pbegin;
50894    }
50895  }
50896
50897  /* If the cell content area begins with a freeblock, remove it. */
50898  if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
50899    int top;
50900    pbegin = get2byte(&data[hdr+1]);
50901    memcpy(&data[hdr+1], &data[pbegin], 2);
50902    top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
50903    put2byte(&data[hdr+5], top);
50904  }
50905  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
50906  return SQLITE_OK;
50907}
50908
50909/*
50910** Decode the flags byte (the first byte of the header) for a page
50911** and initialize fields of the MemPage structure accordingly.
50912**
50913** Only the following combinations are supported.  Anything different
50914** indicates a corrupt database files:
50915**
50916**         PTF_ZERODATA
50917**         PTF_ZERODATA | PTF_LEAF
50918**         PTF_LEAFDATA | PTF_INTKEY
50919**         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
50920*/
50921static int decodeFlags(MemPage *pPage, int flagByte){
50922  BtShared *pBt;     /* A copy of pPage->pBt */
50923
50924  assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
50925  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50926  pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
50927  flagByte &= ~PTF_LEAF;
50928  pPage->childPtrSize = 4-4*pPage->leaf;
50929  pBt = pPage->pBt;
50930  if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
50931    pPage->intKey = 1;
50932    pPage->hasData = pPage->leaf;
50933    pPage->maxLocal = pBt->maxLeaf;
50934    pPage->minLocal = pBt->minLeaf;
50935  }else if( flagByte==PTF_ZERODATA ){
50936    pPage->intKey = 0;
50937    pPage->hasData = 0;
50938    pPage->maxLocal = pBt->maxLocal;
50939    pPage->minLocal = pBt->minLocal;
50940  }else{
50941    return SQLITE_CORRUPT_BKPT;
50942  }
50943  pPage->max1bytePayload = pBt->max1bytePayload;
50944  return SQLITE_OK;
50945}
50946
50947/*
50948** Initialize the auxiliary information for a disk block.
50949**
50950** Return SQLITE_OK on success.  If we see that the page does
50951** not contain a well-formed database page, then return
50952** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
50953** guarantee that the page is well-formed.  It only shows that
50954** we failed to detect any corruption.
50955*/
50956static int btreeInitPage(MemPage *pPage){
50957
50958  assert( pPage->pBt!=0 );
50959  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50960  assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
50961  assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
50962  assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
50963
50964  if( !pPage->isInit ){
50965    u16 pc;            /* Address of a freeblock within pPage->aData[] */
50966    u8 hdr;            /* Offset to beginning of page header */
50967    u8 *data;          /* Equal to pPage->aData */
50968    BtShared *pBt;        /* The main btree structure */
50969    int usableSize;    /* Amount of usable space on each page */
50970    u16 cellOffset;    /* Offset from start of page to first cell pointer */
50971    int nFree;         /* Number of unused bytes on the page */
50972    int top;           /* First byte of the cell content area */
50973    int iCellFirst;    /* First allowable cell or freeblock offset */
50974    int iCellLast;     /* Last possible cell or freeblock offset */
50975
50976    pBt = pPage->pBt;
50977
50978    hdr = pPage->hdrOffset;
50979    data = pPage->aData;
50980    if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
50981    assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
50982    pPage->maskPage = (u16)(pBt->pageSize - 1);
50983    pPage->nOverflow = 0;
50984    usableSize = pBt->usableSize;
50985    pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
50986    pPage->aDataEnd = &data[usableSize];
50987    pPage->aCellIdx = &data[cellOffset];
50988    top = get2byteNotZero(&data[hdr+5]);
50989    pPage->nCell = get2byte(&data[hdr+3]);
50990    if( pPage->nCell>MX_CELL(pBt) ){
50991      /* To many cells for a single page.  The page must be corrupt */
50992      return SQLITE_CORRUPT_BKPT;
50993    }
50994    testcase( pPage->nCell==MX_CELL(pBt) );
50995
50996    /* A malformed database page might cause us to read past the end
50997    ** of page when parsing a cell.
50998    **
50999    ** The following block of code checks early to see if a cell extends
51000    ** past the end of a page boundary and causes SQLITE_CORRUPT to be
51001    ** returned if it does.
51002    */
51003    iCellFirst = cellOffset + 2*pPage->nCell;
51004    iCellLast = usableSize - 4;
51005#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
51006    {
51007      int i;            /* Index into the cell pointer array */
51008      int sz;           /* Size of a cell */
51009
51010      if( !pPage->leaf ) iCellLast--;
51011      for(i=0; i<pPage->nCell; i++){
51012        pc = get2byte(&data[cellOffset+i*2]);
51013        testcase( pc==iCellFirst );
51014        testcase( pc==iCellLast );
51015        if( pc<iCellFirst || pc>iCellLast ){
51016          return SQLITE_CORRUPT_BKPT;
51017        }
51018        sz = cellSizePtr(pPage, &data[pc]);
51019        testcase( pc+sz==usableSize );
51020        if( pc+sz>usableSize ){
51021          return SQLITE_CORRUPT_BKPT;
51022        }
51023      }
51024      if( !pPage->leaf ) iCellLast++;
51025    }
51026#endif
51027
51028    /* Compute the total free space on the page */
51029    pc = get2byte(&data[hdr+1]);
51030    nFree = data[hdr+7] + top;
51031    while( pc>0 ){
51032      u16 next, size;
51033      if( pc<iCellFirst || pc>iCellLast ){
51034        /* Start of free block is off the page */
51035        return SQLITE_CORRUPT_BKPT;
51036      }
51037      next = get2byte(&data[pc]);
51038      size = get2byte(&data[pc+2]);
51039      if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
51040        /* Free blocks must be in ascending order. And the last byte of
51041        ** the free-block must lie on the database page.  */
51042        return SQLITE_CORRUPT_BKPT;
51043      }
51044      nFree = nFree + size;
51045      pc = next;
51046    }
51047
51048    /* At this point, nFree contains the sum of the offset to the start
51049    ** of the cell-content area plus the number of free bytes within
51050    ** the cell-content area. If this is greater than the usable-size
51051    ** of the page, then the page must be corrupted. This check also
51052    ** serves to verify that the offset to the start of the cell-content
51053    ** area, according to the page header, lies within the page.
51054    */
51055    if( nFree>usableSize ){
51056      return SQLITE_CORRUPT_BKPT;
51057    }
51058    pPage->nFree = (u16)(nFree - iCellFirst);
51059    pPage->isInit = 1;
51060  }
51061  return SQLITE_OK;
51062}
51063
51064/*
51065** Set up a raw page so that it looks like a database page holding
51066** no entries.
51067*/
51068static void zeroPage(MemPage *pPage, int flags){
51069  unsigned char *data = pPage->aData;
51070  BtShared *pBt = pPage->pBt;
51071  u8 hdr = pPage->hdrOffset;
51072  u16 first;
51073
51074  assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
51075  assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
51076  assert( sqlite3PagerGetData(pPage->pDbPage) == data );
51077  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
51078  assert( sqlite3_mutex_held(pBt->mutex) );
51079  if( pBt->btsFlags & BTS_SECURE_DELETE ){
51080    memset(&data[hdr], 0, pBt->usableSize - hdr);
51081  }
51082  data[hdr] = (char)flags;
51083  first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
51084  memset(&data[hdr+1], 0, 4);
51085  data[hdr+7] = 0;
51086  put2byte(&data[hdr+5], pBt->usableSize);
51087  pPage->nFree = (u16)(pBt->usableSize - first);
51088  decodeFlags(pPage, flags);
51089  pPage->hdrOffset = hdr;
51090  pPage->cellOffset = first;
51091  pPage->aDataEnd = &data[pBt->usableSize];
51092  pPage->aCellIdx = &data[first];
51093  pPage->nOverflow = 0;
51094  assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
51095  pPage->maskPage = (u16)(pBt->pageSize - 1);
51096  pPage->nCell = 0;
51097  pPage->isInit = 1;
51098}
51099
51100
51101/*
51102** Convert a DbPage obtained from the pager into a MemPage used by
51103** the btree layer.
51104*/
51105static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
51106  MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
51107  pPage->aData = sqlite3PagerGetData(pDbPage);
51108  pPage->pDbPage = pDbPage;
51109  pPage->pBt = pBt;
51110  pPage->pgno = pgno;
51111  pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
51112  return pPage;
51113}
51114
51115/*
51116** Get a page from the pager.  Initialize the MemPage.pBt and
51117** MemPage.aData elements if needed.
51118**
51119** If the noContent flag is set, it means that we do not care about
51120** the content of the page at this time.  So do not go to the disk
51121** to fetch the content.  Just fill in the content with zeros for now.
51122** If in the future we call sqlite3PagerWrite() on this page, that
51123** means we have started to be concerned about content and the disk
51124** read should occur at that point.
51125*/
51126static int btreeGetPage(
51127  BtShared *pBt,       /* The btree */
51128  Pgno pgno,           /* Number of the page to fetch */
51129  MemPage **ppPage,    /* Return the page in this parameter */
51130  int noContent,       /* Do not load page content if true */
51131  int bReadonly        /* True if a read-only (mmap) page is ok */
51132){
51133  int rc;
51134  DbPage *pDbPage;
51135  int flags = (noContent ? PAGER_ACQUIRE_NOCONTENT : 0)
51136            | (bReadonly ? PAGER_ACQUIRE_READONLY : 0);
51137
51138  assert( noContent==0 || bReadonly==0 );
51139  assert( sqlite3_mutex_held(pBt->mutex) );
51140  rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
51141  if( rc ) return rc;
51142  *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
51143  return SQLITE_OK;
51144}
51145
51146/*
51147** Retrieve a page from the pager cache. If the requested page is not
51148** already in the pager cache return NULL. Initialize the MemPage.pBt and
51149** MemPage.aData elements if needed.
51150*/
51151static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
51152  DbPage *pDbPage;
51153  assert( sqlite3_mutex_held(pBt->mutex) );
51154  pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
51155  if( pDbPage ){
51156    return btreePageFromDbPage(pDbPage, pgno, pBt);
51157  }
51158  return 0;
51159}
51160
51161/*
51162** Return the size of the database file in pages. If there is any kind of
51163** error, return ((unsigned int)-1).
51164*/
51165static Pgno btreePagecount(BtShared *pBt){
51166  return pBt->nPage;
51167}
51168SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
51169  assert( sqlite3BtreeHoldsMutex(p) );
51170  assert( ((p->pBt->nPage)&0x8000000)==0 );
51171  return (int)btreePagecount(p->pBt);
51172}
51173
51174/*
51175** Get a page from the pager and initialize it.  This routine is just a
51176** convenience wrapper around separate calls to btreeGetPage() and
51177** btreeInitPage().
51178**
51179** If an error occurs, then the value *ppPage is set to is undefined. It
51180** may remain unchanged, or it may be set to an invalid value.
51181*/
51182static int getAndInitPage(
51183  BtShared *pBt,                  /* The database file */
51184  Pgno pgno,                      /* Number of the page to get */
51185  MemPage **ppPage,               /* Write the page pointer here */
51186  int bReadonly                   /* True if a read-only (mmap) page is ok */
51187){
51188  int rc;
51189  assert( sqlite3_mutex_held(pBt->mutex) );
51190
51191  if( pgno>btreePagecount(pBt) ){
51192    rc = SQLITE_CORRUPT_BKPT;
51193  }else{
51194    rc = btreeGetPage(pBt, pgno, ppPage, 0, bReadonly);
51195    if( rc==SQLITE_OK ){
51196      rc = btreeInitPage(*ppPage);
51197      if( rc!=SQLITE_OK ){
51198        releasePage(*ppPage);
51199      }
51200    }
51201  }
51202
51203  testcase( pgno==0 );
51204  assert( pgno!=0 || rc==SQLITE_CORRUPT );
51205  return rc;
51206}
51207
51208/*
51209** Release a MemPage.  This should be called once for each prior
51210** call to btreeGetPage.
51211*/
51212static void releasePage(MemPage *pPage){
51213  if( pPage ){
51214    assert( pPage->aData );
51215    assert( pPage->pBt );
51216    assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
51217    assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
51218    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
51219    sqlite3PagerUnref(pPage->pDbPage);
51220  }
51221}
51222
51223/*
51224** During a rollback, when the pager reloads information into the cache
51225** so that the cache is restored to its original state at the start of
51226** the transaction, for each page restored this routine is called.
51227**
51228** This routine needs to reset the extra data section at the end of the
51229** page to agree with the restored data.
51230*/
51231static void pageReinit(DbPage *pData){
51232  MemPage *pPage;
51233  pPage = (MemPage *)sqlite3PagerGetExtra(pData);
51234  assert( sqlite3PagerPageRefcount(pData)>0 );
51235  if( pPage->isInit ){
51236    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
51237    pPage->isInit = 0;
51238    if( sqlite3PagerPageRefcount(pData)>1 ){
51239      /* pPage might not be a btree page;  it might be an overflow page
51240      ** or ptrmap page or a free page.  In those cases, the following
51241      ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
51242      ** But no harm is done by this.  And it is very important that
51243      ** btreeInitPage() be called on every btree page so we make
51244      ** the call for every page that comes in for re-initing. */
51245      btreeInitPage(pPage);
51246    }
51247  }
51248}
51249
51250/*
51251** Invoke the busy handler for a btree.
51252*/
51253static int btreeInvokeBusyHandler(void *pArg){
51254  BtShared *pBt = (BtShared*)pArg;
51255  assert( pBt->db );
51256  assert( sqlite3_mutex_held(pBt->db->mutex) );
51257  return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
51258}
51259
51260/*
51261** Open a database file.
51262**
51263** zFilename is the name of the database file.  If zFilename is NULL
51264** then an ephemeral database is created.  The ephemeral database might
51265** be exclusively in memory, or it might use a disk-based memory cache.
51266** Either way, the ephemeral database will be automatically deleted
51267** when sqlite3BtreeClose() is called.
51268**
51269** If zFilename is ":memory:" then an in-memory database is created
51270** that is automatically destroyed when it is closed.
51271**
51272** The "flags" parameter is a bitmask that might contain bits like
51273** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
51274**
51275** If the database is already opened in the same database connection
51276** and we are in shared cache mode, then the open will fail with an
51277** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
51278** objects in the same database connection since doing so will lead
51279** to problems with locking.
51280*/
51281SQLITE_PRIVATE int sqlite3BtreeOpen(
51282  sqlite3_vfs *pVfs,      /* VFS to use for this b-tree */
51283  const char *zFilename,  /* Name of the file containing the BTree database */
51284  sqlite3 *db,            /* Associated database handle */
51285  Btree **ppBtree,        /* Pointer to new Btree object written here */
51286  int flags,              /* Options */
51287  int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
51288){
51289  BtShared *pBt = 0;             /* Shared part of btree structure */
51290  Btree *p;                      /* Handle to return */
51291  sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
51292  int rc = SQLITE_OK;            /* Result code from this function */
51293  u8 nReserve;                   /* Byte of unused space on each page */
51294  unsigned char zDbHeader[100];  /* Database header content */
51295
51296  /* True if opening an ephemeral, temporary database */
51297  const int isTempDb = zFilename==0 || zFilename[0]==0;
51298
51299  /* Set the variable isMemdb to true for an in-memory database, or
51300  ** false for a file-based database.
51301  */
51302#ifdef SQLITE_OMIT_MEMORYDB
51303  const int isMemdb = 0;
51304#else
51305  const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
51306                       || (isTempDb && sqlite3TempInMemory(db))
51307                       || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
51308#endif
51309
51310  assert( db!=0 );
51311  assert( pVfs!=0 );
51312  assert( sqlite3_mutex_held(db->mutex) );
51313  assert( (flags&0xff)==flags );   /* flags fit in 8 bits */
51314
51315  /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
51316  assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
51317
51318  /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
51319  assert( (flags & BTREE_SINGLE)==0 || isTempDb );
51320
51321  if( isMemdb ){
51322    flags |= BTREE_MEMORY;
51323  }
51324  if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
51325    vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
51326  }
51327  p = sqlite3MallocZero(sizeof(Btree));
51328  if( !p ){
51329    return SQLITE_NOMEM;
51330  }
51331  p->inTrans = TRANS_NONE;
51332  p->db = db;
51333#ifndef SQLITE_OMIT_SHARED_CACHE
51334  p->lock.pBtree = p;
51335  p->lock.iTable = 1;
51336#endif
51337
51338#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
51339  /*
51340  ** If this Btree is a candidate for shared cache, try to find an
51341  ** existing BtShared object that we can share with
51342  */
51343  if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
51344    if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
51345      int nFullPathname = pVfs->mxPathname+1;
51346      char *zFullPathname = sqlite3Malloc(nFullPathname);
51347      MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
51348      p->sharable = 1;
51349      if( !zFullPathname ){
51350        sqlite3_free(p);
51351        return SQLITE_NOMEM;
51352      }
51353      if( isMemdb ){
51354        memcpy(zFullPathname, zFilename, sqlite3Strlen30(zFilename)+1);
51355      }else{
51356        rc = sqlite3OsFullPathname(pVfs, zFilename,
51357                                   nFullPathname, zFullPathname);
51358        if( rc ){
51359          sqlite3_free(zFullPathname);
51360          sqlite3_free(p);
51361          return rc;
51362        }
51363      }
51364#if SQLITE_THREADSAFE
51365      mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
51366      sqlite3_mutex_enter(mutexOpen);
51367      mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
51368      sqlite3_mutex_enter(mutexShared);
51369#endif
51370      for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
51371        assert( pBt->nRef>0 );
51372        if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
51373                 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
51374          int iDb;
51375          for(iDb=db->nDb-1; iDb>=0; iDb--){
51376            Btree *pExisting = db->aDb[iDb].pBt;
51377            if( pExisting && pExisting->pBt==pBt ){
51378              sqlite3_mutex_leave(mutexShared);
51379              sqlite3_mutex_leave(mutexOpen);
51380              sqlite3_free(zFullPathname);
51381              sqlite3_free(p);
51382              return SQLITE_CONSTRAINT;
51383            }
51384          }
51385          p->pBt = pBt;
51386          pBt->nRef++;
51387          break;
51388        }
51389      }
51390      sqlite3_mutex_leave(mutexShared);
51391      sqlite3_free(zFullPathname);
51392    }
51393#ifdef SQLITE_DEBUG
51394    else{
51395      /* In debug mode, we mark all persistent databases as sharable
51396      ** even when they are not.  This exercises the locking code and
51397      ** gives more opportunity for asserts(sqlite3_mutex_held())
51398      ** statements to find locking problems.
51399      */
51400      p->sharable = 1;
51401    }
51402#endif
51403  }
51404#endif
51405  if( pBt==0 ){
51406    /*
51407    ** The following asserts make sure that structures used by the btree are
51408    ** the right size.  This is to guard against size changes that result
51409    ** when compiling on a different architecture.
51410    */
51411    assert( sizeof(i64)==8 || sizeof(i64)==4 );
51412    assert( sizeof(u64)==8 || sizeof(u64)==4 );
51413    assert( sizeof(u32)==4 );
51414    assert( sizeof(u16)==2 );
51415    assert( sizeof(Pgno)==4 );
51416
51417    pBt = sqlite3MallocZero( sizeof(*pBt) );
51418    if( pBt==0 ){
51419      rc = SQLITE_NOMEM;
51420      goto btree_open_out;
51421    }
51422    rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
51423                          EXTRA_SIZE, flags, vfsFlags, pageReinit);
51424    if( rc==SQLITE_OK ){
51425      sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
51426      rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
51427    }
51428    if( rc!=SQLITE_OK ){
51429      goto btree_open_out;
51430    }
51431    pBt->openFlags = (u8)flags;
51432    pBt->db = db;
51433    sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
51434    p->pBt = pBt;
51435
51436    pBt->pCursor = 0;
51437    pBt->pPage1 = 0;
51438    if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
51439#ifdef SQLITE_SECURE_DELETE
51440    pBt->btsFlags |= BTS_SECURE_DELETE;
51441#endif
51442    pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
51443    if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
51444         || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
51445      pBt->pageSize = 0;
51446#ifndef SQLITE_OMIT_AUTOVACUUM
51447      /* If the magic name ":memory:" will create an in-memory database, then
51448      ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
51449      ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
51450      ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
51451      ** regular file-name. In this case the auto-vacuum applies as per normal.
51452      */
51453      if( zFilename && !isMemdb ){
51454        pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
51455        pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
51456      }
51457#endif
51458      nReserve = 0;
51459    }else{
51460      nReserve = zDbHeader[20];
51461      pBt->btsFlags |= BTS_PAGESIZE_FIXED;
51462#ifndef SQLITE_OMIT_AUTOVACUUM
51463      pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
51464      pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
51465#endif
51466    }
51467    rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
51468    if( rc ) goto btree_open_out;
51469    pBt->usableSize = pBt->pageSize - nReserve;
51470    assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
51471
51472#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
51473    /* Add the new BtShared object to the linked list sharable BtShareds.
51474    */
51475    if( p->sharable ){
51476      MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
51477      pBt->nRef = 1;
51478      MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
51479      if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
51480        pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
51481        if( pBt->mutex==0 ){
51482          rc = SQLITE_NOMEM;
51483          db->mallocFailed = 0;
51484          goto btree_open_out;
51485        }
51486      }
51487      sqlite3_mutex_enter(mutexShared);
51488      pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
51489      GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
51490      sqlite3_mutex_leave(mutexShared);
51491    }
51492#endif
51493  }
51494
51495#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
51496  /* If the new Btree uses a sharable pBtShared, then link the new
51497  ** Btree into the list of all sharable Btrees for the same connection.
51498  ** The list is kept in ascending order by pBt address.
51499  */
51500  if( p->sharable ){
51501    int i;
51502    Btree *pSib;
51503    for(i=0; i<db->nDb; i++){
51504      if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
51505        while( pSib->pPrev ){ pSib = pSib->pPrev; }
51506        if( p->pBt<pSib->pBt ){
51507          p->pNext = pSib;
51508          p->pPrev = 0;
51509          pSib->pPrev = p;
51510        }else{
51511          while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
51512            pSib = pSib->pNext;
51513          }
51514          p->pNext = pSib->pNext;
51515          p->pPrev = pSib;
51516          if( p->pNext ){
51517            p->pNext->pPrev = p;
51518          }
51519          pSib->pNext = p;
51520        }
51521        break;
51522      }
51523    }
51524  }
51525#endif
51526  *ppBtree = p;
51527
51528btree_open_out:
51529  if( rc!=SQLITE_OK ){
51530    if( pBt && pBt->pPager ){
51531      sqlite3PagerClose(pBt->pPager);
51532    }
51533    sqlite3_free(pBt);
51534    sqlite3_free(p);
51535    *ppBtree = 0;
51536  }else{
51537    /* If the B-Tree was successfully opened, set the pager-cache size to the
51538    ** default value. Except, when opening on an existing shared pager-cache,
51539    ** do not change the pager-cache size.
51540    */
51541    if( sqlite3BtreeSchema(p, 0, 0)==0 ){
51542      sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
51543    }
51544  }
51545  if( mutexOpen ){
51546    assert( sqlite3_mutex_held(mutexOpen) );
51547    sqlite3_mutex_leave(mutexOpen);
51548  }
51549  return rc;
51550}
51551
51552/*
51553** Decrement the BtShared.nRef counter.  When it reaches zero,
51554** remove the BtShared structure from the sharing list.  Return
51555** true if the BtShared.nRef counter reaches zero and return
51556** false if it is still positive.
51557*/
51558static int removeFromSharingList(BtShared *pBt){
51559#ifndef SQLITE_OMIT_SHARED_CACHE
51560  MUTEX_LOGIC( sqlite3_mutex *pMaster; )
51561  BtShared *pList;
51562  int removed = 0;
51563
51564  assert( sqlite3_mutex_notheld(pBt->mutex) );
51565  MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
51566  sqlite3_mutex_enter(pMaster);
51567  pBt->nRef--;
51568  if( pBt->nRef<=0 ){
51569    if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
51570      GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
51571    }else{
51572      pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
51573      while( ALWAYS(pList) && pList->pNext!=pBt ){
51574        pList=pList->pNext;
51575      }
51576      if( ALWAYS(pList) ){
51577        pList->pNext = pBt->pNext;
51578      }
51579    }
51580    if( SQLITE_THREADSAFE ){
51581      sqlite3_mutex_free(pBt->mutex);
51582    }
51583    removed = 1;
51584  }
51585  sqlite3_mutex_leave(pMaster);
51586  return removed;
51587#else
51588  return 1;
51589#endif
51590}
51591
51592/*
51593** Make sure pBt->pTmpSpace points to an allocation of
51594** MX_CELL_SIZE(pBt) bytes.
51595*/
51596static void allocateTempSpace(BtShared *pBt){
51597  if( !pBt->pTmpSpace ){
51598    pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
51599  }
51600}
51601
51602/*
51603** Free the pBt->pTmpSpace allocation
51604*/
51605static void freeTempSpace(BtShared *pBt){
51606  sqlite3PageFree( pBt->pTmpSpace);
51607  pBt->pTmpSpace = 0;
51608}
51609
51610/*
51611** Close an open database and invalidate all cursors.
51612*/
51613SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
51614  BtShared *pBt = p->pBt;
51615  BtCursor *pCur;
51616
51617  /* Close all cursors opened via this handle.  */
51618  assert( sqlite3_mutex_held(p->db->mutex) );
51619  sqlite3BtreeEnter(p);
51620  pCur = pBt->pCursor;
51621  while( pCur ){
51622    BtCursor *pTmp = pCur;
51623    pCur = pCur->pNext;
51624    if( pTmp->pBtree==p ){
51625      sqlite3BtreeCloseCursor(pTmp);
51626    }
51627  }
51628
51629  /* Rollback any active transaction and free the handle structure.
51630  ** The call to sqlite3BtreeRollback() drops any table-locks held by
51631  ** this handle.
51632  */
51633  sqlite3BtreeRollback(p, SQLITE_OK);
51634  sqlite3BtreeLeave(p);
51635
51636  /* If there are still other outstanding references to the shared-btree
51637  ** structure, return now. The remainder of this procedure cleans
51638  ** up the shared-btree.
51639  */
51640  assert( p->wantToLock==0 && p->locked==0 );
51641  if( !p->sharable || removeFromSharingList(pBt) ){
51642    /* The pBt is no longer on the sharing list, so we can access
51643    ** it without having to hold the mutex.
51644    **
51645    ** Clean out and delete the BtShared object.
51646    */
51647    assert( !pBt->pCursor );
51648    sqlite3PagerClose(pBt->pPager);
51649    if( pBt->xFreeSchema && pBt->pSchema ){
51650      pBt->xFreeSchema(pBt->pSchema);
51651    }
51652    sqlite3DbFree(0, pBt->pSchema);
51653    freeTempSpace(pBt);
51654    sqlite3_free(pBt);
51655  }
51656
51657#ifndef SQLITE_OMIT_SHARED_CACHE
51658  assert( p->wantToLock==0 );
51659  assert( p->locked==0 );
51660  if( p->pPrev ) p->pPrev->pNext = p->pNext;
51661  if( p->pNext ) p->pNext->pPrev = p->pPrev;
51662#endif
51663
51664  sqlite3_free(p);
51665  return SQLITE_OK;
51666}
51667
51668/*
51669** Change the limit on the number of pages allowed in the cache.
51670**
51671** The maximum number of cache pages is set to the absolute
51672** value of mxPage.  If mxPage is negative, the pager will
51673** operate asynchronously - it will not stop to do fsync()s
51674** to insure data is written to the disk surface before
51675** continuing.  Transactions still work if synchronous is off,
51676** and the database cannot be corrupted if this program
51677** crashes.  But if the operating system crashes or there is
51678** an abrupt power failure when synchronous is off, the database
51679** could be left in an inconsistent and unrecoverable state.
51680** Synchronous is on by default so database corruption is not
51681** normally a worry.
51682*/
51683SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
51684  BtShared *pBt = p->pBt;
51685  assert( sqlite3_mutex_held(p->db->mutex) );
51686  sqlite3BtreeEnter(p);
51687  sqlite3PagerSetCachesize(pBt->pPager, mxPage);
51688  sqlite3BtreeLeave(p);
51689  return SQLITE_OK;
51690}
51691
51692/*
51693** Change the limit on the amount of the database file that may be
51694** memory mapped.
51695*/
51696SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
51697  BtShared *pBt = p->pBt;
51698  assert( sqlite3_mutex_held(p->db->mutex) );
51699  sqlite3BtreeEnter(p);
51700  sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
51701  sqlite3BtreeLeave(p);
51702  return SQLITE_OK;
51703}
51704
51705/*
51706** Change the way data is synced to disk in order to increase or decrease
51707** how well the database resists damage due to OS crashes and power
51708** failures.  Level 1 is the same as asynchronous (no syncs() occur and
51709** there is a high probability of damage)  Level 2 is the default.  There
51710** is a very low but non-zero probability of damage.  Level 3 reduces the
51711** probability of damage to near zero but with a write performance reduction.
51712*/
51713#ifndef SQLITE_OMIT_PAGER_PRAGMAS
51714SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(
51715  Btree *p,              /* The btree to set the safety level on */
51716  int level,             /* PRAGMA synchronous.  1=OFF, 2=NORMAL, 3=FULL */
51717  int fullSync,          /* PRAGMA fullfsync. */
51718  int ckptFullSync       /* PRAGMA checkpoint_fullfync */
51719){
51720  BtShared *pBt = p->pBt;
51721  assert( sqlite3_mutex_held(p->db->mutex) );
51722  assert( level>=1 && level<=3 );
51723  sqlite3BtreeEnter(p);
51724  sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync, ckptFullSync);
51725  sqlite3BtreeLeave(p);
51726  return SQLITE_OK;
51727}
51728#endif
51729
51730/*
51731** Return TRUE if the given btree is set to safety level 1.  In other
51732** words, return TRUE if no sync() occurs on the disk files.
51733*/
51734SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
51735  BtShared *pBt = p->pBt;
51736  int rc;
51737  assert( sqlite3_mutex_held(p->db->mutex) );
51738  sqlite3BtreeEnter(p);
51739  assert( pBt && pBt->pPager );
51740  rc = sqlite3PagerNosync(pBt->pPager);
51741  sqlite3BtreeLeave(p);
51742  return rc;
51743}
51744
51745/*
51746** Change the default pages size and the number of reserved bytes per page.
51747** Or, if the page size has already been fixed, return SQLITE_READONLY
51748** without changing anything.
51749**
51750** The page size must be a power of 2 between 512 and 65536.  If the page
51751** size supplied does not meet this constraint then the page size is not
51752** changed.
51753**
51754** Page sizes are constrained to be a power of two so that the region
51755** of the database file used for locking (beginning at PENDING_BYTE,
51756** the first byte past the 1GB boundary, 0x40000000) needs to occur
51757** at the beginning of a page.
51758**
51759** If parameter nReserve is less than zero, then the number of reserved
51760** bytes per page is left unchanged.
51761**
51762** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
51763** and autovacuum mode can no longer be changed.
51764*/
51765SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
51766  int rc = SQLITE_OK;
51767  BtShared *pBt = p->pBt;
51768  assert( nReserve>=-1 && nReserve<=255 );
51769  sqlite3BtreeEnter(p);
51770  if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
51771    sqlite3BtreeLeave(p);
51772    return SQLITE_READONLY;
51773  }
51774  if( nReserve<0 ){
51775    nReserve = pBt->pageSize - pBt->usableSize;
51776  }
51777  assert( nReserve>=0 && nReserve<=255 );
51778  if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
51779        ((pageSize-1)&pageSize)==0 ){
51780    assert( (pageSize & 7)==0 );
51781    assert( !pBt->pPage1 && !pBt->pCursor );
51782    pBt->pageSize = (u32)pageSize;
51783    freeTempSpace(pBt);
51784  }
51785  rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
51786  pBt->usableSize = pBt->pageSize - (u16)nReserve;
51787  if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
51788  sqlite3BtreeLeave(p);
51789  return rc;
51790}
51791
51792/*
51793** Return the currently defined page size
51794*/
51795SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
51796  return p->pBt->pageSize;
51797}
51798
51799#if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG)
51800/*
51801** This function is similar to sqlite3BtreeGetReserve(), except that it
51802** may only be called if it is guaranteed that the b-tree mutex is already
51803** held.
51804**
51805** This is useful in one special case in the backup API code where it is
51806** known that the shared b-tree mutex is held, but the mutex on the
51807** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
51808** were to be called, it might collide with some other operation on the
51809** database handle that owns *p, causing undefined behavior.
51810*/
51811SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
51812  assert( sqlite3_mutex_held(p->pBt->mutex) );
51813  return p->pBt->pageSize - p->pBt->usableSize;
51814}
51815#endif /* SQLITE_HAS_CODEC || SQLITE_DEBUG */
51816
51817#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
51818/*
51819** Return the number of bytes of space at the end of every page that
51820** are intentually left unused.  This is the "reserved" space that is
51821** sometimes used by extensions.
51822*/
51823SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
51824  int n;
51825  sqlite3BtreeEnter(p);
51826  n = p->pBt->pageSize - p->pBt->usableSize;
51827  sqlite3BtreeLeave(p);
51828  return n;
51829}
51830
51831/*
51832** Set the maximum page count for a database if mxPage is positive.
51833** No changes are made if mxPage is 0 or negative.
51834** Regardless of the value of mxPage, return the maximum page count.
51835*/
51836SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
51837  int n;
51838  sqlite3BtreeEnter(p);
51839  n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
51840  sqlite3BtreeLeave(p);
51841  return n;
51842}
51843
51844/*
51845** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1.  If newFlag is -1,
51846** then make no changes.  Always return the value of the BTS_SECURE_DELETE
51847** setting after the change.
51848*/
51849SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
51850  int b;
51851  if( p==0 ) return 0;
51852  sqlite3BtreeEnter(p);
51853  if( newFlag>=0 ){
51854    p->pBt->btsFlags &= ~BTS_SECURE_DELETE;
51855    if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;
51856  }
51857  b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;
51858  sqlite3BtreeLeave(p);
51859  return b;
51860}
51861#endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
51862
51863/*
51864** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
51865** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
51866** is disabled. The default value for the auto-vacuum property is
51867** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
51868*/
51869SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
51870#ifdef SQLITE_OMIT_AUTOVACUUM
51871  return SQLITE_READONLY;
51872#else
51873  BtShared *pBt = p->pBt;
51874  int rc = SQLITE_OK;
51875  u8 av = (u8)autoVacuum;
51876
51877  sqlite3BtreeEnter(p);
51878  if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
51879    rc = SQLITE_READONLY;
51880  }else{
51881    pBt->autoVacuum = av ?1:0;
51882    pBt->incrVacuum = av==2 ?1:0;
51883  }
51884  sqlite3BtreeLeave(p);
51885  return rc;
51886#endif
51887}
51888
51889/*
51890** Return the value of the 'auto-vacuum' property. If auto-vacuum is
51891** enabled 1 is returned. Otherwise 0.
51892*/
51893SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
51894#ifdef SQLITE_OMIT_AUTOVACUUM
51895  return BTREE_AUTOVACUUM_NONE;
51896#else
51897  int rc;
51898  sqlite3BtreeEnter(p);
51899  rc = (
51900    (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
51901    (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
51902    BTREE_AUTOVACUUM_INCR
51903  );
51904  sqlite3BtreeLeave(p);
51905  return rc;
51906#endif
51907}
51908
51909
51910/*
51911** Get a reference to pPage1 of the database file.  This will
51912** also acquire a readlock on that file.
51913**
51914** SQLITE_OK is returned on success.  If the file is not a
51915** well-formed database file, then SQLITE_CORRUPT is returned.
51916** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
51917** is returned if we run out of memory.
51918*/
51919static int lockBtree(BtShared *pBt){
51920  int rc;              /* Result code from subfunctions */
51921  MemPage *pPage1;     /* Page 1 of the database file */
51922  int nPage;           /* Number of pages in the database */
51923  int nPageFile = 0;   /* Number of pages in the database file */
51924  int nPageHeader;     /* Number of pages in the database according to hdr */
51925
51926  assert( sqlite3_mutex_held(pBt->mutex) );
51927  assert( pBt->pPage1==0 );
51928  rc = sqlite3PagerSharedLock(pBt->pPager);
51929  if( rc!=SQLITE_OK ) return rc;
51930  rc = btreeGetPage(pBt, 1, &pPage1, 0, 0);
51931  if( rc!=SQLITE_OK ) return rc;
51932
51933  /* Do some checking to help insure the file we opened really is
51934  ** a valid database file.
51935  */
51936  nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
51937  sqlite3PagerPagecount(pBt->pPager, &nPageFile);
51938  if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
51939    nPage = nPageFile;
51940  }
51941  if( nPage>0 ){
51942    u32 pageSize;
51943    u32 usableSize;
51944    u8 *page1 = pPage1->aData;
51945    rc = SQLITE_NOTADB;
51946    if( memcmp(page1, zMagicHeader, 16)!=0 ){
51947      goto page1_init_failed;
51948    }
51949
51950#ifdef SQLITE_OMIT_WAL
51951    if( page1[18]>1 ){
51952      pBt->btsFlags |= BTS_READ_ONLY;
51953    }
51954    if( page1[19]>1 ){
51955      goto page1_init_failed;
51956    }
51957#else
51958    if( page1[18]>2 ){
51959      pBt->btsFlags |= BTS_READ_ONLY;
51960    }
51961    if( page1[19]>2 ){
51962      goto page1_init_failed;
51963    }
51964
51965    /* If the write version is set to 2, this database should be accessed
51966    ** in WAL mode. If the log is not already open, open it now. Then
51967    ** return SQLITE_OK and return without populating BtShared.pPage1.
51968    ** The caller detects this and calls this function again. This is
51969    ** required as the version of page 1 currently in the page1 buffer
51970    ** may not be the latest version - there may be a newer one in the log
51971    ** file.
51972    */
51973    if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
51974      int isOpen = 0;
51975      rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
51976      if( rc!=SQLITE_OK ){
51977        goto page1_init_failed;
51978      }else if( isOpen==0 ){
51979        releasePage(pPage1);
51980        return SQLITE_OK;
51981      }
51982      rc = SQLITE_NOTADB;
51983    }
51984#endif
51985
51986    /* The maximum embedded fraction must be exactly 25%.  And the minimum
51987    ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
51988    ** The original design allowed these amounts to vary, but as of
51989    ** version 3.6.0, we require them to be fixed.
51990    */
51991    if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
51992      goto page1_init_failed;
51993    }
51994    pageSize = (page1[16]<<8) | (page1[17]<<16);
51995    if( ((pageSize-1)&pageSize)!=0
51996     || pageSize>SQLITE_MAX_PAGE_SIZE
51997     || pageSize<=256
51998    ){
51999      goto page1_init_failed;
52000    }
52001    assert( (pageSize & 7)==0 );
52002    usableSize = pageSize - page1[20];
52003    if( (u32)pageSize!=pBt->pageSize ){
52004      /* After reading the first page of the database assuming a page size
52005      ** of BtShared.pageSize, we have discovered that the page-size is
52006      ** actually pageSize. Unlock the database, leave pBt->pPage1 at
52007      ** zero and return SQLITE_OK. The caller will call this function
52008      ** again with the correct page-size.
52009      */
52010      releasePage(pPage1);
52011      pBt->usableSize = usableSize;
52012      pBt->pageSize = pageSize;
52013      freeTempSpace(pBt);
52014      rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
52015                                   pageSize-usableSize);
52016      return rc;
52017    }
52018    if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
52019      rc = SQLITE_CORRUPT_BKPT;
52020      goto page1_init_failed;
52021    }
52022    if( usableSize<480 ){
52023      goto page1_init_failed;
52024    }
52025    pBt->pageSize = pageSize;
52026    pBt->usableSize = usableSize;
52027#ifndef SQLITE_OMIT_AUTOVACUUM
52028    pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
52029    pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
52030#endif
52031  }
52032
52033  /* maxLocal is the maximum amount of payload to store locally for
52034  ** a cell.  Make sure it is small enough so that at least minFanout
52035  ** cells can will fit on one page.  We assume a 10-byte page header.
52036  ** Besides the payload, the cell must store:
52037  **     2-byte pointer to the cell
52038  **     4-byte child pointer
52039  **     9-byte nKey value
52040  **     4-byte nData value
52041  **     4-byte overflow page pointer
52042  ** So a cell consists of a 2-byte pointer, a header which is as much as
52043  ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
52044  ** page pointer.
52045  */
52046  pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
52047  pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
52048  pBt->maxLeaf = (u16)(pBt->usableSize - 35);
52049  pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
52050  if( pBt->maxLocal>127 ){
52051    pBt->max1bytePayload = 127;
52052  }else{
52053    pBt->max1bytePayload = (u8)pBt->maxLocal;
52054  }
52055  assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
52056  pBt->pPage1 = pPage1;
52057  pBt->nPage = nPage;
52058  return SQLITE_OK;
52059
52060page1_init_failed:
52061  releasePage(pPage1);
52062  pBt->pPage1 = 0;
52063  return rc;
52064}
52065
52066#ifndef NDEBUG
52067/*
52068** Return the number of cursors open on pBt. This is for use
52069** in assert() expressions, so it is only compiled if NDEBUG is not
52070** defined.
52071**
52072** Only write cursors are counted if wrOnly is true.  If wrOnly is
52073** false then all cursors are counted.
52074**
52075** For the purposes of this routine, a cursor is any cursor that
52076** is capable of reading or writing to the databse.  Cursors that
52077** have been tripped into the CURSOR_FAULT state are not counted.
52078*/
52079static int countValidCursors(BtShared *pBt, int wrOnly){
52080  BtCursor *pCur;
52081  int r = 0;
52082  for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
52083    if( (wrOnly==0 || pCur->wrFlag) && pCur->eState!=CURSOR_FAULT ) r++;
52084  }
52085  return r;
52086}
52087#endif
52088
52089/*
52090** If there are no outstanding cursors and we are not in the middle
52091** of a transaction but there is a read lock on the database, then
52092** this routine unrefs the first page of the database file which
52093** has the effect of releasing the read lock.
52094**
52095** If there is a transaction in progress, this routine is a no-op.
52096*/
52097static void unlockBtreeIfUnused(BtShared *pBt){
52098  assert( sqlite3_mutex_held(pBt->mutex) );
52099  assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
52100  if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
52101    assert( pBt->pPage1->aData );
52102    assert( sqlite3PagerRefcount(pBt->pPager)==1 );
52103    assert( pBt->pPage1->aData );
52104    releasePage(pBt->pPage1);
52105    pBt->pPage1 = 0;
52106  }
52107}
52108
52109/*
52110** If pBt points to an empty file then convert that empty file
52111** into a new empty database by initializing the first page of
52112** the database.
52113*/
52114static int newDatabase(BtShared *pBt){
52115  MemPage *pP1;
52116  unsigned char *data;
52117  int rc;
52118
52119  assert( sqlite3_mutex_held(pBt->mutex) );
52120  if( pBt->nPage>0 ){
52121    return SQLITE_OK;
52122  }
52123  pP1 = pBt->pPage1;
52124  assert( pP1!=0 );
52125  data = pP1->aData;
52126  rc = sqlite3PagerWrite(pP1->pDbPage);
52127  if( rc ) return rc;
52128  memcpy(data, zMagicHeader, sizeof(zMagicHeader));
52129  assert( sizeof(zMagicHeader)==16 );
52130  data[16] = (u8)((pBt->pageSize>>8)&0xff);
52131  data[17] = (u8)((pBt->pageSize>>16)&0xff);
52132  data[18] = 1;
52133  data[19] = 1;
52134  assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
52135  data[20] = (u8)(pBt->pageSize - pBt->usableSize);
52136  data[21] = 64;
52137  data[22] = 32;
52138  data[23] = 32;
52139  memset(&data[24], 0, 100-24);
52140  zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
52141  pBt->btsFlags |= BTS_PAGESIZE_FIXED;
52142#ifndef SQLITE_OMIT_AUTOVACUUM
52143  assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
52144  assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
52145  put4byte(&data[36 + 4*4], pBt->autoVacuum);
52146  put4byte(&data[36 + 7*4], pBt->incrVacuum);
52147#endif
52148  pBt->nPage = 1;
52149  data[31] = 1;
52150  return SQLITE_OK;
52151}
52152
52153/*
52154** Initialize the first page of the database file (creating a database
52155** consisting of a single page and no schema objects). Return SQLITE_OK
52156** if successful, or an SQLite error code otherwise.
52157*/
52158SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
52159  int rc;
52160  sqlite3BtreeEnter(p);
52161  p->pBt->nPage = 0;
52162  rc = newDatabase(p->pBt);
52163  sqlite3BtreeLeave(p);
52164  return rc;
52165}
52166
52167/*
52168** Attempt to start a new transaction. A write-transaction
52169** is started if the second argument is nonzero, otherwise a read-
52170** transaction.  If the second argument is 2 or more and exclusive
52171** transaction is started, meaning that no other process is allowed
52172** to access the database.  A preexisting transaction may not be
52173** upgraded to exclusive by calling this routine a second time - the
52174** exclusivity flag only works for a new transaction.
52175**
52176** A write-transaction must be started before attempting any
52177** changes to the database.  None of the following routines
52178** will work unless a transaction is started first:
52179**
52180**      sqlite3BtreeCreateTable()
52181**      sqlite3BtreeCreateIndex()
52182**      sqlite3BtreeClearTable()
52183**      sqlite3BtreeDropTable()
52184**      sqlite3BtreeInsert()
52185**      sqlite3BtreeDelete()
52186**      sqlite3BtreeUpdateMeta()
52187**
52188** If an initial attempt to acquire the lock fails because of lock contention
52189** and the database was previously unlocked, then invoke the busy handler
52190** if there is one.  But if there was previously a read-lock, do not
52191** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is
52192** returned when there is already a read-lock in order to avoid a deadlock.
52193**
52194** Suppose there are two processes A and B.  A has a read lock and B has
52195** a reserved lock.  B tries to promote to exclusive but is blocked because
52196** of A's read lock.  A tries to promote to reserved but is blocked by B.
52197** One or the other of the two processes must give way or there can be
52198** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
52199** when A already has a read lock, we encourage A to give up and let B
52200** proceed.
52201*/
52202SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
52203  sqlite3 *pBlock = 0;
52204  BtShared *pBt = p->pBt;
52205  int rc = SQLITE_OK;
52206
52207  sqlite3BtreeEnter(p);
52208  btreeIntegrity(p);
52209
52210  /* If the btree is already in a write-transaction, or it
52211  ** is already in a read-transaction and a read-transaction
52212  ** is requested, this is a no-op.
52213  */
52214  if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
52215    goto trans_begun;
52216  }
52217  assert( IfNotOmitAV(pBt->bDoTruncate)==0 );
52218
52219  /* Write transactions are not possible on a read-only database */
52220  if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
52221    rc = SQLITE_READONLY;
52222    goto trans_begun;
52223  }
52224
52225#ifndef SQLITE_OMIT_SHARED_CACHE
52226  /* If another database handle has already opened a write transaction
52227  ** on this shared-btree structure and a second write transaction is
52228  ** requested, return SQLITE_LOCKED.
52229  */
52230  if( (wrflag && pBt->inTransaction==TRANS_WRITE)
52231   || (pBt->btsFlags & BTS_PENDING)!=0
52232  ){
52233    pBlock = pBt->pWriter->db;
52234  }else if( wrflag>1 ){
52235    BtLock *pIter;
52236    for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
52237      if( pIter->pBtree!=p ){
52238        pBlock = pIter->pBtree->db;
52239        break;
52240      }
52241    }
52242  }
52243  if( pBlock ){
52244    sqlite3ConnectionBlocked(p->db, pBlock);
52245    rc = SQLITE_LOCKED_SHAREDCACHE;
52246    goto trans_begun;
52247  }
52248#endif
52249
52250  /* Any read-only or read-write transaction implies a read-lock on
52251  ** page 1. So if some other shared-cache client already has a write-lock
52252  ** on page 1, the transaction cannot be opened. */
52253  rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
52254  if( SQLITE_OK!=rc ) goto trans_begun;
52255
52256  pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
52257  if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
52258  do {
52259    /* Call lockBtree() until either pBt->pPage1 is populated or
52260    ** lockBtree() returns something other than SQLITE_OK. lockBtree()
52261    ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
52262    ** reading page 1 it discovers that the page-size of the database
52263    ** file is not pBt->pageSize. In this case lockBtree() will update
52264    ** pBt->pageSize to the page-size of the file on disk.
52265    */
52266    while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
52267
52268    if( rc==SQLITE_OK && wrflag ){
52269      if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
52270        rc = SQLITE_READONLY;
52271      }else{
52272        rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
52273        if( rc==SQLITE_OK ){
52274          rc = newDatabase(pBt);
52275        }
52276      }
52277    }
52278
52279    if( rc!=SQLITE_OK ){
52280      unlockBtreeIfUnused(pBt);
52281    }
52282  }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
52283          btreeInvokeBusyHandler(pBt) );
52284
52285  if( rc==SQLITE_OK ){
52286    if( p->inTrans==TRANS_NONE ){
52287      pBt->nTransaction++;
52288#ifndef SQLITE_OMIT_SHARED_CACHE
52289      if( p->sharable ){
52290        assert( p->lock.pBtree==p && p->lock.iTable==1 );
52291        p->lock.eLock = READ_LOCK;
52292        p->lock.pNext = pBt->pLock;
52293        pBt->pLock = &p->lock;
52294      }
52295#endif
52296    }
52297    p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
52298    if( p->inTrans>pBt->inTransaction ){
52299      pBt->inTransaction = p->inTrans;
52300    }
52301    if( wrflag ){
52302      MemPage *pPage1 = pBt->pPage1;
52303#ifndef SQLITE_OMIT_SHARED_CACHE
52304      assert( !pBt->pWriter );
52305      pBt->pWriter = p;
52306      pBt->btsFlags &= ~BTS_EXCLUSIVE;
52307      if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
52308#endif
52309
52310      /* If the db-size header field is incorrect (as it may be if an old
52311      ** client has been writing the database file), update it now. Doing
52312      ** this sooner rather than later means the database size can safely
52313      ** re-read the database size from page 1 if a savepoint or transaction
52314      ** rollback occurs within the transaction.
52315      */
52316      if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
52317        rc = sqlite3PagerWrite(pPage1->pDbPage);
52318        if( rc==SQLITE_OK ){
52319          put4byte(&pPage1->aData[28], pBt->nPage);
52320        }
52321      }
52322    }
52323  }
52324
52325
52326trans_begun:
52327  if( rc==SQLITE_OK && wrflag ){
52328    /* This call makes sure that the pager has the correct number of
52329    ** open savepoints. If the second parameter is greater than 0 and
52330    ** the sub-journal is not already open, then it will be opened here.
52331    */
52332    rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
52333  }
52334
52335  btreeIntegrity(p);
52336  sqlite3BtreeLeave(p);
52337  return rc;
52338}
52339
52340#ifndef SQLITE_OMIT_AUTOVACUUM
52341
52342/*
52343** Set the pointer-map entries for all children of page pPage. Also, if
52344** pPage contains cells that point to overflow pages, set the pointer
52345** map entries for the overflow pages as well.
52346*/
52347static int setChildPtrmaps(MemPage *pPage){
52348  int i;                             /* Counter variable */
52349  int nCell;                         /* Number of cells in page pPage */
52350  int rc;                            /* Return code */
52351  BtShared *pBt = pPage->pBt;
52352  u8 isInitOrig = pPage->isInit;
52353  Pgno pgno = pPage->pgno;
52354
52355  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52356  rc = btreeInitPage(pPage);
52357  if( rc!=SQLITE_OK ){
52358    goto set_child_ptrmaps_out;
52359  }
52360  nCell = pPage->nCell;
52361
52362  for(i=0; i<nCell; i++){
52363    u8 *pCell = findCell(pPage, i);
52364
52365    ptrmapPutOvflPtr(pPage, pCell, &rc);
52366
52367    if( !pPage->leaf ){
52368      Pgno childPgno = get4byte(pCell);
52369      ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
52370    }
52371  }
52372
52373  if( !pPage->leaf ){
52374    Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
52375    ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
52376  }
52377
52378set_child_ptrmaps_out:
52379  pPage->isInit = isInitOrig;
52380  return rc;
52381}
52382
52383/*
52384** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
52385** that it points to iTo. Parameter eType describes the type of pointer to
52386** be modified, as  follows:
52387**
52388** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child
52389**                   page of pPage.
52390**
52391** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
52392**                   page pointed to by one of the cells on pPage.
52393**
52394** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
52395**                   overflow page in the list.
52396*/
52397static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
52398  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52399  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
52400  if( eType==PTRMAP_OVERFLOW2 ){
52401    /* The pointer is always the first 4 bytes of the page in this case.  */
52402    if( get4byte(pPage->aData)!=iFrom ){
52403      return SQLITE_CORRUPT_BKPT;
52404    }
52405    put4byte(pPage->aData, iTo);
52406  }else{
52407    u8 isInitOrig = pPage->isInit;
52408    int i;
52409    int nCell;
52410
52411    btreeInitPage(pPage);
52412    nCell = pPage->nCell;
52413
52414    for(i=0; i<nCell; i++){
52415      u8 *pCell = findCell(pPage, i);
52416      if( eType==PTRMAP_OVERFLOW1 ){
52417        CellInfo info;
52418        btreeParseCellPtr(pPage, pCell, &info);
52419        if( info.iOverflow
52420         && pCell+info.iOverflow+3<=pPage->aData+pPage->maskPage
52421         && iFrom==get4byte(&pCell[info.iOverflow])
52422        ){
52423          put4byte(&pCell[info.iOverflow], iTo);
52424          break;
52425        }
52426      }else{
52427        if( get4byte(pCell)==iFrom ){
52428          put4byte(pCell, iTo);
52429          break;
52430        }
52431      }
52432    }
52433
52434    if( i==nCell ){
52435      if( eType!=PTRMAP_BTREE ||
52436          get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
52437        return SQLITE_CORRUPT_BKPT;
52438      }
52439      put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
52440    }
52441
52442    pPage->isInit = isInitOrig;
52443  }
52444  return SQLITE_OK;
52445}
52446
52447
52448/*
52449** Move the open database page pDbPage to location iFreePage in the
52450** database. The pDbPage reference remains valid.
52451**
52452** The isCommit flag indicates that there is no need to remember that
52453** the journal needs to be sync()ed before database page pDbPage->pgno
52454** can be written to. The caller has already promised not to write to that
52455** page.
52456*/
52457static int relocatePage(
52458  BtShared *pBt,           /* Btree */
52459  MemPage *pDbPage,        /* Open page to move */
52460  u8 eType,                /* Pointer map 'type' entry for pDbPage */
52461  Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
52462  Pgno iFreePage,          /* The location to move pDbPage to */
52463  int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
52464){
52465  MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
52466  Pgno iDbPage = pDbPage->pgno;
52467  Pager *pPager = pBt->pPager;
52468  int rc;
52469
52470  assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
52471      eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
52472  assert( sqlite3_mutex_held(pBt->mutex) );
52473  assert( pDbPage->pBt==pBt );
52474
52475  /* Move page iDbPage from its current location to page number iFreePage */
52476  TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
52477      iDbPage, iFreePage, iPtrPage, eType));
52478  rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
52479  if( rc!=SQLITE_OK ){
52480    return rc;
52481  }
52482  pDbPage->pgno = iFreePage;
52483
52484  /* If pDbPage was a btree-page, then it may have child pages and/or cells
52485  ** that point to overflow pages. The pointer map entries for all these
52486  ** pages need to be changed.
52487  **
52488  ** If pDbPage is an overflow page, then the first 4 bytes may store a
52489  ** pointer to a subsequent overflow page. If this is the case, then
52490  ** the pointer map needs to be updated for the subsequent overflow page.
52491  */
52492  if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
52493    rc = setChildPtrmaps(pDbPage);
52494    if( rc!=SQLITE_OK ){
52495      return rc;
52496    }
52497  }else{
52498    Pgno nextOvfl = get4byte(pDbPage->aData);
52499    if( nextOvfl!=0 ){
52500      ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
52501      if( rc!=SQLITE_OK ){
52502        return rc;
52503      }
52504    }
52505  }
52506
52507  /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
52508  ** that it points at iFreePage. Also fix the pointer map entry for
52509  ** iPtrPage.
52510  */
52511  if( eType!=PTRMAP_ROOTPAGE ){
52512    rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0, 0);
52513    if( rc!=SQLITE_OK ){
52514      return rc;
52515    }
52516    rc = sqlite3PagerWrite(pPtrPage->pDbPage);
52517    if( rc!=SQLITE_OK ){
52518      releasePage(pPtrPage);
52519      return rc;
52520    }
52521    rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
52522    releasePage(pPtrPage);
52523    if( rc==SQLITE_OK ){
52524      ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
52525    }
52526  }
52527  return rc;
52528}
52529
52530/* Forward declaration required by incrVacuumStep(). */
52531static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
52532
52533/*
52534** Perform a single step of an incremental-vacuum. If successful, return
52535** SQLITE_OK. If there is no work to do (and therefore no point in
52536** calling this function again), return SQLITE_DONE. Or, if an error
52537** occurs, return some other error code.
52538**
52539** More specificly, this function attempts to re-organize the database so
52540** that the last page of the file currently in use is no longer in use.
52541**
52542** Parameter nFin is the number of pages that this database would contain
52543** were this function called until it returns SQLITE_DONE.
52544**
52545** If the bCommit parameter is non-zero, this function assumes that the
52546** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
52547** or an error. bCommit is passed true for an auto-vacuum-on-commmit
52548** operation, or false for an incremental vacuum.
52549*/
52550static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
52551  Pgno nFreeList;           /* Number of pages still on the free-list */
52552  int rc;
52553
52554  assert( sqlite3_mutex_held(pBt->mutex) );
52555  assert( iLastPg>nFin );
52556
52557  if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
52558    u8 eType;
52559    Pgno iPtrPage;
52560
52561    nFreeList = get4byte(&pBt->pPage1->aData[36]);
52562    if( nFreeList==0 ){
52563      return SQLITE_DONE;
52564    }
52565
52566    rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
52567    if( rc!=SQLITE_OK ){
52568      return rc;
52569    }
52570    if( eType==PTRMAP_ROOTPAGE ){
52571      return SQLITE_CORRUPT_BKPT;
52572    }
52573
52574    if( eType==PTRMAP_FREEPAGE ){
52575      if( bCommit==0 ){
52576        /* Remove the page from the files free-list. This is not required
52577        ** if bCommit is non-zero. In that case, the free-list will be
52578        ** truncated to zero after this function returns, so it doesn't
52579        ** matter if it still contains some garbage entries.
52580        */
52581        Pgno iFreePg;
52582        MemPage *pFreePg;
52583        rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
52584        if( rc!=SQLITE_OK ){
52585          return rc;
52586        }
52587        assert( iFreePg==iLastPg );
52588        releasePage(pFreePg);
52589      }
52590    } else {
52591      Pgno iFreePg;             /* Index of free page to move pLastPg to */
52592      MemPage *pLastPg;
52593      u8 eMode = BTALLOC_ANY;   /* Mode parameter for allocateBtreePage() */
52594      Pgno iNear = 0;           /* nearby parameter for allocateBtreePage() */
52595
52596      rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0, 0);
52597      if( rc!=SQLITE_OK ){
52598        return rc;
52599      }
52600
52601      /* If bCommit is zero, this loop runs exactly once and page pLastPg
52602      ** is swapped with the first free page pulled off the free list.
52603      **
52604      ** On the other hand, if bCommit is greater than zero, then keep
52605      ** looping until a free-page located within the first nFin pages
52606      ** of the file is found.
52607      */
52608      if( bCommit==0 ){
52609        eMode = BTALLOC_LE;
52610        iNear = nFin;
52611      }
52612      do {
52613        MemPage *pFreePg;
52614        rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
52615        if( rc!=SQLITE_OK ){
52616          releasePage(pLastPg);
52617          return rc;
52618        }
52619        releasePage(pFreePg);
52620      }while( bCommit && iFreePg>nFin );
52621      assert( iFreePg<iLastPg );
52622
52623      rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
52624      releasePage(pLastPg);
52625      if( rc!=SQLITE_OK ){
52626        return rc;
52627      }
52628    }
52629  }
52630
52631  if( bCommit==0 ){
52632    do {
52633      iLastPg--;
52634    }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
52635    pBt->bDoTruncate = 1;
52636    pBt->nPage = iLastPg;
52637  }
52638  return SQLITE_OK;
52639}
52640
52641/*
52642** The database opened by the first argument is an auto-vacuum database
52643** nOrig pages in size containing nFree free pages. Return the expected
52644** size of the database in pages following an auto-vacuum operation.
52645*/
52646static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
52647  int nEntry;                     /* Number of entries on one ptrmap page */
52648  Pgno nPtrmap;                   /* Number of PtrMap pages to be freed */
52649  Pgno nFin;                      /* Return value */
52650
52651  nEntry = pBt->usableSize/5;
52652  nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
52653  nFin = nOrig - nFree - nPtrmap;
52654  if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
52655    nFin--;
52656  }
52657  while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
52658    nFin--;
52659  }
52660
52661  return nFin;
52662}
52663
52664/*
52665** A write-transaction must be opened before calling this function.
52666** It performs a single unit of work towards an incremental vacuum.
52667**
52668** If the incremental vacuum is finished after this function has run,
52669** SQLITE_DONE is returned. If it is not finished, but no error occurred,
52670** SQLITE_OK is returned. Otherwise an SQLite error code.
52671*/
52672SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
52673  int rc;
52674  BtShared *pBt = p->pBt;
52675
52676  sqlite3BtreeEnter(p);
52677  assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
52678  if( !pBt->autoVacuum ){
52679    rc = SQLITE_DONE;
52680  }else{
52681    Pgno nOrig = btreePagecount(pBt);
52682    Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
52683    Pgno nFin = finalDbSize(pBt, nOrig, nFree);
52684
52685    if( nOrig<nFin ){
52686      rc = SQLITE_CORRUPT_BKPT;
52687    }else if( nFree>0 ){
52688      rc = saveAllCursors(pBt, 0, 0);
52689      if( rc==SQLITE_OK ){
52690        invalidateAllOverflowCache(pBt);
52691        rc = incrVacuumStep(pBt, nFin, nOrig, 0);
52692      }
52693      if( rc==SQLITE_OK ){
52694        rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
52695        put4byte(&pBt->pPage1->aData[28], pBt->nPage);
52696      }
52697    }else{
52698      rc = SQLITE_DONE;
52699    }
52700  }
52701  sqlite3BtreeLeave(p);
52702  return rc;
52703}
52704
52705/*
52706** This routine is called prior to sqlite3PagerCommit when a transaction
52707** is commited for an auto-vacuum database.
52708**
52709** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
52710** the database file should be truncated to during the commit process.
52711** i.e. the database has been reorganized so that only the first *pnTrunc
52712** pages are in use.
52713*/
52714static int autoVacuumCommit(BtShared *pBt){
52715  int rc = SQLITE_OK;
52716  Pager *pPager = pBt->pPager;
52717  VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
52718
52719  assert( sqlite3_mutex_held(pBt->mutex) );
52720  invalidateAllOverflowCache(pBt);
52721  assert(pBt->autoVacuum);
52722  if( !pBt->incrVacuum ){
52723    Pgno nFin;         /* Number of pages in database after autovacuuming */
52724    Pgno nFree;        /* Number of pages on the freelist initially */
52725    Pgno iFree;        /* The next page to be freed */
52726    Pgno nOrig;        /* Database size before freeing */
52727
52728    nOrig = btreePagecount(pBt);
52729    if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
52730      /* It is not possible to create a database for which the final page
52731      ** is either a pointer-map page or the pending-byte page. If one
52732      ** is encountered, this indicates corruption.
52733      */
52734      return SQLITE_CORRUPT_BKPT;
52735    }
52736
52737    nFree = get4byte(&pBt->pPage1->aData[36]);
52738    nFin = finalDbSize(pBt, nOrig, nFree);
52739    if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
52740    if( nFin<nOrig ){
52741      rc = saveAllCursors(pBt, 0, 0);
52742    }
52743    for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
52744      rc = incrVacuumStep(pBt, nFin, iFree, 1);
52745    }
52746    if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
52747      rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
52748      put4byte(&pBt->pPage1->aData[32], 0);
52749      put4byte(&pBt->pPage1->aData[36], 0);
52750      put4byte(&pBt->pPage1->aData[28], nFin);
52751      pBt->bDoTruncate = 1;
52752      pBt->nPage = nFin;
52753    }
52754    if( rc!=SQLITE_OK ){
52755      sqlite3PagerRollback(pPager);
52756    }
52757  }
52758
52759  assert( nRef>=sqlite3PagerRefcount(pPager) );
52760  return rc;
52761}
52762
52763#else /* ifndef SQLITE_OMIT_AUTOVACUUM */
52764# define setChildPtrmaps(x) SQLITE_OK
52765#endif
52766
52767/*
52768** This routine does the first phase of a two-phase commit.  This routine
52769** causes a rollback journal to be created (if it does not already exist)
52770** and populated with enough information so that if a power loss occurs
52771** the database can be restored to its original state by playing back
52772** the journal.  Then the contents of the journal are flushed out to
52773** the disk.  After the journal is safely on oxide, the changes to the
52774** database are written into the database file and flushed to oxide.
52775** At the end of this call, the rollback journal still exists on the
52776** disk and we are still holding all locks, so the transaction has not
52777** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
52778** commit process.
52779**
52780** This call is a no-op if no write-transaction is currently active on pBt.
52781**
52782** Otherwise, sync the database file for the btree pBt. zMaster points to
52783** the name of a master journal file that should be written into the
52784** individual journal file, or is NULL, indicating no master journal file
52785** (single database transaction).
52786**
52787** When this is called, the master journal should already have been
52788** created, populated with this journal pointer and synced to disk.
52789**
52790** Once this is routine has returned, the only thing required to commit
52791** the write-transaction for this database file is to delete the journal.
52792*/
52793SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
52794  int rc = SQLITE_OK;
52795  if( p->inTrans==TRANS_WRITE ){
52796    BtShared *pBt = p->pBt;
52797    sqlite3BtreeEnter(p);
52798#ifndef SQLITE_OMIT_AUTOVACUUM
52799    if( pBt->autoVacuum ){
52800      rc = autoVacuumCommit(pBt);
52801      if( rc!=SQLITE_OK ){
52802        sqlite3BtreeLeave(p);
52803        return rc;
52804      }
52805    }
52806    if( pBt->bDoTruncate ){
52807      sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
52808    }
52809#endif
52810    rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
52811    sqlite3BtreeLeave(p);
52812  }
52813  return rc;
52814}
52815
52816/*
52817** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
52818** at the conclusion of a transaction.
52819*/
52820static void btreeEndTransaction(Btree *p){
52821  BtShared *pBt = p->pBt;
52822  assert( sqlite3BtreeHoldsMutex(p) );
52823
52824#ifndef SQLITE_OMIT_AUTOVACUUM
52825  pBt->bDoTruncate = 0;
52826#endif
52827  if( p->inTrans>TRANS_NONE && p->db->activeVdbeCnt>1 ){
52828    /* If there are other active statements that belong to this database
52829    ** handle, downgrade to a read-only transaction. The other statements
52830    ** may still be reading from the database.  */
52831    downgradeAllSharedCacheTableLocks(p);
52832    p->inTrans = TRANS_READ;
52833  }else{
52834    /* If the handle had any kind of transaction open, decrement the
52835    ** transaction count of the shared btree. If the transaction count
52836    ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
52837    ** call below will unlock the pager.  */
52838    if( p->inTrans!=TRANS_NONE ){
52839      clearAllSharedCacheTableLocks(p);
52840      pBt->nTransaction--;
52841      if( 0==pBt->nTransaction ){
52842        pBt->inTransaction = TRANS_NONE;
52843      }
52844    }
52845
52846    /* Set the current transaction state to TRANS_NONE and unlock the
52847    ** pager if this call closed the only read or write transaction.  */
52848    p->inTrans = TRANS_NONE;
52849    unlockBtreeIfUnused(pBt);
52850  }
52851
52852  btreeIntegrity(p);
52853}
52854
52855/*
52856** Commit the transaction currently in progress.
52857**
52858** This routine implements the second phase of a 2-phase commit.  The
52859** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
52860** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
52861** routine did all the work of writing information out to disk and flushing the
52862** contents so that they are written onto the disk platter.  All this
52863** routine has to do is delete or truncate or zero the header in the
52864** the rollback journal (which causes the transaction to commit) and
52865** drop locks.
52866**
52867** Normally, if an error occurs while the pager layer is attempting to
52868** finalize the underlying journal file, this function returns an error and
52869** the upper layer will attempt a rollback. However, if the second argument
52870** is non-zero then this b-tree transaction is part of a multi-file
52871** transaction. In this case, the transaction has already been committed
52872** (by deleting a master journal file) and the caller will ignore this
52873** functions return code. So, even if an error occurs in the pager layer,
52874** reset the b-tree objects internal state to indicate that the write
52875** transaction has been closed. This is quite safe, as the pager will have
52876** transitioned to the error state.
52877**
52878** This will release the write lock on the database file.  If there
52879** are no active cursors, it also releases the read lock.
52880*/
52881SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
52882
52883  if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
52884  sqlite3BtreeEnter(p);
52885  btreeIntegrity(p);
52886
52887  /* If the handle has a write-transaction open, commit the shared-btrees
52888  ** transaction and set the shared state to TRANS_READ.
52889  */
52890  if( p->inTrans==TRANS_WRITE ){
52891    int rc;
52892    BtShared *pBt = p->pBt;
52893    assert( pBt->inTransaction==TRANS_WRITE );
52894    assert( pBt->nTransaction>0 );
52895    rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
52896    if( rc!=SQLITE_OK && bCleanup==0 ){
52897      sqlite3BtreeLeave(p);
52898      return rc;
52899    }
52900    pBt->inTransaction = TRANS_READ;
52901    btreeClearHasContent(pBt);
52902  }
52903
52904  btreeEndTransaction(p);
52905  sqlite3BtreeLeave(p);
52906  return SQLITE_OK;
52907}
52908
52909/*
52910** Do both phases of a commit.
52911*/
52912SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
52913  int rc;
52914  sqlite3BtreeEnter(p);
52915  rc = sqlite3BtreeCommitPhaseOne(p, 0);
52916  if( rc==SQLITE_OK ){
52917    rc = sqlite3BtreeCommitPhaseTwo(p, 0);
52918  }
52919  sqlite3BtreeLeave(p);
52920  return rc;
52921}
52922
52923/*
52924** This routine sets the state to CURSOR_FAULT and the error
52925** code to errCode for every cursor on BtShared that pBtree
52926** references.
52927**
52928** Every cursor is tripped, including cursors that belong
52929** to other database connections that happen to be sharing
52930** the cache with pBtree.
52931**
52932** This routine gets called when a rollback occurs.
52933** All cursors using the same cache must be tripped
52934** to prevent them from trying to use the btree after
52935** the rollback.  The rollback may have deleted tables
52936** or moved root pages, so it is not sufficient to
52937** save the state of the cursor.  The cursor must be
52938** invalidated.
52939*/
52940SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
52941  BtCursor *p;
52942  if( pBtree==0 ) return;
52943  sqlite3BtreeEnter(pBtree);
52944  for(p=pBtree->pBt->pCursor; p; p=p->pNext){
52945    int i;
52946    sqlite3BtreeClearCursor(p);
52947    p->eState = CURSOR_FAULT;
52948    p->skipNext = errCode;
52949    for(i=0; i<=p->iPage; i++){
52950      releasePage(p->apPage[i]);
52951      p->apPage[i] = 0;
52952    }
52953  }
52954  sqlite3BtreeLeave(pBtree);
52955}
52956
52957/*
52958** Rollback the transaction in progress.  All cursors will be
52959** invalided by this operation.  Any attempt to use a cursor
52960** that was open at the beginning of this operation will result
52961** in an error.
52962**
52963** This will release the write lock on the database file.  If there
52964** are no active cursors, it also releases the read lock.
52965*/
52966SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode){
52967  int rc;
52968  BtShared *pBt = p->pBt;
52969  MemPage *pPage1;
52970
52971  sqlite3BtreeEnter(p);
52972  if( tripCode==SQLITE_OK ){
52973    rc = tripCode = saveAllCursors(pBt, 0, 0);
52974  }else{
52975    rc = SQLITE_OK;
52976  }
52977  if( tripCode ){
52978    sqlite3BtreeTripAllCursors(p, tripCode);
52979  }
52980  btreeIntegrity(p);
52981
52982  if( p->inTrans==TRANS_WRITE ){
52983    int rc2;
52984
52985    assert( TRANS_WRITE==pBt->inTransaction );
52986    rc2 = sqlite3PagerRollback(pBt->pPager);
52987    if( rc2!=SQLITE_OK ){
52988      rc = rc2;
52989    }
52990
52991    /* The rollback may have destroyed the pPage1->aData value.  So
52992    ** call btreeGetPage() on page 1 again to make
52993    ** sure pPage1->aData is set correctly. */
52994    if( btreeGetPage(pBt, 1, &pPage1, 0, 0)==SQLITE_OK ){
52995      int nPage = get4byte(28+(u8*)pPage1->aData);
52996      testcase( nPage==0 );
52997      if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
52998      testcase( pBt->nPage!=nPage );
52999      pBt->nPage = nPage;
53000      releasePage(pPage1);
53001    }
53002    assert( countValidCursors(pBt, 1)==0 );
53003    pBt->inTransaction = TRANS_READ;
53004    btreeClearHasContent(pBt);
53005  }
53006
53007  btreeEndTransaction(p);
53008  sqlite3BtreeLeave(p);
53009  return rc;
53010}
53011
53012/*
53013** Start a statement subtransaction. The subtransaction can can be rolled
53014** back independently of the main transaction. You must start a transaction
53015** before starting a subtransaction. The subtransaction is ended automatically
53016** if the main transaction commits or rolls back.
53017**
53018** Statement subtransactions are used around individual SQL statements
53019** that are contained within a BEGIN...COMMIT block.  If a constraint
53020** error occurs within the statement, the effect of that one statement
53021** can be rolled back without having to rollback the entire transaction.
53022**
53023** A statement sub-transaction is implemented as an anonymous savepoint. The
53024** value passed as the second parameter is the total number of savepoints,
53025** including the new anonymous savepoint, open on the B-Tree. i.e. if there
53026** are no active savepoints and no other statement-transactions open,
53027** iStatement is 1. This anonymous savepoint can be released or rolled back
53028** using the sqlite3BtreeSavepoint() function.
53029*/
53030SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
53031  int rc;
53032  BtShared *pBt = p->pBt;
53033  sqlite3BtreeEnter(p);
53034  assert( p->inTrans==TRANS_WRITE );
53035  assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
53036  assert( iStatement>0 );
53037  assert( iStatement>p->db->nSavepoint );
53038  assert( pBt->inTransaction==TRANS_WRITE );
53039  /* At the pager level, a statement transaction is a savepoint with
53040  ** an index greater than all savepoints created explicitly using
53041  ** SQL statements. It is illegal to open, release or rollback any
53042  ** such savepoints while the statement transaction savepoint is active.
53043  */
53044  rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
53045  sqlite3BtreeLeave(p);
53046  return rc;
53047}
53048
53049/*
53050** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
53051** or SAVEPOINT_RELEASE. This function either releases or rolls back the
53052** savepoint identified by parameter iSavepoint, depending on the value
53053** of op.
53054**
53055** Normally, iSavepoint is greater than or equal to zero. However, if op is
53056** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
53057** contents of the entire transaction are rolled back. This is different
53058** from a normal transaction rollback, as no locks are released and the
53059** transaction remains open.
53060*/
53061SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
53062  int rc = SQLITE_OK;
53063  if( p && p->inTrans==TRANS_WRITE ){
53064    BtShared *pBt = p->pBt;
53065    assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
53066    assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
53067    sqlite3BtreeEnter(p);
53068    rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
53069    if( rc==SQLITE_OK ){
53070      if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
53071        pBt->nPage = 0;
53072      }
53073      rc = newDatabase(pBt);
53074      pBt->nPage = get4byte(28 + pBt->pPage1->aData);
53075
53076      /* The database size was written into the offset 28 of the header
53077      ** when the transaction started, so we know that the value at offset
53078      ** 28 is nonzero. */
53079      assert( pBt->nPage>0 );
53080    }
53081    sqlite3BtreeLeave(p);
53082  }
53083  return rc;
53084}
53085
53086/*
53087** Create a new cursor for the BTree whose root is on the page
53088** iTable. If a read-only cursor is requested, it is assumed that
53089** the caller already has at least a read-only transaction open
53090** on the database already. If a write-cursor is requested, then
53091** the caller is assumed to have an open write transaction.
53092**
53093** If wrFlag==0, then the cursor can only be used for reading.
53094** If wrFlag==1, then the cursor can be used for reading or for
53095** writing if other conditions for writing are also met.  These
53096** are the conditions that must be met in order for writing to
53097** be allowed:
53098**
53099** 1:  The cursor must have been opened with wrFlag==1
53100**
53101** 2:  Other database connections that share the same pager cache
53102**     but which are not in the READ_UNCOMMITTED state may not have
53103**     cursors open with wrFlag==0 on the same table.  Otherwise
53104**     the changes made by this write cursor would be visible to
53105**     the read cursors in the other database connection.
53106**
53107** 3:  The database must be writable (not on read-only media)
53108**
53109** 4:  There must be an active transaction.
53110**
53111** No checking is done to make sure that page iTable really is the
53112** root page of a b-tree.  If it is not, then the cursor acquired
53113** will not work correctly.
53114**
53115** It is assumed that the sqlite3BtreeCursorZero() has been called
53116** on pCur to initialize the memory space prior to invoking this routine.
53117*/
53118static int btreeCursor(
53119  Btree *p,                              /* The btree */
53120  int iTable,                            /* Root page of table to open */
53121  int wrFlag,                            /* 1 to write. 0 read-only */
53122  struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
53123  BtCursor *pCur                         /* Space for new cursor */
53124){
53125  BtShared *pBt = p->pBt;                /* Shared b-tree handle */
53126
53127  assert( sqlite3BtreeHoldsMutex(p) );
53128  assert( wrFlag==0 || wrFlag==1 );
53129
53130  /* The following assert statements verify that if this is a sharable
53131  ** b-tree database, the connection is holding the required table locks,
53132  ** and that no other connection has any open cursor that conflicts with
53133  ** this lock.  */
53134  assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
53135  assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
53136
53137  /* Assert that the caller has opened the required transaction. */
53138  assert( p->inTrans>TRANS_NONE );
53139  assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
53140  assert( pBt->pPage1 && pBt->pPage1->aData );
53141
53142  if( NEVER(wrFlag && (pBt->btsFlags & BTS_READ_ONLY)!=0) ){
53143    return SQLITE_READONLY;
53144  }
53145  if( iTable==1 && btreePagecount(pBt)==0 ){
53146    assert( wrFlag==0 );
53147    iTable = 0;
53148  }
53149
53150  /* Now that no other errors can occur, finish filling in the BtCursor
53151  ** variables and link the cursor into the BtShared list.  */
53152  pCur->pgnoRoot = (Pgno)iTable;
53153  pCur->iPage = -1;
53154  pCur->pKeyInfo = pKeyInfo;
53155  pCur->pBtree = p;
53156  pCur->pBt = pBt;
53157  pCur->wrFlag = (u8)wrFlag;
53158  pCur->pNext = pBt->pCursor;
53159  if( pCur->pNext ){
53160    pCur->pNext->pPrev = pCur;
53161  }
53162  pBt->pCursor = pCur;
53163  pCur->eState = CURSOR_INVALID;
53164  pCur->cachedRowid = 0;
53165  return SQLITE_OK;
53166}
53167SQLITE_PRIVATE int sqlite3BtreeCursor(
53168  Btree *p,                                   /* The btree */
53169  int iTable,                                 /* Root page of table to open */
53170  int wrFlag,                                 /* 1 to write. 0 read-only */
53171  struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
53172  BtCursor *pCur                              /* Write new cursor here */
53173){
53174  int rc;
53175  sqlite3BtreeEnter(p);
53176  rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
53177  sqlite3BtreeLeave(p);
53178  return rc;
53179}
53180
53181/*
53182** Return the size of a BtCursor object in bytes.
53183**
53184** This interfaces is needed so that users of cursors can preallocate
53185** sufficient storage to hold a cursor.  The BtCursor object is opaque
53186** to users so they cannot do the sizeof() themselves - they must call
53187** this routine.
53188*/
53189SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
53190  return ROUND8(sizeof(BtCursor));
53191}
53192
53193/*
53194** Initialize memory that will be converted into a BtCursor object.
53195**
53196** The simple approach here would be to memset() the entire object
53197** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
53198** do not need to be zeroed and they are large, so we can save a lot
53199** of run-time by skipping the initialization of those elements.
53200*/
53201SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
53202  memset(p, 0, offsetof(BtCursor, iPage));
53203}
53204
53205/*
53206** Set the cached rowid value of every cursor in the same database file
53207** as pCur and having the same root page number as pCur.  The value is
53208** set to iRowid.
53209**
53210** Only positive rowid values are considered valid for this cache.
53211** The cache is initialized to zero, indicating an invalid cache.
53212** A btree will work fine with zero or negative rowids.  We just cannot
53213** cache zero or negative rowids, which means tables that use zero or
53214** negative rowids might run a little slower.  But in practice, zero
53215** or negative rowids are very uncommon so this should not be a problem.
53216*/
53217SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
53218  BtCursor *p;
53219  for(p=pCur->pBt->pCursor; p; p=p->pNext){
53220    if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
53221  }
53222  assert( pCur->cachedRowid==iRowid );
53223}
53224
53225/*
53226** Return the cached rowid for the given cursor.  A negative or zero
53227** return value indicates that the rowid cache is invalid and should be
53228** ignored.  If the rowid cache has never before been set, then a
53229** zero is returned.
53230*/
53231SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
53232  return pCur->cachedRowid;
53233}
53234
53235/*
53236** Close a cursor.  The read lock on the database file is released
53237** when the last cursor is closed.
53238*/
53239SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
53240  Btree *pBtree = pCur->pBtree;
53241  if( pBtree ){
53242    int i;
53243    BtShared *pBt = pCur->pBt;
53244    sqlite3BtreeEnter(pBtree);
53245    sqlite3BtreeClearCursor(pCur);
53246    if( pCur->pPrev ){
53247      pCur->pPrev->pNext = pCur->pNext;
53248    }else{
53249      pBt->pCursor = pCur->pNext;
53250    }
53251    if( pCur->pNext ){
53252      pCur->pNext->pPrev = pCur->pPrev;
53253    }
53254    for(i=0; i<=pCur->iPage; i++){
53255      releasePage(pCur->apPage[i]);
53256    }
53257    unlockBtreeIfUnused(pBt);
53258    invalidateOverflowCache(pCur);
53259    /* sqlite3_free(pCur); */
53260    sqlite3BtreeLeave(pBtree);
53261  }
53262  return SQLITE_OK;
53263}
53264
53265/*
53266** Make sure the BtCursor* given in the argument has a valid
53267** BtCursor.info structure.  If it is not already valid, call
53268** btreeParseCell() to fill it in.
53269**
53270** BtCursor.info is a cache of the information in the current cell.
53271** Using this cache reduces the number of calls to btreeParseCell().
53272**
53273** 2007-06-25:  There is a bug in some versions of MSVC that cause the
53274** compiler to crash when getCellInfo() is implemented as a macro.
53275** But there is a measureable speed advantage to using the macro on gcc
53276** (when less compiler optimizations like -Os or -O0 are used and the
53277** compiler is not doing agressive inlining.)  So we use a real function
53278** for MSVC and a macro for everything else.  Ticket #2457.
53279*/
53280#ifndef NDEBUG
53281  static void assertCellInfo(BtCursor *pCur){
53282    CellInfo info;
53283    int iPage = pCur->iPage;
53284    memset(&info, 0, sizeof(info));
53285    btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
53286    assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
53287  }
53288#else
53289  #define assertCellInfo(x)
53290#endif
53291#ifdef _MSC_VER
53292  /* Use a real function in MSVC to work around bugs in that compiler. */
53293  static void getCellInfo(BtCursor *pCur){
53294    if( pCur->info.nSize==0 ){
53295      int iPage = pCur->iPage;
53296      btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
53297      pCur->validNKey = 1;
53298    }else{
53299      assertCellInfo(pCur);
53300    }
53301  }
53302#else /* if not _MSC_VER */
53303  /* Use a macro in all other compilers so that the function is inlined */
53304#define getCellInfo(pCur)                                                      \
53305  if( pCur->info.nSize==0 ){                                                   \
53306    int iPage = pCur->iPage;                                                   \
53307    btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
53308    pCur->validNKey = 1;                                                       \
53309  }else{                                                                       \
53310    assertCellInfo(pCur);                                                      \
53311  }
53312#endif /* _MSC_VER */
53313
53314#ifndef NDEBUG  /* The next routine used only within assert() statements */
53315/*
53316** Return true if the given BtCursor is valid.  A valid cursor is one
53317** that is currently pointing to a row in a (non-empty) table.
53318** This is a verification routine is used only within assert() statements.
53319*/
53320SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
53321  return pCur && pCur->eState==CURSOR_VALID;
53322}
53323#endif /* NDEBUG */
53324
53325/*
53326** Set *pSize to the size of the buffer needed to hold the value of
53327** the key for the current entry.  If the cursor is not pointing
53328** to a valid entry, *pSize is set to 0.
53329**
53330** For a table with the INTKEY flag set, this routine returns the key
53331** itself, not the number of bytes in the key.
53332**
53333** The caller must position the cursor prior to invoking this routine.
53334**
53335** This routine cannot fail.  It always returns SQLITE_OK.
53336*/
53337SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
53338  assert( cursorHoldsMutex(pCur) );
53339  assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
53340  if( pCur->eState!=CURSOR_VALID ){
53341    *pSize = 0;
53342  }else{
53343    getCellInfo(pCur);
53344    *pSize = pCur->info.nKey;
53345  }
53346  return SQLITE_OK;
53347}
53348
53349/*
53350** Set *pSize to the number of bytes of data in the entry the
53351** cursor currently points to.
53352**
53353** The caller must guarantee that the cursor is pointing to a non-NULL
53354** valid entry.  In other words, the calling procedure must guarantee
53355** that the cursor has Cursor.eState==CURSOR_VALID.
53356**
53357** Failure is not possible.  This function always returns SQLITE_OK.
53358** It might just as well be a procedure (returning void) but we continue
53359** to return an integer result code for historical reasons.
53360*/
53361SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
53362  assert( cursorHoldsMutex(pCur) );
53363  assert( pCur->eState==CURSOR_VALID );
53364  getCellInfo(pCur);
53365  *pSize = pCur->info.nData;
53366  return SQLITE_OK;
53367}
53368
53369/*
53370** Given the page number of an overflow page in the database (parameter
53371** ovfl), this function finds the page number of the next page in the
53372** linked list of overflow pages. If possible, it uses the auto-vacuum
53373** pointer-map data instead of reading the content of page ovfl to do so.
53374**
53375** If an error occurs an SQLite error code is returned. Otherwise:
53376**
53377** The page number of the next overflow page in the linked list is
53378** written to *pPgnoNext. If page ovfl is the last page in its linked
53379** list, *pPgnoNext is set to zero.
53380**
53381** If ppPage is not NULL, and a reference to the MemPage object corresponding
53382** to page number pOvfl was obtained, then *ppPage is set to point to that
53383** reference. It is the responsibility of the caller to call releasePage()
53384** on *ppPage to free the reference. In no reference was obtained (because
53385** the pointer-map was used to obtain the value for *pPgnoNext), then
53386** *ppPage is set to zero.
53387*/
53388static int getOverflowPage(
53389  BtShared *pBt,               /* The database file */
53390  Pgno ovfl,                   /* Current overflow page number */
53391  MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
53392  Pgno *pPgnoNext              /* OUT: Next overflow page number */
53393){
53394  Pgno next = 0;
53395  MemPage *pPage = 0;
53396  int rc = SQLITE_OK;
53397
53398  assert( sqlite3_mutex_held(pBt->mutex) );
53399  assert(pPgnoNext);
53400
53401#ifndef SQLITE_OMIT_AUTOVACUUM
53402  /* Try to find the next page in the overflow list using the
53403  ** autovacuum pointer-map pages. Guess that the next page in
53404  ** the overflow list is page number (ovfl+1). If that guess turns
53405  ** out to be wrong, fall back to loading the data of page
53406  ** number ovfl to determine the next page number.
53407  */
53408  if( pBt->autoVacuum ){
53409    Pgno pgno;
53410    Pgno iGuess = ovfl+1;
53411    u8 eType;
53412
53413    while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
53414      iGuess++;
53415    }
53416
53417    if( iGuess<=btreePagecount(pBt) ){
53418      rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
53419      if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
53420        next = iGuess;
53421        rc = SQLITE_DONE;
53422      }
53423    }
53424  }
53425#endif
53426
53427  assert( next==0 || rc==SQLITE_DONE );
53428  if( rc==SQLITE_OK ){
53429    rc = btreeGetPage(pBt, ovfl, &pPage, 0, (ppPage==0));
53430    assert( rc==SQLITE_OK || pPage==0 );
53431    if( rc==SQLITE_OK ){
53432      next = get4byte(pPage->aData);
53433    }
53434  }
53435
53436  *pPgnoNext = next;
53437  if( ppPage ){
53438    *ppPage = pPage;
53439  }else{
53440    releasePage(pPage);
53441  }
53442  return (rc==SQLITE_DONE ? SQLITE_OK : rc);
53443}
53444
53445/*
53446** Copy data from a buffer to a page, or from a page to a buffer.
53447**
53448** pPayload is a pointer to data stored on database page pDbPage.
53449** If argument eOp is false, then nByte bytes of data are copied
53450** from pPayload to the buffer pointed at by pBuf. If eOp is true,
53451** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
53452** of data are copied from the buffer pBuf to pPayload.
53453**
53454** SQLITE_OK is returned on success, otherwise an error code.
53455*/
53456static int copyPayload(
53457  void *pPayload,           /* Pointer to page data */
53458  void *pBuf,               /* Pointer to buffer */
53459  int nByte,                /* Number of bytes to copy */
53460  int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
53461  DbPage *pDbPage           /* Page containing pPayload */
53462){
53463  if( eOp ){
53464    /* Copy data from buffer to page (a write operation) */
53465    int rc = sqlite3PagerWrite(pDbPage);
53466    if( rc!=SQLITE_OK ){
53467      return rc;
53468    }
53469    memcpy(pPayload, pBuf, nByte);
53470  }else{
53471    /* Copy data from page to buffer (a read operation) */
53472    memcpy(pBuf, pPayload, nByte);
53473  }
53474  return SQLITE_OK;
53475}
53476
53477/*
53478** This function is used to read or overwrite payload information
53479** for the entry that the pCur cursor is pointing to. If the eOp
53480** parameter is 0, this is a read operation (data copied into
53481** buffer pBuf). If it is non-zero, a write (data copied from
53482** buffer pBuf).
53483**
53484** A total of "amt" bytes are read or written beginning at "offset".
53485** Data is read to or from the buffer pBuf.
53486**
53487** The content being read or written might appear on the main page
53488** or be scattered out on multiple overflow pages.
53489**
53490** If the BtCursor.isIncrblobHandle flag is set, and the current
53491** cursor entry uses one or more overflow pages, this function
53492** allocates space for and lazily popluates the overflow page-list
53493** cache array (BtCursor.aOverflow). Subsequent calls use this
53494** cache to make seeking to the supplied offset more efficient.
53495**
53496** Once an overflow page-list cache has been allocated, it may be
53497** invalidated if some other cursor writes to the same table, or if
53498** the cursor is moved to a different row. Additionally, in auto-vacuum
53499** mode, the following events may invalidate an overflow page-list cache.
53500**
53501**   * An incremental vacuum,
53502**   * A commit in auto_vacuum="full" mode,
53503**   * Creating a table (may require moving an overflow page).
53504*/
53505static int accessPayload(
53506  BtCursor *pCur,      /* Cursor pointing to entry to read from */
53507  u32 offset,          /* Begin reading this far into payload */
53508  u32 amt,             /* Read this many bytes */
53509  unsigned char *pBuf, /* Write the bytes into this buffer */
53510  int eOp              /* zero to read. non-zero to write. */
53511){
53512  unsigned char *aPayload;
53513  int rc = SQLITE_OK;
53514  u32 nKey;
53515  int iIdx = 0;
53516  MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
53517  BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
53518
53519  assert( pPage );
53520  assert( pCur->eState==CURSOR_VALID );
53521  assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
53522  assert( cursorHoldsMutex(pCur) );
53523
53524  getCellInfo(pCur);
53525  aPayload = pCur->info.pCell + pCur->info.nHeader;
53526  nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
53527
53528  if( NEVER(offset+amt > nKey+pCur->info.nData)
53529   || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
53530  ){
53531    /* Trying to read or write past the end of the data is an error */
53532    return SQLITE_CORRUPT_BKPT;
53533  }
53534
53535  /* Check if data must be read/written to/from the btree page itself. */
53536  if( offset<pCur->info.nLocal ){
53537    int a = amt;
53538    if( a+offset>pCur->info.nLocal ){
53539      a = pCur->info.nLocal - offset;
53540    }
53541    rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
53542    offset = 0;
53543    pBuf += a;
53544    amt -= a;
53545  }else{
53546    offset -= pCur->info.nLocal;
53547  }
53548
53549  if( rc==SQLITE_OK && amt>0 ){
53550    const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
53551    Pgno nextPage;
53552
53553    nextPage = get4byte(&aPayload[pCur->info.nLocal]);
53554
53555#ifndef SQLITE_OMIT_INCRBLOB
53556    /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
53557    ** has not been allocated, allocate it now. The array is sized at
53558    ** one entry for each overflow page in the overflow chain. The
53559    ** page number of the first overflow page is stored in aOverflow[0],
53560    ** etc. A value of 0 in the aOverflow[] array means "not yet known"
53561    ** (the cache is lazily populated).
53562    */
53563    if( pCur->isIncrblobHandle && !pCur->aOverflow ){
53564      int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
53565      pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
53566      /* nOvfl is always positive.  If it were zero, fetchPayload would have
53567      ** been used instead of this routine. */
53568      if( ALWAYS(nOvfl) && !pCur->aOverflow ){
53569        rc = SQLITE_NOMEM;
53570      }
53571    }
53572
53573    /* If the overflow page-list cache has been allocated and the
53574    ** entry for the first required overflow page is valid, skip
53575    ** directly to it.
53576    */
53577    if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
53578      iIdx = (offset/ovflSize);
53579      nextPage = pCur->aOverflow[iIdx];
53580      offset = (offset%ovflSize);
53581    }
53582#endif
53583
53584    for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
53585
53586#ifndef SQLITE_OMIT_INCRBLOB
53587      /* If required, populate the overflow page-list cache. */
53588      if( pCur->aOverflow ){
53589        assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
53590        pCur->aOverflow[iIdx] = nextPage;
53591      }
53592#endif
53593
53594      if( offset>=ovflSize ){
53595        /* The only reason to read this page is to obtain the page
53596        ** number for the next page in the overflow chain. The page
53597        ** data is not required. So first try to lookup the overflow
53598        ** page-list cache, if any, then fall back to the getOverflowPage()
53599        ** function.
53600        */
53601#ifndef SQLITE_OMIT_INCRBLOB
53602        if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
53603          nextPage = pCur->aOverflow[iIdx+1];
53604        } else
53605#endif
53606          rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
53607        offset -= ovflSize;
53608      }else{
53609        /* Need to read this page properly. It contains some of the
53610        ** range of data that is being read (eOp==0) or written (eOp!=0).
53611        */
53612#ifdef SQLITE_DIRECT_OVERFLOW_READ
53613        sqlite3_file *fd;
53614#endif
53615        int a = amt;
53616        if( a + offset > ovflSize ){
53617          a = ovflSize - offset;
53618        }
53619
53620#ifdef SQLITE_DIRECT_OVERFLOW_READ
53621        /* If all the following are true:
53622        **
53623        **   1) this is a read operation, and
53624        **   2) data is required from the start of this overflow page, and
53625        **   3) the database is file-backed, and
53626        **   4) there is no open write-transaction, and
53627        **   5) the database is not a WAL database,
53628        **
53629        ** then data can be read directly from the database file into the
53630        ** output buffer, bypassing the page-cache altogether. This speeds
53631        ** up loading large records that span many overflow pages.
53632        */
53633        if( eOp==0                                             /* (1) */
53634         && offset==0                                          /* (2) */
53635         && pBt->inTransaction==TRANS_READ                     /* (4) */
53636         && (fd = sqlite3PagerFile(pBt->pPager))->pMethods     /* (3) */
53637         && pBt->pPage1->aData[19]==0x01                       /* (5) */
53638        ){
53639          u8 aSave[4];
53640          u8 *aWrite = &pBuf[-4];
53641          memcpy(aSave, aWrite, 4);
53642          rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
53643          nextPage = get4byte(aWrite);
53644          memcpy(aWrite, aSave, 4);
53645        }else
53646#endif
53647
53648        {
53649          DbPage *pDbPage;
53650          rc = sqlite3PagerAcquire(pBt->pPager, nextPage, &pDbPage,
53651              (eOp==0 ? PAGER_ACQUIRE_READONLY : 0)
53652          );
53653          if( rc==SQLITE_OK ){
53654            aPayload = sqlite3PagerGetData(pDbPage);
53655            nextPage = get4byte(aPayload);
53656            rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
53657            sqlite3PagerUnref(pDbPage);
53658            offset = 0;
53659          }
53660        }
53661        amt -= a;
53662        pBuf += a;
53663      }
53664    }
53665  }
53666
53667  if( rc==SQLITE_OK && amt>0 ){
53668    return SQLITE_CORRUPT_BKPT;
53669  }
53670  return rc;
53671}
53672
53673/*
53674** Read part of the key associated with cursor pCur.  Exactly
53675** "amt" bytes will be transfered into pBuf[].  The transfer
53676** begins at "offset".
53677**
53678** The caller must ensure that pCur is pointing to a valid row
53679** in the table.
53680**
53681** Return SQLITE_OK on success or an error code if anything goes
53682** wrong.  An error is returned if "offset+amt" is larger than
53683** the available payload.
53684*/
53685SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
53686  assert( cursorHoldsMutex(pCur) );
53687  assert( pCur->eState==CURSOR_VALID );
53688  assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
53689  assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
53690  return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
53691}
53692
53693/*
53694** Read part of the data associated with cursor pCur.  Exactly
53695** "amt" bytes will be transfered into pBuf[].  The transfer
53696** begins at "offset".
53697**
53698** Return SQLITE_OK on success or an error code if anything goes
53699** wrong.  An error is returned if "offset+amt" is larger than
53700** the available payload.
53701*/
53702SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
53703  int rc;
53704
53705#ifndef SQLITE_OMIT_INCRBLOB
53706  if ( pCur->eState==CURSOR_INVALID ){
53707    return SQLITE_ABORT;
53708  }
53709#endif
53710
53711  assert( cursorHoldsMutex(pCur) );
53712  rc = restoreCursorPosition(pCur);
53713  if( rc==SQLITE_OK ){
53714    assert( pCur->eState==CURSOR_VALID );
53715    assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
53716    assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
53717    rc = accessPayload(pCur, offset, amt, pBuf, 0);
53718  }
53719  return rc;
53720}
53721
53722/*
53723** Return a pointer to payload information from the entry that the
53724** pCur cursor is pointing to.  The pointer is to the beginning of
53725** the key if skipKey==0 and it points to the beginning of data if
53726** skipKey==1.  The number of bytes of available key/data is written
53727** into *pAmt.  If *pAmt==0, then the value returned will not be
53728** a valid pointer.
53729**
53730** This routine is an optimization.  It is common for the entire key
53731** and data to fit on the local page and for there to be no overflow
53732** pages.  When that is so, this routine can be used to access the
53733** key and data without making a copy.  If the key and/or data spills
53734** onto overflow pages, then accessPayload() must be used to reassemble
53735** the key/data and copy it into a preallocated buffer.
53736**
53737** The pointer returned by this routine looks directly into the cached
53738** page of the database.  The data might change or move the next time
53739** any btree routine is called.
53740*/
53741static const unsigned char *fetchPayload(
53742  BtCursor *pCur,      /* Cursor pointing to entry to read from */
53743  int *pAmt,           /* Write the number of available bytes here */
53744  int skipKey          /* read beginning at data if this is true */
53745){
53746  unsigned char *aPayload;
53747  MemPage *pPage;
53748  u32 nKey;
53749  u32 nLocal;
53750
53751  assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
53752  assert( pCur->eState==CURSOR_VALID );
53753  assert( cursorHoldsMutex(pCur) );
53754  pPage = pCur->apPage[pCur->iPage];
53755  assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
53756  if( NEVER(pCur->info.nSize==0) ){
53757    btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage],
53758                   &pCur->info);
53759  }
53760  aPayload = pCur->info.pCell;
53761  aPayload += pCur->info.nHeader;
53762  if( pPage->intKey ){
53763    nKey = 0;
53764  }else{
53765    nKey = (int)pCur->info.nKey;
53766  }
53767  if( skipKey ){
53768    aPayload += nKey;
53769    nLocal = pCur->info.nLocal - nKey;
53770  }else{
53771    nLocal = pCur->info.nLocal;
53772    assert( nLocal<=nKey );
53773  }
53774  *pAmt = nLocal;
53775  return aPayload;
53776}
53777
53778
53779/*
53780** For the entry that cursor pCur is point to, return as
53781** many bytes of the key or data as are available on the local
53782** b-tree page.  Write the number of available bytes into *pAmt.
53783**
53784** The pointer returned is ephemeral.  The key/data may move
53785** or be destroyed on the next call to any Btree routine,
53786** including calls from other threads against the same cache.
53787** Hence, a mutex on the BtShared should be held prior to calling
53788** this routine.
53789**
53790** These routines is used to get quick access to key and data
53791** in the common case where no overflow pages are used.
53792*/
53793SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
53794  const void *p = 0;
53795  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
53796  assert( cursorHoldsMutex(pCur) );
53797  if( ALWAYS(pCur->eState==CURSOR_VALID) ){
53798    p = (const void*)fetchPayload(pCur, pAmt, 0);
53799  }
53800  return p;
53801}
53802SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
53803  const void *p = 0;
53804  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
53805  assert( cursorHoldsMutex(pCur) );
53806  if( ALWAYS(pCur->eState==CURSOR_VALID) ){
53807    p = (const void*)fetchPayload(pCur, pAmt, 1);
53808  }
53809  return p;
53810}
53811
53812
53813/*
53814** Move the cursor down to a new child page.  The newPgno argument is the
53815** page number of the child page to move to.
53816**
53817** This function returns SQLITE_CORRUPT if the page-header flags field of
53818** the new child page does not match the flags field of the parent (i.e.
53819** if an intkey page appears to be the parent of a non-intkey page, or
53820** vice-versa).
53821*/
53822static int moveToChild(BtCursor *pCur, u32 newPgno){
53823  int rc;
53824  int i = pCur->iPage;
53825  MemPage *pNewPage;
53826  BtShared *pBt = pCur->pBt;
53827
53828  assert( cursorHoldsMutex(pCur) );
53829  assert( pCur->eState==CURSOR_VALID );
53830  assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
53831  assert( pCur->iPage>=0 );
53832  if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
53833    return SQLITE_CORRUPT_BKPT;
53834  }
53835  rc = getAndInitPage(pBt, newPgno, &pNewPage, (pCur->wrFlag==0));
53836  if( rc ) return rc;
53837  pCur->apPage[i+1] = pNewPage;
53838  pCur->aiIdx[i+1] = 0;
53839  pCur->iPage++;
53840
53841  pCur->info.nSize = 0;
53842  pCur->validNKey = 0;
53843  if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
53844    return SQLITE_CORRUPT_BKPT;
53845  }
53846  return SQLITE_OK;
53847}
53848
53849#if 0
53850/*
53851** Page pParent is an internal (non-leaf) tree page. This function
53852** asserts that page number iChild is the left-child if the iIdx'th
53853** cell in page pParent. Or, if iIdx is equal to the total number of
53854** cells in pParent, that page number iChild is the right-child of
53855** the page.
53856*/
53857static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
53858  assert( iIdx<=pParent->nCell );
53859  if( iIdx==pParent->nCell ){
53860    assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
53861  }else{
53862    assert( get4byte(findCell(pParent, iIdx))==iChild );
53863  }
53864}
53865#else
53866#  define assertParentIndex(x,y,z)
53867#endif
53868
53869/*
53870** Move the cursor up to the parent page.
53871**
53872** pCur->idx is set to the cell index that contains the pointer
53873** to the page we are coming from.  If we are coming from the
53874** right-most child page then pCur->idx is set to one more than
53875** the largest cell index.
53876*/
53877static void moveToParent(BtCursor *pCur){
53878  assert( cursorHoldsMutex(pCur) );
53879  assert( pCur->eState==CURSOR_VALID );
53880  assert( pCur->iPage>0 );
53881  assert( pCur->apPage[pCur->iPage] );
53882
53883  /* UPDATE: It is actually possible for the condition tested by the assert
53884  ** below to be untrue if the database file is corrupt. This can occur if
53885  ** one cursor has modified page pParent while a reference to it is held
53886  ** by a second cursor. Which can only happen if a single page is linked
53887  ** into more than one b-tree structure in a corrupt database.  */
53888#if 0
53889  assertParentIndex(
53890    pCur->apPage[pCur->iPage-1],
53891    pCur->aiIdx[pCur->iPage-1],
53892    pCur->apPage[pCur->iPage]->pgno
53893  );
53894#endif
53895  testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
53896
53897  releasePage(pCur->apPage[pCur->iPage]);
53898  pCur->iPage--;
53899  pCur->info.nSize = 0;
53900  pCur->validNKey = 0;
53901}
53902
53903/*
53904** Move the cursor to point to the root page of its b-tree structure.
53905**
53906** If the table has a virtual root page, then the cursor is moved to point
53907** to the virtual root page instead of the actual root page. A table has a
53908** virtual root page when the actual root page contains no cells and a
53909** single child page. This can only happen with the table rooted at page 1.
53910**
53911** If the b-tree structure is empty, the cursor state is set to
53912** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
53913** cell located on the root (or virtual root) page and the cursor state
53914** is set to CURSOR_VALID.
53915**
53916** If this function returns successfully, it may be assumed that the
53917** page-header flags indicate that the [virtual] root-page is the expected
53918** kind of b-tree page (i.e. if when opening the cursor the caller did not
53919** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
53920** indicating a table b-tree, or if the caller did specify a KeyInfo
53921** structure the flags byte is set to 0x02 or 0x0A, indicating an index
53922** b-tree).
53923*/
53924static int moveToRoot(BtCursor *pCur){
53925  MemPage *pRoot;
53926  int rc = SQLITE_OK;
53927  Btree *p = pCur->pBtree;
53928  BtShared *pBt = p->pBt;
53929
53930  assert( cursorHoldsMutex(pCur) );
53931  assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
53932  assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
53933  assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
53934  if( pCur->eState>=CURSOR_REQUIRESEEK ){
53935    if( pCur->eState==CURSOR_FAULT ){
53936      assert( pCur->skipNext!=SQLITE_OK );
53937      return pCur->skipNext;
53938    }
53939    sqlite3BtreeClearCursor(pCur);
53940  }
53941
53942  if( pCur->iPage>=0 ){
53943    int i;
53944    for(i=1; i<=pCur->iPage; i++){
53945      releasePage(pCur->apPage[i]);
53946    }
53947    pCur->iPage = 0;
53948  }else if( pCur->pgnoRoot==0 ){
53949    pCur->eState = CURSOR_INVALID;
53950    return SQLITE_OK;
53951  }else{
53952    rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0], pCur->wrFlag==0);
53953    if( rc!=SQLITE_OK ){
53954      pCur->eState = CURSOR_INVALID;
53955      return rc;
53956    }
53957    pCur->iPage = 0;
53958
53959    /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
53960    ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
53961    ** NULL, the caller expects a table b-tree. If this is not the case,
53962    ** return an SQLITE_CORRUPT error.  */
53963    assert( pCur->apPage[0]->intKey==1 || pCur->apPage[0]->intKey==0 );
53964    if( (pCur->pKeyInfo==0)!=pCur->apPage[0]->intKey ){
53965      return SQLITE_CORRUPT_BKPT;
53966    }
53967  }
53968
53969  /* Assert that the root page is of the correct type. This must be the
53970  ** case as the call to this function that loaded the root-page (either
53971  ** this call or a previous invocation) would have detected corruption
53972  ** if the assumption were not true, and it is not possible for the flags
53973  ** byte to have been modified while this cursor is holding a reference
53974  ** to the page.  */
53975  pRoot = pCur->apPage[0];
53976  assert( pRoot->pgno==pCur->pgnoRoot );
53977  assert( pRoot->isInit && (pCur->pKeyInfo==0)==pRoot->intKey );
53978
53979  pCur->aiIdx[0] = 0;
53980  pCur->info.nSize = 0;
53981  pCur->atLast = 0;
53982  pCur->validNKey = 0;
53983
53984  if( pRoot->nCell==0 && !pRoot->leaf ){
53985    Pgno subpage;
53986    if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
53987    subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
53988    pCur->eState = CURSOR_VALID;
53989    rc = moveToChild(pCur, subpage);
53990  }else{
53991    pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
53992  }
53993  return rc;
53994}
53995
53996/*
53997** Move the cursor down to the left-most leaf entry beneath the
53998** entry to which it is currently pointing.
53999**
54000** The left-most leaf is the one with the smallest key - the first
54001** in ascending order.
54002*/
54003static int moveToLeftmost(BtCursor *pCur){
54004  Pgno pgno;
54005  int rc = SQLITE_OK;
54006  MemPage *pPage;
54007
54008  assert( cursorHoldsMutex(pCur) );
54009  assert( pCur->eState==CURSOR_VALID );
54010  while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
54011    assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
54012    pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
54013    rc = moveToChild(pCur, pgno);
54014  }
54015  return rc;
54016}
54017
54018/*
54019** Move the cursor down to the right-most leaf entry beneath the
54020** page to which it is currently pointing.  Notice the difference
54021** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
54022** finds the left-most entry beneath the *entry* whereas moveToRightmost()
54023** finds the right-most entry beneath the *page*.
54024**
54025** The right-most entry is the one with the largest key - the last
54026** key in ascending order.
54027*/
54028static int moveToRightmost(BtCursor *pCur){
54029  Pgno pgno;
54030  int rc = SQLITE_OK;
54031  MemPage *pPage = 0;
54032
54033  assert( cursorHoldsMutex(pCur) );
54034  assert( pCur->eState==CURSOR_VALID );
54035  while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
54036    pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
54037    pCur->aiIdx[pCur->iPage] = pPage->nCell;
54038    rc = moveToChild(pCur, pgno);
54039  }
54040  if( rc==SQLITE_OK ){
54041    pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
54042    pCur->info.nSize = 0;
54043    pCur->validNKey = 0;
54044  }
54045  return rc;
54046}
54047
54048/* Move the cursor to the first entry in the table.  Return SQLITE_OK
54049** on success.  Set *pRes to 0 if the cursor actually points to something
54050** or set *pRes to 1 if the table is empty.
54051*/
54052SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
54053  int rc;
54054
54055  assert( cursorHoldsMutex(pCur) );
54056  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
54057  rc = moveToRoot(pCur);
54058  if( rc==SQLITE_OK ){
54059    if( pCur->eState==CURSOR_INVALID ){
54060      assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
54061      *pRes = 1;
54062    }else{
54063      assert( pCur->apPage[pCur->iPage]->nCell>0 );
54064      *pRes = 0;
54065      rc = moveToLeftmost(pCur);
54066    }
54067  }
54068  return rc;
54069}
54070
54071/* Move the cursor to the last entry in the table.  Return SQLITE_OK
54072** on success.  Set *pRes to 0 if the cursor actually points to something
54073** or set *pRes to 1 if the table is empty.
54074*/
54075SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
54076  int rc;
54077
54078  assert( cursorHoldsMutex(pCur) );
54079  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
54080
54081  /* If the cursor already points to the last entry, this is a no-op. */
54082  if( CURSOR_VALID==pCur->eState && pCur->atLast ){
54083#ifdef SQLITE_DEBUG
54084    /* This block serves to assert() that the cursor really does point
54085    ** to the last entry in the b-tree. */
54086    int ii;
54087    for(ii=0; ii<pCur->iPage; ii++){
54088      assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
54089    }
54090    assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
54091    assert( pCur->apPage[pCur->iPage]->leaf );
54092#endif
54093    return SQLITE_OK;
54094  }
54095
54096  rc = moveToRoot(pCur);
54097  if( rc==SQLITE_OK ){
54098    if( CURSOR_INVALID==pCur->eState ){
54099      assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
54100      *pRes = 1;
54101    }else{
54102      assert( pCur->eState==CURSOR_VALID );
54103      *pRes = 0;
54104      rc = moveToRightmost(pCur);
54105      pCur->atLast = rc==SQLITE_OK ?1:0;
54106    }
54107  }
54108  return rc;
54109}
54110
54111/* Move the cursor so that it points to an entry near the key
54112** specified by pIdxKey or intKey.   Return a success code.
54113**
54114** For INTKEY tables, the intKey parameter is used.  pIdxKey
54115** must be NULL.  For index tables, pIdxKey is used and intKey
54116** is ignored.
54117**
54118** If an exact match is not found, then the cursor is always
54119** left pointing at a leaf page which would hold the entry if it
54120** were present.  The cursor might point to an entry that comes
54121** before or after the key.
54122**
54123** An integer is written into *pRes which is the result of
54124** comparing the key with the entry to which the cursor is
54125** pointing.  The meaning of the integer written into
54126** *pRes is as follows:
54127**
54128**     *pRes<0      The cursor is left pointing at an entry that
54129**                  is smaller than intKey/pIdxKey or if the table is empty
54130**                  and the cursor is therefore left point to nothing.
54131**
54132**     *pRes==0     The cursor is left pointing at an entry that
54133**                  exactly matches intKey/pIdxKey.
54134**
54135**     *pRes>0      The cursor is left pointing at an entry that
54136**                  is larger than intKey/pIdxKey.
54137**
54138*/
54139SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
54140  BtCursor *pCur,          /* The cursor to be moved */
54141  UnpackedRecord *pIdxKey, /* Unpacked index key */
54142  i64 intKey,              /* The table key */
54143  int biasRight,           /* If true, bias the search to the high end */
54144  int *pRes                /* Write search results here */
54145){
54146  int rc;
54147
54148  assert( cursorHoldsMutex(pCur) );
54149  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
54150  assert( pRes );
54151  assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
54152
54153  /* If the cursor is already positioned at the point we are trying
54154  ** to move to, then just return without doing any work */
54155  if( pCur->eState==CURSOR_VALID && pCur->validNKey
54156   && pCur->apPage[0]->intKey
54157  ){
54158    if( pCur->info.nKey==intKey ){
54159      *pRes = 0;
54160      return SQLITE_OK;
54161    }
54162    if( pCur->atLast && pCur->info.nKey<intKey ){
54163      *pRes = -1;
54164      return SQLITE_OK;
54165    }
54166  }
54167
54168  rc = moveToRoot(pCur);
54169  if( rc ){
54170    return rc;
54171  }
54172  assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
54173  assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
54174  assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
54175  if( pCur->eState==CURSOR_INVALID ){
54176    *pRes = -1;
54177    assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
54178    return SQLITE_OK;
54179  }
54180  assert( pCur->apPage[0]->intKey || pIdxKey );
54181  for(;;){
54182    int lwr, upr, idx;
54183    Pgno chldPg;
54184    MemPage *pPage = pCur->apPage[pCur->iPage];
54185    int c;
54186
54187    /* pPage->nCell must be greater than zero. If this is the root-page
54188    ** the cursor would have been INVALID above and this for(;;) loop
54189    ** not run. If this is not the root-page, then the moveToChild() routine
54190    ** would have already detected db corruption. Similarly, pPage must
54191    ** be the right kind (index or table) of b-tree page. Otherwise
54192    ** a moveToChild() or moveToRoot() call would have detected corruption.  */
54193    assert( pPage->nCell>0 );
54194    assert( pPage->intKey==(pIdxKey==0) );
54195    lwr = 0;
54196    upr = pPage->nCell-1;
54197    if( biasRight ){
54198      pCur->aiIdx[pCur->iPage] = (u16)(idx = upr);
54199    }else{
54200      pCur->aiIdx[pCur->iPage] = (u16)(idx = (upr+lwr)/2);
54201    }
54202    for(;;){
54203      u8 *pCell;                          /* Pointer to current cell in pPage */
54204
54205      assert( idx==pCur->aiIdx[pCur->iPage] );
54206      pCur->info.nSize = 0;
54207      pCell = findCell(pPage, idx) + pPage->childPtrSize;
54208      if( pPage->intKey ){
54209        i64 nCellKey;
54210        if( pPage->hasData ){
54211          u32 dummy;
54212          pCell += getVarint32(pCell, dummy);
54213        }
54214        getVarint(pCell, (u64*)&nCellKey);
54215        if( nCellKey==intKey ){
54216          c = 0;
54217        }else if( nCellKey<intKey ){
54218          c = -1;
54219        }else{
54220          assert( nCellKey>intKey );
54221          c = +1;
54222        }
54223        pCur->validNKey = 1;
54224        pCur->info.nKey = nCellKey;
54225      }else{
54226        /* The maximum supported page-size is 65536 bytes. This means that
54227        ** the maximum number of record bytes stored on an index B-Tree
54228        ** page is less than 16384 bytes and may be stored as a 2-byte
54229        ** varint. This information is used to attempt to avoid parsing
54230        ** the entire cell by checking for the cases where the record is
54231        ** stored entirely within the b-tree page by inspecting the first
54232        ** 2 bytes of the cell.
54233        */
54234        int nCell = pCell[0];
54235        if( nCell<=pPage->max1bytePayload
54236         /* && (pCell+nCell)<pPage->aDataEnd */
54237        ){
54238          /* This branch runs if the record-size field of the cell is a
54239          ** single byte varint and the record fits entirely on the main
54240          ** b-tree page.  */
54241          testcase( pCell+nCell+1==pPage->aDataEnd );
54242          c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
54243        }else if( !(pCell[1] & 0x80)
54244          && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
54245          /* && (pCell+nCell+2)<=pPage->aDataEnd */
54246        ){
54247          /* The record-size field is a 2 byte varint and the record
54248          ** fits entirely on the main b-tree page.  */
54249          testcase( pCell+nCell+2==pPage->aDataEnd );
54250          c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
54251        }else{
54252          /* The record flows over onto one or more overflow pages. In
54253          ** this case the whole cell needs to be parsed, a buffer allocated
54254          ** and accessPayload() used to retrieve the record into the
54255          ** buffer before VdbeRecordCompare() can be called. */
54256          void *pCellKey;
54257          u8 * const pCellBody = pCell - pPage->childPtrSize;
54258          btreeParseCellPtr(pPage, pCellBody, &pCur->info);
54259          nCell = (int)pCur->info.nKey;
54260          pCellKey = sqlite3Malloc( nCell );
54261          if( pCellKey==0 ){
54262            rc = SQLITE_NOMEM;
54263            goto moveto_finish;
54264          }
54265          rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
54266          if( rc ){
54267            sqlite3_free(pCellKey);
54268            goto moveto_finish;
54269          }
54270          c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
54271          sqlite3_free(pCellKey);
54272        }
54273      }
54274      if( c==0 ){
54275        if( pPage->intKey && !pPage->leaf ){
54276          lwr = idx;
54277          break;
54278        }else{
54279          *pRes = 0;
54280          rc = SQLITE_OK;
54281          goto moveto_finish;
54282        }
54283      }
54284      if( c<0 ){
54285        lwr = idx+1;
54286      }else{
54287        upr = idx-1;
54288      }
54289      if( lwr>upr ){
54290        break;
54291      }
54292      pCur->aiIdx[pCur->iPage] = (u16)(idx = (lwr+upr)/2);
54293    }
54294    assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
54295    assert( pPage->isInit );
54296    if( pPage->leaf ){
54297      chldPg = 0;
54298    }else if( lwr>=pPage->nCell ){
54299      chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
54300    }else{
54301      chldPg = get4byte(findCell(pPage, lwr));
54302    }
54303    if( chldPg==0 ){
54304      assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
54305      *pRes = c;
54306      rc = SQLITE_OK;
54307      goto moveto_finish;
54308    }
54309    pCur->aiIdx[pCur->iPage] = (u16)lwr;
54310    pCur->info.nSize = 0;
54311    pCur->validNKey = 0;
54312    rc = moveToChild(pCur, chldPg);
54313    if( rc ) goto moveto_finish;
54314  }
54315moveto_finish:
54316  return rc;
54317}
54318
54319
54320/*
54321** Return TRUE if the cursor is not pointing at an entry of the table.
54322**
54323** TRUE will be returned after a call to sqlite3BtreeNext() moves
54324** past the last entry in the table or sqlite3BtreePrev() moves past
54325** the first entry.  TRUE is also returned if the table is empty.
54326*/
54327SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
54328  /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
54329  ** have been deleted? This API will need to change to return an error code
54330  ** as well as the boolean result value.
54331  */
54332  return (CURSOR_VALID!=pCur->eState);
54333}
54334
54335/*
54336** Advance the cursor to the next entry in the database.  If
54337** successful then set *pRes=0.  If the cursor
54338** was already pointing to the last entry in the database before
54339** this routine was called, then set *pRes=1.
54340*/
54341SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
54342  int rc;
54343  int idx;
54344  MemPage *pPage;
54345
54346  assert( cursorHoldsMutex(pCur) );
54347  rc = restoreCursorPosition(pCur);
54348  if( rc!=SQLITE_OK ){
54349    return rc;
54350  }
54351  assert( pRes!=0 );
54352  if( CURSOR_INVALID==pCur->eState ){
54353    *pRes = 1;
54354    return SQLITE_OK;
54355  }
54356  if( pCur->skipNext>0 ){
54357    pCur->skipNext = 0;
54358    *pRes = 0;
54359    return SQLITE_OK;
54360  }
54361  pCur->skipNext = 0;
54362
54363  pPage = pCur->apPage[pCur->iPage];
54364  idx = ++pCur->aiIdx[pCur->iPage];
54365  assert( pPage->isInit );
54366
54367  /* If the database file is corrupt, it is possible for the value of idx
54368  ** to be invalid here. This can only occur if a second cursor modifies
54369  ** the page while cursor pCur is holding a reference to it. Which can
54370  ** only happen if the database is corrupt in such a way as to link the
54371  ** page into more than one b-tree structure. */
54372  testcase( idx>pPage->nCell );
54373
54374  pCur->info.nSize = 0;
54375  pCur->validNKey = 0;
54376  if( idx>=pPage->nCell ){
54377    if( !pPage->leaf ){
54378      rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
54379      if( rc ) return rc;
54380      rc = moveToLeftmost(pCur);
54381      *pRes = 0;
54382      return rc;
54383    }
54384    do{
54385      if( pCur->iPage==0 ){
54386        *pRes = 1;
54387        pCur->eState = CURSOR_INVALID;
54388        return SQLITE_OK;
54389      }
54390      moveToParent(pCur);
54391      pPage = pCur->apPage[pCur->iPage];
54392    }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
54393    *pRes = 0;
54394    if( pPage->intKey ){
54395      rc = sqlite3BtreeNext(pCur, pRes);
54396    }else{
54397      rc = SQLITE_OK;
54398    }
54399    return rc;
54400  }
54401  *pRes = 0;
54402  if( pPage->leaf ){
54403    return SQLITE_OK;
54404  }
54405  rc = moveToLeftmost(pCur);
54406  return rc;
54407}
54408
54409
54410/*
54411** Step the cursor to the back to the previous entry in the database.  If
54412** successful then set *pRes=0.  If the cursor
54413** was already pointing to the first entry in the database before
54414** this routine was called, then set *pRes=1.
54415*/
54416SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
54417  int rc;
54418  MemPage *pPage;
54419
54420  assert( cursorHoldsMutex(pCur) );
54421  rc = restoreCursorPosition(pCur);
54422  if( rc!=SQLITE_OK ){
54423    return rc;
54424  }
54425  pCur->atLast = 0;
54426  if( CURSOR_INVALID==pCur->eState ){
54427    *pRes = 1;
54428    return SQLITE_OK;
54429  }
54430  if( pCur->skipNext<0 ){
54431    pCur->skipNext = 0;
54432    *pRes = 0;
54433    return SQLITE_OK;
54434  }
54435  pCur->skipNext = 0;
54436
54437  pPage = pCur->apPage[pCur->iPage];
54438  assert( pPage->isInit );
54439  if( !pPage->leaf ){
54440    int idx = pCur->aiIdx[pCur->iPage];
54441    rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
54442    if( rc ){
54443      return rc;
54444    }
54445    rc = moveToRightmost(pCur);
54446  }else{
54447    while( pCur->aiIdx[pCur->iPage]==0 ){
54448      if( pCur->iPage==0 ){
54449        pCur->eState = CURSOR_INVALID;
54450        *pRes = 1;
54451        return SQLITE_OK;
54452      }
54453      moveToParent(pCur);
54454    }
54455    pCur->info.nSize = 0;
54456    pCur->validNKey = 0;
54457
54458    pCur->aiIdx[pCur->iPage]--;
54459    pPage = pCur->apPage[pCur->iPage];
54460    if( pPage->intKey && !pPage->leaf ){
54461      rc = sqlite3BtreePrevious(pCur, pRes);
54462    }else{
54463      rc = SQLITE_OK;
54464    }
54465  }
54466  *pRes = 0;
54467  return rc;
54468}
54469
54470/*
54471** Allocate a new page from the database file.
54472**
54473** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
54474** has already been called on the new page.)  The new page has also
54475** been referenced and the calling routine is responsible for calling
54476** sqlite3PagerUnref() on the new page when it is done.
54477**
54478** SQLITE_OK is returned on success.  Any other return value indicates
54479** an error.  *ppPage and *pPgno are undefined in the event of an error.
54480** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
54481**
54482** If the "nearby" parameter is not 0, then an effort is made to
54483** locate a page close to the page number "nearby".  This can be used in an
54484** attempt to keep related pages close to each other in the database file,
54485** which in turn can make database access faster.
54486**
54487** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
54488** anywhere on the free-list, then it is guaranteed to be returned.  If
54489** eMode is BTALLOC_LT then the page returned will be less than or equal
54490** to nearby if any such page exists.  If eMode is BTALLOC_ANY then there
54491** are no restrictions on which page is returned.
54492*/
54493static int allocateBtreePage(
54494  BtShared *pBt,         /* The btree */
54495  MemPage **ppPage,      /* Store pointer to the allocated page here */
54496  Pgno *pPgno,           /* Store the page number here */
54497  Pgno nearby,           /* Search for a page near this one */
54498  u8 eMode               /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
54499){
54500  MemPage *pPage1;
54501  int rc;
54502  u32 n;     /* Number of pages on the freelist */
54503  u32 k;     /* Number of leaves on the trunk of the freelist */
54504  MemPage *pTrunk = 0;
54505  MemPage *pPrevTrunk = 0;
54506  Pgno mxPage;     /* Total size of the database file */
54507
54508  assert( sqlite3_mutex_held(pBt->mutex) );
54509  assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
54510  pPage1 = pBt->pPage1;
54511  mxPage = btreePagecount(pBt);
54512  n = get4byte(&pPage1->aData[36]);
54513  testcase( n==mxPage-1 );
54514  if( n>=mxPage ){
54515    return SQLITE_CORRUPT_BKPT;
54516  }
54517  if( n>0 ){
54518    /* There are pages on the freelist.  Reuse one of those pages. */
54519    Pgno iTrunk;
54520    u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
54521
54522    /* If eMode==BTALLOC_EXACT and a query of the pointer-map
54523    ** shows that the page 'nearby' is somewhere on the free-list, then
54524    ** the entire-list will be searched for that page.
54525    */
54526#ifndef SQLITE_OMIT_AUTOVACUUM
54527    if( eMode==BTALLOC_EXACT ){
54528      if( nearby<=mxPage ){
54529        u8 eType;
54530        assert( nearby>0 );
54531        assert( pBt->autoVacuum );
54532        rc = ptrmapGet(pBt, nearby, &eType, 0);
54533        if( rc ) return rc;
54534        if( eType==PTRMAP_FREEPAGE ){
54535          searchList = 1;
54536        }
54537      }
54538    }else if( eMode==BTALLOC_LE ){
54539      searchList = 1;
54540    }
54541#endif
54542
54543    /* Decrement the free-list count by 1. Set iTrunk to the index of the
54544    ** first free-list trunk page. iPrevTrunk is initially 1.
54545    */
54546    rc = sqlite3PagerWrite(pPage1->pDbPage);
54547    if( rc ) return rc;
54548    put4byte(&pPage1->aData[36], n-1);
54549
54550    /* The code within this loop is run only once if the 'searchList' variable
54551    ** is not true. Otherwise, it runs once for each trunk-page on the
54552    ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
54553    ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
54554    */
54555    do {
54556      pPrevTrunk = pTrunk;
54557      if( pPrevTrunk ){
54558        iTrunk = get4byte(&pPrevTrunk->aData[0]);
54559      }else{
54560        iTrunk = get4byte(&pPage1->aData[32]);
54561      }
54562      testcase( iTrunk==mxPage );
54563      if( iTrunk>mxPage ){
54564        rc = SQLITE_CORRUPT_BKPT;
54565      }else{
54566        rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0, 0);
54567      }
54568      if( rc ){
54569        pTrunk = 0;
54570        goto end_allocate_page;
54571      }
54572      assert( pTrunk!=0 );
54573      assert( pTrunk->aData!=0 );
54574
54575      k = get4byte(&pTrunk->aData[4]); /* # of leaves on this trunk page */
54576      if( k==0 && !searchList ){
54577        /* The trunk has no leaves and the list is not being searched.
54578        ** So extract the trunk page itself and use it as the newly
54579        ** allocated page */
54580        assert( pPrevTrunk==0 );
54581        rc = sqlite3PagerWrite(pTrunk->pDbPage);
54582        if( rc ){
54583          goto end_allocate_page;
54584        }
54585        *pPgno = iTrunk;
54586        memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
54587        *ppPage = pTrunk;
54588        pTrunk = 0;
54589        TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
54590      }else if( k>(u32)(pBt->usableSize/4 - 2) ){
54591        /* Value of k is out of range.  Database corruption */
54592        rc = SQLITE_CORRUPT_BKPT;
54593        goto end_allocate_page;
54594#ifndef SQLITE_OMIT_AUTOVACUUM
54595      }else if( searchList
54596            && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
54597      ){
54598        /* The list is being searched and this trunk page is the page
54599        ** to allocate, regardless of whether it has leaves.
54600        */
54601        *pPgno = iTrunk;
54602        *ppPage = pTrunk;
54603        searchList = 0;
54604        rc = sqlite3PagerWrite(pTrunk->pDbPage);
54605        if( rc ){
54606          goto end_allocate_page;
54607        }
54608        if( k==0 ){
54609          if( !pPrevTrunk ){
54610            memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
54611          }else{
54612            rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
54613            if( rc!=SQLITE_OK ){
54614              goto end_allocate_page;
54615            }
54616            memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
54617          }
54618        }else{
54619          /* The trunk page is required by the caller but it contains
54620          ** pointers to free-list leaves. The first leaf becomes a trunk
54621          ** page in this case.
54622          */
54623          MemPage *pNewTrunk;
54624          Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
54625          if( iNewTrunk>mxPage ){
54626            rc = SQLITE_CORRUPT_BKPT;
54627            goto end_allocate_page;
54628          }
54629          testcase( iNewTrunk==mxPage );
54630          rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0, 0);
54631          if( rc!=SQLITE_OK ){
54632            goto end_allocate_page;
54633          }
54634          rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
54635          if( rc!=SQLITE_OK ){
54636            releasePage(pNewTrunk);
54637            goto end_allocate_page;
54638          }
54639          memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
54640          put4byte(&pNewTrunk->aData[4], k-1);
54641          memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
54642          releasePage(pNewTrunk);
54643          if( !pPrevTrunk ){
54644            assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
54645            put4byte(&pPage1->aData[32], iNewTrunk);
54646          }else{
54647            rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
54648            if( rc ){
54649              goto end_allocate_page;
54650            }
54651            put4byte(&pPrevTrunk->aData[0], iNewTrunk);
54652          }
54653        }
54654        pTrunk = 0;
54655        TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
54656#endif
54657      }else if( k>0 ){
54658        /* Extract a leaf from the trunk */
54659        u32 closest;
54660        Pgno iPage;
54661        unsigned char *aData = pTrunk->aData;
54662        if( nearby>0 ){
54663          u32 i;
54664          closest = 0;
54665          if( eMode==BTALLOC_LE ){
54666            for(i=0; i<k; i++){
54667              iPage = get4byte(&aData[8+i*4]);
54668              if( iPage<=nearby ){
54669                closest = i;
54670                break;
54671              }
54672            }
54673          }else{
54674            int dist;
54675            dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
54676            for(i=1; i<k; i++){
54677              int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
54678              if( d2<dist ){
54679                closest = i;
54680                dist = d2;
54681              }
54682            }
54683          }
54684        }else{
54685          closest = 0;
54686        }
54687
54688        iPage = get4byte(&aData[8+closest*4]);
54689        testcase( iPage==mxPage );
54690        if( iPage>mxPage ){
54691          rc = SQLITE_CORRUPT_BKPT;
54692          goto end_allocate_page;
54693        }
54694        testcase( iPage==mxPage );
54695        if( !searchList
54696         || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
54697        ){
54698          int noContent;
54699          *pPgno = iPage;
54700          TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
54701                 ": %d more free pages\n",
54702                 *pPgno, closest+1, k, pTrunk->pgno, n-1));
54703          rc = sqlite3PagerWrite(pTrunk->pDbPage);
54704          if( rc ) goto end_allocate_page;
54705          if( closest<k-1 ){
54706            memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
54707          }
54708          put4byte(&aData[4], k-1);
54709          noContent = !btreeGetHasContent(pBt, *pPgno);
54710          rc = btreeGetPage(pBt, *pPgno, ppPage, noContent, 0);
54711          if( rc==SQLITE_OK ){
54712            rc = sqlite3PagerWrite((*ppPage)->pDbPage);
54713            if( rc!=SQLITE_OK ){
54714              releasePage(*ppPage);
54715            }
54716          }
54717          searchList = 0;
54718        }
54719      }
54720      releasePage(pPrevTrunk);
54721      pPrevTrunk = 0;
54722    }while( searchList );
54723  }else{
54724    /* There are no pages on the freelist, so append a new page to the
54725    ** database image.
54726    **
54727    ** Normally, new pages allocated by this block can be requested from the
54728    ** pager layer with the 'no-content' flag set. This prevents the pager
54729    ** from trying to read the pages content from disk. However, if the
54730    ** current transaction has already run one or more incremental-vacuum
54731    ** steps, then the page we are about to allocate may contain content
54732    ** that is required in the event of a rollback. In this case, do
54733    ** not set the no-content flag. This causes the pager to load and journal
54734    ** the current page content before overwriting it.
54735    **
54736    ** Note that the pager will not actually attempt to load or journal
54737    ** content for any page that really does lie past the end of the database
54738    ** file on disk. So the effects of disabling the no-content optimization
54739    ** here are confined to those pages that lie between the end of the
54740    ** database image and the end of the database file.
54741    */
54742    int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate));
54743
54744    rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
54745    if( rc ) return rc;
54746    pBt->nPage++;
54747    if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
54748
54749#ifndef SQLITE_OMIT_AUTOVACUUM
54750    if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
54751      /* If *pPgno refers to a pointer-map page, allocate two new pages
54752      ** at the end of the file instead of one. The first allocated page
54753      ** becomes a new pointer-map page, the second is used by the caller.
54754      */
54755      MemPage *pPg = 0;
54756      TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
54757      assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
54758      rc = btreeGetPage(pBt, pBt->nPage, &pPg, bNoContent, 0);
54759      if( rc==SQLITE_OK ){
54760        rc = sqlite3PagerWrite(pPg->pDbPage);
54761        releasePage(pPg);
54762      }
54763      if( rc ) return rc;
54764      pBt->nPage++;
54765      if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
54766    }
54767#endif
54768    put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
54769    *pPgno = pBt->nPage;
54770
54771    assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
54772    rc = btreeGetPage(pBt, *pPgno, ppPage, bNoContent, 0);
54773    if( rc ) return rc;
54774    rc = sqlite3PagerWrite((*ppPage)->pDbPage);
54775    if( rc!=SQLITE_OK ){
54776      releasePage(*ppPage);
54777    }
54778    TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
54779  }
54780
54781  assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
54782
54783end_allocate_page:
54784  releasePage(pTrunk);
54785  releasePage(pPrevTrunk);
54786  if( rc==SQLITE_OK ){
54787    if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
54788      releasePage(*ppPage);
54789      return SQLITE_CORRUPT_BKPT;
54790    }
54791    (*ppPage)->isInit = 0;
54792  }else{
54793    *ppPage = 0;
54794  }
54795  assert( rc!=SQLITE_OK || sqlite3PagerIswriteable((*ppPage)->pDbPage) );
54796  return rc;
54797}
54798
54799/*
54800** This function is used to add page iPage to the database file free-list.
54801** It is assumed that the page is not already a part of the free-list.
54802**
54803** The value passed as the second argument to this function is optional.
54804** If the caller happens to have a pointer to the MemPage object
54805** corresponding to page iPage handy, it may pass it as the second value.
54806** Otherwise, it may pass NULL.
54807**
54808** If a pointer to a MemPage object is passed as the second argument,
54809** its reference count is not altered by this function.
54810*/
54811static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
54812  MemPage *pTrunk = 0;                /* Free-list trunk page */
54813  Pgno iTrunk = 0;                    /* Page number of free-list trunk page */
54814  MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
54815  MemPage *pPage;                     /* Page being freed. May be NULL. */
54816  int rc;                             /* Return Code */
54817  int nFree;                          /* Initial number of pages on free-list */
54818
54819  assert( sqlite3_mutex_held(pBt->mutex) );
54820  assert( iPage>1 );
54821  assert( !pMemPage || pMemPage->pgno==iPage );
54822
54823  if( pMemPage ){
54824    pPage = pMemPage;
54825    sqlite3PagerRef(pPage->pDbPage);
54826  }else{
54827    pPage = btreePageLookup(pBt, iPage);
54828  }
54829
54830  /* Increment the free page count on pPage1 */
54831  rc = sqlite3PagerWrite(pPage1->pDbPage);
54832  if( rc ) goto freepage_out;
54833  nFree = get4byte(&pPage1->aData[36]);
54834  put4byte(&pPage1->aData[36], nFree+1);
54835
54836  if( pBt->btsFlags & BTS_SECURE_DELETE ){
54837    /* If the secure_delete option is enabled, then
54838    ** always fully overwrite deleted information with zeros.
54839    */
54840    if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0, 0))!=0) )
54841     ||            ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
54842    ){
54843      goto freepage_out;
54844    }
54845    memset(pPage->aData, 0, pPage->pBt->pageSize);
54846  }
54847
54848  /* If the database supports auto-vacuum, write an entry in the pointer-map
54849  ** to indicate that the page is free.
54850  */
54851  if( ISAUTOVACUUM ){
54852    ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
54853    if( rc ) goto freepage_out;
54854  }
54855
54856  /* Now manipulate the actual database free-list structure. There are two
54857  ** possibilities. If the free-list is currently empty, or if the first
54858  ** trunk page in the free-list is full, then this page will become a
54859  ** new free-list trunk page. Otherwise, it will become a leaf of the
54860  ** first trunk page in the current free-list. This block tests if it
54861  ** is possible to add the page as a new free-list leaf.
54862  */
54863  if( nFree!=0 ){
54864    u32 nLeaf;                /* Initial number of leaf cells on trunk page */
54865
54866    iTrunk = get4byte(&pPage1->aData[32]);
54867    rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0, 0);
54868    if( rc!=SQLITE_OK ){
54869      goto freepage_out;
54870    }
54871
54872    nLeaf = get4byte(&pTrunk->aData[4]);
54873    assert( pBt->usableSize>32 );
54874    if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
54875      rc = SQLITE_CORRUPT_BKPT;
54876      goto freepage_out;
54877    }
54878    if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
54879      /* In this case there is room on the trunk page to insert the page
54880      ** being freed as a new leaf.
54881      **
54882      ** Note that the trunk page is not really full until it contains
54883      ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
54884      ** coded.  But due to a coding error in versions of SQLite prior to
54885      ** 3.6.0, databases with freelist trunk pages holding more than
54886      ** usableSize/4 - 8 entries will be reported as corrupt.  In order
54887      ** to maintain backwards compatibility with older versions of SQLite,
54888      ** we will continue to restrict the number of entries to usableSize/4 - 8
54889      ** for now.  At some point in the future (once everyone has upgraded
54890      ** to 3.6.0 or later) we should consider fixing the conditional above
54891      ** to read "usableSize/4-2" instead of "usableSize/4-8".
54892      */
54893      rc = sqlite3PagerWrite(pTrunk->pDbPage);
54894      if( rc==SQLITE_OK ){
54895        put4byte(&pTrunk->aData[4], nLeaf+1);
54896        put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
54897        if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
54898          sqlite3PagerDontWrite(pPage->pDbPage);
54899        }
54900        rc = btreeSetHasContent(pBt, iPage);
54901      }
54902      TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
54903      goto freepage_out;
54904    }
54905  }
54906
54907  /* If control flows to this point, then it was not possible to add the
54908  ** the page being freed as a leaf page of the first trunk in the free-list.
54909  ** Possibly because the free-list is empty, or possibly because the
54910  ** first trunk in the free-list is full. Either way, the page being freed
54911  ** will become the new first trunk page in the free-list.
54912  */
54913  if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0, 0)) ){
54914    goto freepage_out;
54915  }
54916  rc = sqlite3PagerWrite(pPage->pDbPage);
54917  if( rc!=SQLITE_OK ){
54918    goto freepage_out;
54919  }
54920  put4byte(pPage->aData, iTrunk);
54921  put4byte(&pPage->aData[4], 0);
54922  put4byte(&pPage1->aData[32], iPage);
54923  TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
54924
54925freepage_out:
54926  if( pPage ){
54927    pPage->isInit = 0;
54928  }
54929  releasePage(pPage);
54930  releasePage(pTrunk);
54931  return rc;
54932}
54933static void freePage(MemPage *pPage, int *pRC){
54934  if( (*pRC)==SQLITE_OK ){
54935    *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
54936  }
54937}
54938
54939/*
54940** Free any overflow pages associated with the given Cell.
54941*/
54942static int clearCell(MemPage *pPage, unsigned char *pCell){
54943  BtShared *pBt = pPage->pBt;
54944  CellInfo info;
54945  Pgno ovflPgno;
54946  int rc;
54947  int nOvfl;
54948  u32 ovflPageSize;
54949
54950  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
54951  btreeParseCellPtr(pPage, pCell, &info);
54952  if( info.iOverflow==0 ){
54953    return SQLITE_OK;  /* No overflow pages. Return without doing anything */
54954  }
54955  if( pCell+info.iOverflow+3 > pPage->aData+pPage->maskPage ){
54956    return SQLITE_CORRUPT_BKPT;  /* Cell extends past end of page */
54957  }
54958  ovflPgno = get4byte(&pCell[info.iOverflow]);
54959  assert( pBt->usableSize > 4 );
54960  ovflPageSize = pBt->usableSize - 4;
54961  nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
54962  assert( ovflPgno==0 || nOvfl>0 );
54963  while( nOvfl-- ){
54964    Pgno iNext = 0;
54965    MemPage *pOvfl = 0;
54966    if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
54967      /* 0 is not a legal page number and page 1 cannot be an
54968      ** overflow page. Therefore if ovflPgno<2 or past the end of the
54969      ** file the database must be corrupt. */
54970      return SQLITE_CORRUPT_BKPT;
54971    }
54972    if( nOvfl ){
54973      rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
54974      if( rc ) return rc;
54975    }
54976
54977    if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
54978     && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
54979    ){
54980      /* There is no reason any cursor should have an outstanding reference
54981      ** to an overflow page belonging to a cell that is being deleted/updated.
54982      ** So if there exists more than one reference to this page, then it
54983      ** must not really be an overflow page and the database must be corrupt.
54984      ** It is helpful to detect this before calling freePage2(), as
54985      ** freePage2() may zero the page contents if secure-delete mode is
54986      ** enabled. If this 'overflow' page happens to be a page that the
54987      ** caller is iterating through or using in some other way, this
54988      ** can be problematic.
54989      */
54990      rc = SQLITE_CORRUPT_BKPT;
54991    }else{
54992      rc = freePage2(pBt, pOvfl, ovflPgno);
54993    }
54994
54995    if( pOvfl ){
54996      sqlite3PagerUnref(pOvfl->pDbPage);
54997    }
54998    if( rc ) return rc;
54999    ovflPgno = iNext;
55000  }
55001  return SQLITE_OK;
55002}
55003
55004/*
55005** Create the byte sequence used to represent a cell on page pPage
55006** and write that byte sequence into pCell[].  Overflow pages are
55007** allocated and filled in as necessary.  The calling procedure
55008** is responsible for making sure sufficient space has been allocated
55009** for pCell[].
55010**
55011** Note that pCell does not necessary need to point to the pPage->aData
55012** area.  pCell might point to some temporary storage.  The cell will
55013** be constructed in this temporary area then copied into pPage->aData
55014** later.
55015*/
55016static int fillInCell(
55017  MemPage *pPage,                /* The page that contains the cell */
55018  unsigned char *pCell,          /* Complete text of the cell */
55019  const void *pKey, i64 nKey,    /* The key */
55020  const void *pData,int nData,   /* The data */
55021  int nZero,                     /* Extra zero bytes to append to pData */
55022  int *pnSize                    /* Write cell size here */
55023){
55024  int nPayload;
55025  const u8 *pSrc;
55026  int nSrc, n, rc;
55027  int spaceLeft;
55028  MemPage *pOvfl = 0;
55029  MemPage *pToRelease = 0;
55030  unsigned char *pPrior;
55031  unsigned char *pPayload;
55032  BtShared *pBt = pPage->pBt;
55033  Pgno pgnoOvfl = 0;
55034  int nHeader;
55035  CellInfo info;
55036
55037  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
55038
55039  /* pPage is not necessarily writeable since pCell might be auxiliary
55040  ** buffer space that is separate from the pPage buffer area */
55041  assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
55042            || sqlite3PagerIswriteable(pPage->pDbPage) );
55043
55044  /* Fill in the header. */
55045  nHeader = 0;
55046  if( !pPage->leaf ){
55047    nHeader += 4;
55048  }
55049  if( pPage->hasData ){
55050    nHeader += putVarint(&pCell[nHeader], nData+nZero);
55051  }else{
55052    nData = nZero = 0;
55053  }
55054  nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
55055  btreeParseCellPtr(pPage, pCell, &info);
55056  assert( info.nHeader==nHeader );
55057  assert( info.nKey==nKey );
55058  assert( info.nData==(u32)(nData+nZero) );
55059
55060  /* Fill in the payload */
55061  nPayload = nData + nZero;
55062  if( pPage->intKey ){
55063    pSrc = pData;
55064    nSrc = nData;
55065    nData = 0;
55066  }else{
55067    if( NEVER(nKey>0x7fffffff || pKey==0) ){
55068      return SQLITE_CORRUPT_BKPT;
55069    }
55070    nPayload += (int)nKey;
55071    pSrc = pKey;
55072    nSrc = (int)nKey;
55073  }
55074  *pnSize = info.nSize;
55075  spaceLeft = info.nLocal;
55076  pPayload = &pCell[nHeader];
55077  pPrior = &pCell[info.iOverflow];
55078
55079  while( nPayload>0 ){
55080    if( spaceLeft==0 ){
55081#ifndef SQLITE_OMIT_AUTOVACUUM
55082      Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
55083      if( pBt->autoVacuum ){
55084        do{
55085          pgnoOvfl++;
55086        } while(
55087          PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
55088        );
55089      }
55090#endif
55091      rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
55092#ifndef SQLITE_OMIT_AUTOVACUUM
55093      /* If the database supports auto-vacuum, and the second or subsequent
55094      ** overflow page is being allocated, add an entry to the pointer-map
55095      ** for that page now.
55096      **
55097      ** If this is the first overflow page, then write a partial entry
55098      ** to the pointer-map. If we write nothing to this pointer-map slot,
55099      ** then the optimistic overflow chain processing in clearCell()
55100      ** may misinterpret the uninitialized values and delete the
55101      ** wrong pages from the database.
55102      */
55103      if( pBt->autoVacuum && rc==SQLITE_OK ){
55104        u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
55105        ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
55106        if( rc ){
55107          releasePage(pOvfl);
55108        }
55109      }
55110#endif
55111      if( rc ){
55112        releasePage(pToRelease);
55113        return rc;
55114      }
55115
55116      /* If pToRelease is not zero than pPrior points into the data area
55117      ** of pToRelease.  Make sure pToRelease is still writeable. */
55118      assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
55119
55120      /* If pPrior is part of the data area of pPage, then make sure pPage
55121      ** is still writeable */
55122      assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
55123            || sqlite3PagerIswriteable(pPage->pDbPage) );
55124
55125      put4byte(pPrior, pgnoOvfl);
55126      releasePage(pToRelease);
55127      pToRelease = pOvfl;
55128      pPrior = pOvfl->aData;
55129      put4byte(pPrior, 0);
55130      pPayload = &pOvfl->aData[4];
55131      spaceLeft = pBt->usableSize - 4;
55132    }
55133    n = nPayload;
55134    if( n>spaceLeft ) n = spaceLeft;
55135
55136    /* If pToRelease is not zero than pPayload points into the data area
55137    ** of pToRelease.  Make sure pToRelease is still writeable. */
55138    assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
55139
55140    /* If pPayload is part of the data area of pPage, then make sure pPage
55141    ** is still writeable */
55142    assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
55143            || sqlite3PagerIswriteable(pPage->pDbPage) );
55144
55145    if( nSrc>0 ){
55146      if( n>nSrc ) n = nSrc;
55147      assert( pSrc );
55148      memcpy(pPayload, pSrc, n);
55149    }else{
55150      memset(pPayload, 0, n);
55151    }
55152    nPayload -= n;
55153    pPayload += n;
55154    pSrc += n;
55155    nSrc -= n;
55156    spaceLeft -= n;
55157    if( nSrc==0 ){
55158      nSrc = nData;
55159      pSrc = pData;
55160    }
55161  }
55162  releasePage(pToRelease);
55163  return SQLITE_OK;
55164}
55165
55166/*
55167** Remove the i-th cell from pPage.  This routine effects pPage only.
55168** The cell content is not freed or deallocated.  It is assumed that
55169** the cell content has been copied someplace else.  This routine just
55170** removes the reference to the cell from pPage.
55171**
55172** "sz" must be the number of bytes in the cell.
55173*/
55174static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
55175  u32 pc;         /* Offset to cell content of cell being deleted */
55176  u8 *data;       /* pPage->aData */
55177  u8 *ptr;        /* Used to move bytes around within data[] */
55178  u8 *endPtr;     /* End of loop */
55179  int rc;         /* The return code */
55180  int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
55181
55182  if( *pRC ) return;
55183
55184  assert( idx>=0 && idx<pPage->nCell );
55185  assert( sz==cellSize(pPage, idx) );
55186  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
55187  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
55188  data = pPage->aData;
55189  ptr = &pPage->aCellIdx[2*idx];
55190  pc = get2byte(ptr);
55191  hdr = pPage->hdrOffset;
55192  testcase( pc==get2byte(&data[hdr+5]) );
55193  testcase( pc+sz==pPage->pBt->usableSize );
55194  if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
55195    *pRC = SQLITE_CORRUPT_BKPT;
55196    return;
55197  }
55198  rc = freeSpace(pPage, pc, sz);
55199  if( rc ){
55200    *pRC = rc;
55201    return;
55202  }
55203  endPtr = &pPage->aCellIdx[2*pPage->nCell - 2];
55204  assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 );  /* ptr is always 2-byte aligned */
55205  while( ptr<endPtr ){
55206    *(u16*)ptr = *(u16*)&ptr[2];
55207    ptr += 2;
55208  }
55209  pPage->nCell--;
55210  put2byte(&data[hdr+3], pPage->nCell);
55211  pPage->nFree += 2;
55212}
55213
55214/*
55215** Insert a new cell on pPage at cell index "i".  pCell points to the
55216** content of the cell.
55217**
55218** If the cell content will fit on the page, then put it there.  If it
55219** will not fit, then make a copy of the cell content into pTemp if
55220** pTemp is not null.  Regardless of pTemp, allocate a new entry
55221** in pPage->apOvfl[] and make it point to the cell content (either
55222** in pTemp or the original pCell) and also record its index.
55223** Allocating a new entry in pPage->aCell[] implies that
55224** pPage->nOverflow is incremented.
55225**
55226** If nSkip is non-zero, then do not copy the first nSkip bytes of the
55227** cell. The caller will overwrite them after this function returns. If
55228** nSkip is non-zero, then pCell may not point to an invalid memory location
55229** (but pCell+nSkip is always valid).
55230*/
55231static void insertCell(
55232  MemPage *pPage,   /* Page into which we are copying */
55233  int i,            /* New cell becomes the i-th cell of the page */
55234  u8 *pCell,        /* Content of the new cell */
55235  int sz,           /* Bytes of content in pCell */
55236  u8 *pTemp,        /* Temp storage space for pCell, if needed */
55237  Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
55238  int *pRC          /* Read and write return code from here */
55239){
55240  int idx = 0;      /* Where to write new cell content in data[] */
55241  int j;            /* Loop counter */
55242  int end;          /* First byte past the last cell pointer in data[] */
55243  int ins;          /* Index in data[] where new cell pointer is inserted */
55244  int cellOffset;   /* Address of first cell pointer in data[] */
55245  u8 *data;         /* The content of the whole page */
55246  u8 *ptr;          /* Used for moving information around in data[] */
55247  u8 *endPtr;       /* End of the loop */
55248
55249  int nSkip = (iChild ? 4 : 0);
55250
55251  if( *pRC ) return;
55252
55253  assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
55254  assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=10921 );
55255  assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
55256  assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
55257  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
55258  /* The cell should normally be sized correctly.  However, when moving a
55259  ** malformed cell from a leaf page to an interior page, if the cell size
55260  ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
55261  ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence
55262  ** the term after the || in the following assert(). */
55263  assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
55264  if( pPage->nOverflow || sz+2>pPage->nFree ){
55265    if( pTemp ){
55266      memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
55267      pCell = pTemp;
55268    }
55269    if( iChild ){
55270      put4byte(pCell, iChild);
55271    }
55272    j = pPage->nOverflow++;
55273    assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) );
55274    pPage->apOvfl[j] = pCell;
55275    pPage->aiOvfl[j] = (u16)i;
55276  }else{
55277    int rc = sqlite3PagerWrite(pPage->pDbPage);
55278    if( rc!=SQLITE_OK ){
55279      *pRC = rc;
55280      return;
55281    }
55282    assert( sqlite3PagerIswriteable(pPage->pDbPage) );
55283    data = pPage->aData;
55284    cellOffset = pPage->cellOffset;
55285    end = cellOffset + 2*pPage->nCell;
55286    ins = cellOffset + 2*i;
55287    rc = allocateSpace(pPage, sz, &idx);
55288    if( rc ){ *pRC = rc; return; }
55289    /* The allocateSpace() routine guarantees the following two properties
55290    ** if it returns success */
55291    assert( idx >= end+2 );
55292    assert( idx+sz <= (int)pPage->pBt->usableSize );
55293    pPage->nCell++;
55294    pPage->nFree -= (u16)(2 + sz);
55295    memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
55296    if( iChild ){
55297      put4byte(&data[idx], iChild);
55298    }
55299    ptr = &data[end];
55300    endPtr = &data[ins];
55301    assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 );  /* ptr is always 2-byte aligned */
55302    while( ptr>endPtr ){
55303      *(u16*)ptr = *(u16*)&ptr[-2];
55304      ptr -= 2;
55305    }
55306    put2byte(&data[ins], idx);
55307    put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
55308#ifndef SQLITE_OMIT_AUTOVACUUM
55309    if( pPage->pBt->autoVacuum ){
55310      /* The cell may contain a pointer to an overflow page. If so, write
55311      ** the entry for the overflow page into the pointer map.
55312      */
55313      ptrmapPutOvflPtr(pPage, pCell, pRC);
55314    }
55315#endif
55316  }
55317}
55318
55319/*
55320** Add a list of cells to a page.  The page should be initially empty.
55321** The cells are guaranteed to fit on the page.
55322*/
55323static void assemblePage(
55324  MemPage *pPage,   /* The page to be assemblied */
55325  int nCell,        /* The number of cells to add to this page */
55326  u8 **apCell,      /* Pointers to cell bodies */
55327  u16 *aSize        /* Sizes of the cells */
55328){
55329  int i;            /* Loop counter */
55330  u8 *pCellptr;     /* Address of next cell pointer */
55331  int cellbody;     /* Address of next cell body */
55332  u8 * const data = pPage->aData;             /* Pointer to data for pPage */
55333  const int hdr = pPage->hdrOffset;           /* Offset of header on pPage */
55334  const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
55335
55336  assert( pPage->nOverflow==0 );
55337  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
55338  assert( nCell>=0 && nCell<=(int)MX_CELL(pPage->pBt)
55339            && (int)MX_CELL(pPage->pBt)<=10921);
55340  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
55341
55342  /* Check that the page has just been zeroed by zeroPage() */
55343  assert( pPage->nCell==0 );
55344  assert( get2byteNotZero(&data[hdr+5])==nUsable );
55345
55346  pCellptr = &pPage->aCellIdx[nCell*2];
55347  cellbody = nUsable;
55348  for(i=nCell-1; i>=0; i--){
55349    u16 sz = aSize[i];
55350    pCellptr -= 2;
55351    cellbody -= sz;
55352    put2byte(pCellptr, cellbody);
55353    memcpy(&data[cellbody], apCell[i], sz);
55354  }
55355  put2byte(&data[hdr+3], nCell);
55356  put2byte(&data[hdr+5], cellbody);
55357  pPage->nFree -= (nCell*2 + nUsable - cellbody);
55358  pPage->nCell = (u16)nCell;
55359}
55360
55361/*
55362** The following parameters determine how many adjacent pages get involved
55363** in a balancing operation.  NN is the number of neighbors on either side
55364** of the page that participate in the balancing operation.  NB is the
55365** total number of pages that participate, including the target page and
55366** NN neighbors on either side.
55367**
55368** The minimum value of NN is 1 (of course).  Increasing NN above 1
55369** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
55370** in exchange for a larger degradation in INSERT and UPDATE performance.
55371** The value of NN appears to give the best results overall.
55372*/
55373#define NN 1             /* Number of neighbors on either side of pPage */
55374#define NB (NN*2+1)      /* Total pages involved in the balance */
55375
55376
55377#ifndef SQLITE_OMIT_QUICKBALANCE
55378/*
55379** This version of balance() handles the common special case where
55380** a new entry is being inserted on the extreme right-end of the
55381** tree, in other words, when the new entry will become the largest
55382** entry in the tree.
55383**
55384** Instead of trying to balance the 3 right-most leaf pages, just add
55385** a new page to the right-hand side and put the one new entry in
55386** that page.  This leaves the right side of the tree somewhat
55387** unbalanced.  But odds are that we will be inserting new entries
55388** at the end soon afterwards so the nearly empty page will quickly
55389** fill up.  On average.
55390**
55391** pPage is the leaf page which is the right-most page in the tree.
55392** pParent is its parent.  pPage must have a single overflow entry
55393** which is also the right-most entry on the page.
55394**
55395** The pSpace buffer is used to store a temporary copy of the divider
55396** cell that will be inserted into pParent. Such a cell consists of a 4
55397** byte page number followed by a variable length integer. In other
55398** words, at most 13 bytes. Hence the pSpace buffer must be at
55399** least 13 bytes in size.
55400*/
55401static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
55402  BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
55403  MemPage *pNew;                       /* Newly allocated page */
55404  int rc;                              /* Return Code */
55405  Pgno pgnoNew;                        /* Page number of pNew */
55406
55407  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
55408  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
55409  assert( pPage->nOverflow==1 );
55410
55411  /* This error condition is now caught prior to reaching this function */
55412  if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT;
55413
55414  /* Allocate a new page. This page will become the right-sibling of
55415  ** pPage. Make the parent page writable, so that the new divider cell
55416  ** may be inserted. If both these operations are successful, proceed.
55417  */
55418  rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
55419
55420  if( rc==SQLITE_OK ){
55421
55422    u8 *pOut = &pSpace[4];
55423    u8 *pCell = pPage->apOvfl[0];
55424    u16 szCell = cellSizePtr(pPage, pCell);
55425    u8 *pStop;
55426
55427    assert( sqlite3PagerIswriteable(pNew->pDbPage) );
55428    assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
55429    zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
55430    assemblePage(pNew, 1, &pCell, &szCell);
55431
55432    /* If this is an auto-vacuum database, update the pointer map
55433    ** with entries for the new page, and any pointer from the
55434    ** cell on the page to an overflow page. If either of these
55435    ** operations fails, the return code is set, but the contents
55436    ** of the parent page are still manipulated by thh code below.
55437    ** That is Ok, at this point the parent page is guaranteed to
55438    ** be marked as dirty. Returning an error code will cause a
55439    ** rollback, undoing any changes made to the parent page.
55440    */
55441    if( ISAUTOVACUUM ){
55442      ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
55443      if( szCell>pNew->minLocal ){
55444        ptrmapPutOvflPtr(pNew, pCell, &rc);
55445      }
55446    }
55447
55448    /* Create a divider cell to insert into pParent. The divider cell
55449    ** consists of a 4-byte page number (the page number of pPage) and
55450    ** a variable length key value (which must be the same value as the
55451    ** largest key on pPage).
55452    **
55453    ** To find the largest key value on pPage, first find the right-most
55454    ** cell on pPage. The first two fields of this cell are the
55455    ** record-length (a variable length integer at most 32-bits in size)
55456    ** and the key value (a variable length integer, may have any value).
55457    ** The first of the while(...) loops below skips over the record-length
55458    ** field. The second while(...) loop copies the key value from the
55459    ** cell on pPage into the pSpace buffer.
55460    */
55461    pCell = findCell(pPage, pPage->nCell-1);
55462    pStop = &pCell[9];
55463    while( (*(pCell++)&0x80) && pCell<pStop );
55464    pStop = &pCell[9];
55465    while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
55466
55467    /* Insert the new divider cell into pParent. */
55468    insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
55469               0, pPage->pgno, &rc);
55470
55471    /* Set the right-child pointer of pParent to point to the new page. */
55472    put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
55473
55474    /* Release the reference to the new page. */
55475    releasePage(pNew);
55476  }
55477
55478  return rc;
55479}
55480#endif /* SQLITE_OMIT_QUICKBALANCE */
55481
55482#if 0
55483/*
55484** This function does not contribute anything to the operation of SQLite.
55485** it is sometimes activated temporarily while debugging code responsible
55486** for setting pointer-map entries.
55487*/
55488static int ptrmapCheckPages(MemPage **apPage, int nPage){
55489  int i, j;
55490  for(i=0; i<nPage; i++){
55491    Pgno n;
55492    u8 e;
55493    MemPage *pPage = apPage[i];
55494    BtShared *pBt = pPage->pBt;
55495    assert( pPage->isInit );
55496
55497    for(j=0; j<pPage->nCell; j++){
55498      CellInfo info;
55499      u8 *z;
55500
55501      z = findCell(pPage, j);
55502      btreeParseCellPtr(pPage, z, &info);
55503      if( info.iOverflow ){
55504        Pgno ovfl = get4byte(&z[info.iOverflow]);
55505        ptrmapGet(pBt, ovfl, &e, &n);
55506        assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
55507      }
55508      if( !pPage->leaf ){
55509        Pgno child = get4byte(z);
55510        ptrmapGet(pBt, child, &e, &n);
55511        assert( n==pPage->pgno && e==PTRMAP_BTREE );
55512      }
55513    }
55514    if( !pPage->leaf ){
55515      Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
55516      ptrmapGet(pBt, child, &e, &n);
55517      assert( n==pPage->pgno && e==PTRMAP_BTREE );
55518    }
55519  }
55520  return 1;
55521}
55522#endif
55523
55524/*
55525** This function is used to copy the contents of the b-tree node stored
55526** on page pFrom to page pTo. If page pFrom was not a leaf page, then
55527** the pointer-map entries for each child page are updated so that the
55528** parent page stored in the pointer map is page pTo. If pFrom contained
55529** any cells with overflow page pointers, then the corresponding pointer
55530** map entries are also updated so that the parent page is page pTo.
55531**
55532** If pFrom is currently carrying any overflow cells (entries in the
55533** MemPage.apOvfl[] array), they are not copied to pTo.
55534**
55535** Before returning, page pTo is reinitialized using btreeInitPage().
55536**
55537** The performance of this function is not critical. It is only used by
55538** the balance_shallower() and balance_deeper() procedures, neither of
55539** which are called often under normal circumstances.
55540*/
55541static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
55542  if( (*pRC)==SQLITE_OK ){
55543    BtShared * const pBt = pFrom->pBt;
55544    u8 * const aFrom = pFrom->aData;
55545    u8 * const aTo = pTo->aData;
55546    int const iFromHdr = pFrom->hdrOffset;
55547    int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
55548    int rc;
55549    int iData;
55550
55551
55552    assert( pFrom->isInit );
55553    assert( pFrom->nFree>=iToHdr );
55554    assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
55555
55556    /* Copy the b-tree node content from page pFrom to page pTo. */
55557    iData = get2byte(&aFrom[iFromHdr+5]);
55558    memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
55559    memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
55560
55561    /* Reinitialize page pTo so that the contents of the MemPage structure
55562    ** match the new data. The initialization of pTo can actually fail under
55563    ** fairly obscure circumstances, even though it is a copy of initialized
55564    ** page pFrom.
55565    */
55566    pTo->isInit = 0;
55567    rc = btreeInitPage(pTo);
55568    if( rc!=SQLITE_OK ){
55569      *pRC = rc;
55570      return;
55571    }
55572
55573    /* If this is an auto-vacuum database, update the pointer-map entries
55574    ** for any b-tree or overflow pages that pTo now contains the pointers to.
55575    */
55576    if( ISAUTOVACUUM ){
55577      *pRC = setChildPtrmaps(pTo);
55578    }
55579  }
55580}
55581
55582/*
55583** This routine redistributes cells on the iParentIdx'th child of pParent
55584** (hereafter "the page") and up to 2 siblings so that all pages have about the
55585** same amount of free space. Usually a single sibling on either side of the
55586** page are used in the balancing, though both siblings might come from one
55587** side if the page is the first or last child of its parent. If the page
55588** has fewer than 2 siblings (something which can only happen if the page
55589** is a root page or a child of a root page) then all available siblings
55590** participate in the balancing.
55591**
55592** The number of siblings of the page might be increased or decreased by
55593** one or two in an effort to keep pages nearly full but not over full.
55594**
55595** Note that when this routine is called, some of the cells on the page
55596** might not actually be stored in MemPage.aData[]. This can happen
55597** if the page is overfull. This routine ensures that all cells allocated
55598** to the page and its siblings fit into MemPage.aData[] before returning.
55599**
55600** In the course of balancing the page and its siblings, cells may be
55601** inserted into or removed from the parent page (pParent). Doing so
55602** may cause the parent page to become overfull or underfull. If this
55603** happens, it is the responsibility of the caller to invoke the correct
55604** balancing routine to fix this problem (see the balance() routine).
55605**
55606** If this routine fails for any reason, it might leave the database
55607** in a corrupted state. So if this routine fails, the database should
55608** be rolled back.
55609**
55610** The third argument to this function, aOvflSpace, is a pointer to a
55611** buffer big enough to hold one page. If while inserting cells into the parent
55612** page (pParent) the parent page becomes overfull, this buffer is
55613** used to store the parent's overflow cells. Because this function inserts
55614** a maximum of four divider cells into the parent page, and the maximum
55615** size of a cell stored within an internal node is always less than 1/4
55616** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
55617** enough for all overflow cells.
55618**
55619** If aOvflSpace is set to a null pointer, this function returns
55620** SQLITE_NOMEM.
55621*/
55622#if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
55623#pragma optimize("", off)
55624#endif
55625static int balance_nonroot(
55626  MemPage *pParent,               /* Parent page of siblings being balanced */
55627  int iParentIdx,                 /* Index of "the page" in pParent */
55628  u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
55629  int isRoot,                     /* True if pParent is a root-page */
55630  int bBulk                       /* True if this call is part of a bulk load */
55631){
55632  BtShared *pBt;               /* The whole database */
55633  int nCell = 0;               /* Number of cells in apCell[] */
55634  int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
55635  int nNew = 0;                /* Number of pages in apNew[] */
55636  int nOld;                    /* Number of pages in apOld[] */
55637  int i, j, k;                 /* Loop counters */
55638  int nxDiv;                   /* Next divider slot in pParent->aCell[] */
55639  int rc = SQLITE_OK;          /* The return code */
55640  u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
55641  int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
55642  int usableSpace;             /* Bytes in pPage beyond the header */
55643  int pageFlags;               /* Value of pPage->aData[0] */
55644  int subtotal;                /* Subtotal of bytes in cells on one page */
55645  int iSpace1 = 0;             /* First unused byte of aSpace1[] */
55646  int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
55647  int szScratch;               /* Size of scratch memory requested */
55648  MemPage *apOld[NB];          /* pPage and up to two siblings */
55649  MemPage *apCopy[NB];         /* Private copies of apOld[] pages */
55650  MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
55651  u8 *pRight;                  /* Location in parent of right-sibling pointer */
55652  u8 *apDiv[NB-1];             /* Divider cells in pParent */
55653  int cntNew[NB+2];            /* Index in aCell[] of cell after i-th page */
55654  int szNew[NB+2];             /* Combined size of cells place on i-th page */
55655  u8 **apCell = 0;             /* All cells begin balanced */
55656  u16 *szCell;                 /* Local size of all cells in apCell[] */
55657  u8 *aSpace1;                 /* Space for copies of dividers cells */
55658  Pgno pgno;                   /* Temp var to store a page number in */
55659
55660  pBt = pParent->pBt;
55661  assert( sqlite3_mutex_held(pBt->mutex) );
55662  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
55663
55664#if 0
55665  TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
55666#endif
55667
55668  /* At this point pParent may have at most one overflow cell. And if
55669  ** this overflow cell is present, it must be the cell with
55670  ** index iParentIdx. This scenario comes about when this function
55671  ** is called (indirectly) from sqlite3BtreeDelete().
55672  */
55673  assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
55674  assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
55675
55676  if( !aOvflSpace ){
55677    return SQLITE_NOMEM;
55678  }
55679
55680  /* Find the sibling pages to balance. Also locate the cells in pParent
55681  ** that divide the siblings. An attempt is made to find NN siblings on
55682  ** either side of pPage. More siblings are taken from one side, however,
55683  ** if there are fewer than NN siblings on the other side. If pParent
55684  ** has NB or fewer children then all children of pParent are taken.
55685  **
55686  ** This loop also drops the divider cells from the parent page. This
55687  ** way, the remainder of the function does not have to deal with any
55688  ** overflow cells in the parent page, since if any existed they will
55689  ** have already been removed.
55690  */
55691  i = pParent->nOverflow + pParent->nCell;
55692  if( i<2 ){
55693    nxDiv = 0;
55694  }else{
55695    assert( bBulk==0 || bBulk==1 );
55696    if( iParentIdx==0 ){
55697      nxDiv = 0;
55698    }else if( iParentIdx==i ){
55699      nxDiv = i-2+bBulk;
55700    }else{
55701      assert( bBulk==0 );
55702      nxDiv = iParentIdx-1;
55703    }
55704    i = 2-bBulk;
55705  }
55706  nOld = i+1;
55707  if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
55708    pRight = &pParent->aData[pParent->hdrOffset+8];
55709  }else{
55710    pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
55711  }
55712  pgno = get4byte(pRight);
55713  while( 1 ){
55714    rc = getAndInitPage(pBt, pgno, &apOld[i], 0);
55715    if( rc ){
55716      memset(apOld, 0, (i+1)*sizeof(MemPage*));
55717      goto balance_cleanup;
55718    }
55719    nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
55720    if( (i--)==0 ) break;
55721
55722    if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){
55723      apDiv[i] = pParent->apOvfl[0];
55724      pgno = get4byte(apDiv[i]);
55725      szNew[i] = cellSizePtr(pParent, apDiv[i]);
55726      pParent->nOverflow = 0;
55727    }else{
55728      apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
55729      pgno = get4byte(apDiv[i]);
55730      szNew[i] = cellSizePtr(pParent, apDiv[i]);
55731
55732      /* Drop the cell from the parent page. apDiv[i] still points to
55733      ** the cell within the parent, even though it has been dropped.
55734      ** This is safe because dropping a cell only overwrites the first
55735      ** four bytes of it, and this function does not need the first
55736      ** four bytes of the divider cell. So the pointer is safe to use
55737      ** later on.
55738      **
55739      ** But not if we are in secure-delete mode. In secure-delete mode,
55740      ** the dropCell() routine will overwrite the entire cell with zeroes.
55741      ** In this case, temporarily copy the cell into the aOvflSpace[]
55742      ** buffer. It will be copied out again as soon as the aSpace[] buffer
55743      ** is allocated.  */
55744      if( pBt->btsFlags & BTS_SECURE_DELETE ){
55745        int iOff;
55746
55747        iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
55748        if( (iOff+szNew[i])>(int)pBt->usableSize ){
55749          rc = SQLITE_CORRUPT_BKPT;
55750          memset(apOld, 0, (i+1)*sizeof(MemPage*));
55751          goto balance_cleanup;
55752        }else{
55753          memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
55754          apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
55755        }
55756      }
55757      dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
55758    }
55759  }
55760
55761  /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
55762  ** alignment */
55763  nMaxCells = (nMaxCells + 3)&~3;
55764
55765  /*
55766  ** Allocate space for memory structures
55767  */
55768  k = pBt->pageSize + ROUND8(sizeof(MemPage));
55769  szScratch =
55770       nMaxCells*sizeof(u8*)                       /* apCell */
55771     + nMaxCells*sizeof(u16)                       /* szCell */
55772     + pBt->pageSize                               /* aSpace1 */
55773     + k*nOld;                                     /* Page copies (apCopy) */
55774  apCell = sqlite3ScratchMalloc( szScratch );
55775  if( apCell==0 ){
55776    rc = SQLITE_NOMEM;
55777    goto balance_cleanup;
55778  }
55779  szCell = (u16*)&apCell[nMaxCells];
55780  aSpace1 = (u8*)&szCell[nMaxCells];
55781  assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
55782
55783  /*
55784  ** Load pointers to all cells on sibling pages and the divider cells
55785  ** into the local apCell[] array.  Make copies of the divider cells
55786  ** into space obtained from aSpace1[] and remove the divider cells
55787  ** from pParent.
55788  **
55789  ** If the siblings are on leaf pages, then the child pointers of the
55790  ** divider cells are stripped from the cells before they are copied
55791  ** into aSpace1[].  In this way, all cells in apCell[] are without
55792  ** child pointers.  If siblings are not leaves, then all cell in
55793  ** apCell[] include child pointers.  Either way, all cells in apCell[]
55794  ** are alike.
55795  **
55796  ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
55797  **       leafData:  1 if pPage holds key+data and pParent holds only keys.
55798  */
55799  leafCorrection = apOld[0]->leaf*4;
55800  leafData = apOld[0]->hasData;
55801  for(i=0; i<nOld; i++){
55802    int limit;
55803
55804    /* Before doing anything else, take a copy of the i'th original sibling
55805    ** The rest of this function will use data from the copies rather
55806    ** that the original pages since the original pages will be in the
55807    ** process of being overwritten.  */
55808    MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
55809    memcpy(pOld, apOld[i], sizeof(MemPage));
55810    pOld->aData = (void*)&pOld[1];
55811    memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
55812
55813    limit = pOld->nCell+pOld->nOverflow;
55814    if( pOld->nOverflow>0 ){
55815      for(j=0; j<limit; j++){
55816        assert( nCell<nMaxCells );
55817        apCell[nCell] = findOverflowCell(pOld, j);
55818        szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
55819        nCell++;
55820      }
55821    }else{
55822      u8 *aData = pOld->aData;
55823      u16 maskPage = pOld->maskPage;
55824      u16 cellOffset = pOld->cellOffset;
55825      for(j=0; j<limit; j++){
55826        assert( nCell<nMaxCells );
55827        apCell[nCell] = findCellv2(aData, maskPage, cellOffset, j);
55828        szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
55829        nCell++;
55830      }
55831    }
55832    if( i<nOld-1 && !leafData){
55833      u16 sz = (u16)szNew[i];
55834      u8 *pTemp;
55835      assert( nCell<nMaxCells );
55836      szCell[nCell] = sz;
55837      pTemp = &aSpace1[iSpace1];
55838      iSpace1 += sz;
55839      assert( sz<=pBt->maxLocal+23 );
55840      assert( iSpace1 <= (int)pBt->pageSize );
55841      memcpy(pTemp, apDiv[i], sz);
55842      apCell[nCell] = pTemp+leafCorrection;
55843      assert( leafCorrection==0 || leafCorrection==4 );
55844      szCell[nCell] = szCell[nCell] - leafCorrection;
55845      if( !pOld->leaf ){
55846        assert( leafCorrection==0 );
55847        assert( pOld->hdrOffset==0 );
55848        /* The right pointer of the child page pOld becomes the left
55849        ** pointer of the divider cell */
55850        memcpy(apCell[nCell], &pOld->aData[8], 4);
55851      }else{
55852        assert( leafCorrection==4 );
55853        if( szCell[nCell]<4 ){
55854          /* Do not allow any cells smaller than 4 bytes. */
55855          szCell[nCell] = 4;
55856        }
55857      }
55858      nCell++;
55859    }
55860  }
55861
55862  /*
55863  ** Figure out the number of pages needed to hold all nCell cells.
55864  ** Store this number in "k".  Also compute szNew[] which is the total
55865  ** size of all cells on the i-th page and cntNew[] which is the index
55866  ** in apCell[] of the cell that divides page i from page i+1.
55867  ** cntNew[k] should equal nCell.
55868  **
55869  ** Values computed by this block:
55870  **
55871  **           k: The total number of sibling pages
55872  **    szNew[i]: Spaced used on the i-th sibling page.
55873  **   cntNew[i]: Index in apCell[] and szCell[] for the first cell to
55874  **              the right of the i-th sibling page.
55875  ** usableSpace: Number of bytes of space available on each sibling.
55876  **
55877  */
55878  usableSpace = pBt->usableSize - 12 + leafCorrection;
55879  for(subtotal=k=i=0; i<nCell; i++){
55880    assert( i<nMaxCells );
55881    subtotal += szCell[i] + 2;
55882    if( subtotal > usableSpace ){
55883      szNew[k] = subtotal - szCell[i];
55884      cntNew[k] = i;
55885      if( leafData ){ i--; }
55886      subtotal = 0;
55887      k++;
55888      if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
55889    }
55890  }
55891  szNew[k] = subtotal;
55892  cntNew[k] = nCell;
55893  k++;
55894
55895  /*
55896  ** The packing computed by the previous block is biased toward the siblings
55897  ** on the left side.  The left siblings are always nearly full, while the
55898  ** right-most sibling might be nearly empty.  This block of code attempts
55899  ** to adjust the packing of siblings to get a better balance.
55900  **
55901  ** This adjustment is more than an optimization.  The packing above might
55902  ** be so out of balance as to be illegal.  For example, the right-most
55903  ** sibling might be completely empty.  This adjustment is not optional.
55904  */
55905  for(i=k-1; i>0; i--){
55906    int szRight = szNew[i];  /* Size of sibling on the right */
55907    int szLeft = szNew[i-1]; /* Size of sibling on the left */
55908    int r;              /* Index of right-most cell in left sibling */
55909    int d;              /* Index of first cell to the left of right sibling */
55910
55911    r = cntNew[i-1] - 1;
55912    d = r + 1 - leafData;
55913    assert( d<nMaxCells );
55914    assert( r<nMaxCells );
55915    while( szRight==0
55916       || (!bBulk && szRight+szCell[d]+2<=szLeft-(szCell[r]+2))
55917    ){
55918      szRight += szCell[d] + 2;
55919      szLeft -= szCell[r] + 2;
55920      cntNew[i-1]--;
55921      r = cntNew[i-1] - 1;
55922      d = r + 1 - leafData;
55923    }
55924    szNew[i] = szRight;
55925    szNew[i-1] = szLeft;
55926  }
55927
55928  /* Either we found one or more cells (cntnew[0])>0) or pPage is
55929  ** a virtual root page.  A virtual root page is when the real root
55930  ** page is page 1 and we are the only child of that page.
55931  **
55932  ** UPDATE:  The assert() below is not necessarily true if the database
55933  ** file is corrupt.  The corruption will be detected and reported later
55934  ** in this procedure so there is no need to act upon it now.
55935  */
55936#if 0
55937  assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
55938#endif
55939
55940  TRACE(("BALANCE: old: %d %d %d  ",
55941    apOld[0]->pgno,
55942    nOld>=2 ? apOld[1]->pgno : 0,
55943    nOld>=3 ? apOld[2]->pgno : 0
55944  ));
55945
55946  /*
55947  ** Allocate k new pages.  Reuse old pages where possible.
55948  */
55949  if( apOld[0]->pgno<=1 ){
55950    rc = SQLITE_CORRUPT_BKPT;
55951    goto balance_cleanup;
55952  }
55953  pageFlags = apOld[0]->aData[0];
55954  for(i=0; i<k; i++){
55955    MemPage *pNew;
55956    if( i<nOld ){
55957      pNew = apNew[i] = apOld[i];
55958      apOld[i] = 0;
55959      rc = sqlite3PagerWrite(pNew->pDbPage);
55960      nNew++;
55961      if( rc ) goto balance_cleanup;
55962    }else{
55963      assert( i>0 );
55964      rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
55965      if( rc ) goto balance_cleanup;
55966      apNew[i] = pNew;
55967      nNew++;
55968
55969      /* Set the pointer-map entry for the new sibling page. */
55970      if( ISAUTOVACUUM ){
55971        ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
55972        if( rc!=SQLITE_OK ){
55973          goto balance_cleanup;
55974        }
55975      }
55976    }
55977  }
55978
55979  /* Free any old pages that were not reused as new pages.
55980  */
55981  while( i<nOld ){
55982    freePage(apOld[i], &rc);
55983    if( rc ) goto balance_cleanup;
55984    releasePage(apOld[i]);
55985    apOld[i] = 0;
55986    i++;
55987  }
55988
55989  /*
55990  ** Put the new pages in accending order.  This helps to
55991  ** keep entries in the disk file in order so that a scan
55992  ** of the table is a linear scan through the file.  That
55993  ** in turn helps the operating system to deliver pages
55994  ** from the disk more rapidly.
55995  **
55996  ** An O(n^2) insertion sort algorithm is used, but since
55997  ** n is never more than NB (a small constant), that should
55998  ** not be a problem.
55999  **
56000  ** When NB==3, this one optimization makes the database
56001  ** about 25% faster for large insertions and deletions.
56002  */
56003  for(i=0; i<k-1; i++){
56004    int minV = apNew[i]->pgno;
56005    int minI = i;
56006    for(j=i+1; j<k; j++){
56007      if( apNew[j]->pgno<(unsigned)minV ){
56008        minI = j;
56009        minV = apNew[j]->pgno;
56010      }
56011    }
56012    if( minI>i ){
56013      MemPage *pT;
56014      pT = apNew[i];
56015      apNew[i] = apNew[minI];
56016      apNew[minI] = pT;
56017    }
56018  }
56019  TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
56020    apNew[0]->pgno, szNew[0],
56021    nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
56022    nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
56023    nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
56024    nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
56025
56026  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
56027  put4byte(pRight, apNew[nNew-1]->pgno);
56028
56029  /*
56030  ** Evenly distribute the data in apCell[] across the new pages.
56031  ** Insert divider cells into pParent as necessary.
56032  */
56033  j = 0;
56034  for(i=0; i<nNew; i++){
56035    /* Assemble the new sibling page. */
56036    MemPage *pNew = apNew[i];
56037    assert( j<nMaxCells );
56038    zeroPage(pNew, pageFlags);
56039    assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
56040    assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
56041    assert( pNew->nOverflow==0 );
56042
56043    j = cntNew[i];
56044
56045    /* If the sibling page assembled above was not the right-most sibling,
56046    ** insert a divider cell into the parent page.
56047    */
56048    assert( i<nNew-1 || j==nCell );
56049    if( j<nCell ){
56050      u8 *pCell;
56051      u8 *pTemp;
56052      int sz;
56053
56054      assert( j<nMaxCells );
56055      pCell = apCell[j];
56056      sz = szCell[j] + leafCorrection;
56057      pTemp = &aOvflSpace[iOvflSpace];
56058      if( !pNew->leaf ){
56059        memcpy(&pNew->aData[8], pCell, 4);
56060      }else if( leafData ){
56061        /* If the tree is a leaf-data tree, and the siblings are leaves,
56062        ** then there is no divider cell in apCell[]. Instead, the divider
56063        ** cell consists of the integer key for the right-most cell of
56064        ** the sibling-page assembled above only.
56065        */
56066        CellInfo info;
56067        j--;
56068        btreeParseCellPtr(pNew, apCell[j], &info);
56069        pCell = pTemp;
56070        sz = 4 + putVarint(&pCell[4], info.nKey);
56071        pTemp = 0;
56072      }else{
56073        pCell -= 4;
56074        /* Obscure case for non-leaf-data trees: If the cell at pCell was
56075        ** previously stored on a leaf node, and its reported size was 4
56076        ** bytes, then it may actually be smaller than this
56077        ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
56078        ** any cell). But it is important to pass the correct size to
56079        ** insertCell(), so reparse the cell now.
56080        **
56081        ** Note that this can never happen in an SQLite data file, as all
56082        ** cells are at least 4 bytes. It only happens in b-trees used
56083        ** to evaluate "IN (SELECT ...)" and similar clauses.
56084        */
56085        if( szCell[j]==4 ){
56086          assert(leafCorrection==4);
56087          sz = cellSizePtr(pParent, pCell);
56088        }
56089      }
56090      iOvflSpace += sz;
56091      assert( sz<=pBt->maxLocal+23 );
56092      assert( iOvflSpace <= (int)pBt->pageSize );
56093      insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
56094      if( rc!=SQLITE_OK ) goto balance_cleanup;
56095      assert( sqlite3PagerIswriteable(pParent->pDbPage) );
56096
56097      j++;
56098      nxDiv++;
56099    }
56100  }
56101  assert( j==nCell );
56102  assert( nOld>0 );
56103  assert( nNew>0 );
56104  if( (pageFlags & PTF_LEAF)==0 ){
56105    u8 *zChild = &apCopy[nOld-1]->aData[8];
56106    memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
56107  }
56108
56109  if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
56110    /* The root page of the b-tree now contains no cells. The only sibling
56111    ** page is the right-child of the parent. Copy the contents of the
56112    ** child page into the parent, decreasing the overall height of the
56113    ** b-tree structure by one. This is described as the "balance-shallower"
56114    ** sub-algorithm in some documentation.
56115    **
56116    ** If this is an auto-vacuum database, the call to copyNodeContent()
56117    ** sets all pointer-map entries corresponding to database image pages
56118    ** for which the pointer is stored within the content being copied.
56119    **
56120    ** The second assert below verifies that the child page is defragmented
56121    ** (it must be, as it was just reconstructed using assemblePage()). This
56122    ** is important if the parent page happens to be page 1 of the database
56123    ** image.  */
56124    assert( nNew==1 );
56125    assert( apNew[0]->nFree ==
56126        (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
56127    );
56128    copyNodeContent(apNew[0], pParent, &rc);
56129    freePage(apNew[0], &rc);
56130  }else if( ISAUTOVACUUM ){
56131    /* Fix the pointer-map entries for all the cells that were shifted around.
56132    ** There are several different types of pointer-map entries that need to
56133    ** be dealt with by this routine. Some of these have been set already, but
56134    ** many have not. The following is a summary:
56135    **
56136    **   1) The entries associated with new sibling pages that were not
56137    **      siblings when this function was called. These have already
56138    **      been set. We don't need to worry about old siblings that were
56139    **      moved to the free-list - the freePage() code has taken care
56140    **      of those.
56141    **
56142    **   2) The pointer-map entries associated with the first overflow
56143    **      page in any overflow chains used by new divider cells. These
56144    **      have also already been taken care of by the insertCell() code.
56145    **
56146    **   3) If the sibling pages are not leaves, then the child pages of
56147    **      cells stored on the sibling pages may need to be updated.
56148    **
56149    **   4) If the sibling pages are not internal intkey nodes, then any
56150    **      overflow pages used by these cells may need to be updated
56151    **      (internal intkey nodes never contain pointers to overflow pages).
56152    **
56153    **   5) If the sibling pages are not leaves, then the pointer-map
56154    **      entries for the right-child pages of each sibling may need
56155    **      to be updated.
56156    **
56157    ** Cases 1 and 2 are dealt with above by other code. The next
56158    ** block deals with cases 3 and 4 and the one after that, case 5. Since
56159    ** setting a pointer map entry is a relatively expensive operation, this
56160    ** code only sets pointer map entries for child or overflow pages that have
56161    ** actually moved between pages.  */
56162    MemPage *pNew = apNew[0];
56163    MemPage *pOld = apCopy[0];
56164    int nOverflow = pOld->nOverflow;
56165    int iNextOld = pOld->nCell + nOverflow;
56166    int iOverflow = (nOverflow ? pOld->aiOvfl[0] : -1);
56167    j = 0;                             /* Current 'old' sibling page */
56168    k = 0;                             /* Current 'new' sibling page */
56169    for(i=0; i<nCell; i++){
56170      int isDivider = 0;
56171      while( i==iNextOld ){
56172        /* Cell i is the cell immediately following the last cell on old
56173        ** sibling page j. If the siblings are not leaf pages of an
56174        ** intkey b-tree, then cell i was a divider cell. */
56175        assert( j+1 < ArraySize(apCopy) );
56176        assert( j+1 < nOld );
56177        pOld = apCopy[++j];
56178        iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
56179        if( pOld->nOverflow ){
56180          nOverflow = pOld->nOverflow;
56181          iOverflow = i + !leafData + pOld->aiOvfl[0];
56182        }
56183        isDivider = !leafData;
56184      }
56185
56186      assert(nOverflow>0 || iOverflow<i );
56187      assert(nOverflow<2 || pOld->aiOvfl[0]==pOld->aiOvfl[1]-1);
56188      assert(nOverflow<3 || pOld->aiOvfl[1]==pOld->aiOvfl[2]-1);
56189      if( i==iOverflow ){
56190        isDivider = 1;
56191        if( (--nOverflow)>0 ){
56192          iOverflow++;
56193        }
56194      }
56195
56196      if( i==cntNew[k] ){
56197        /* Cell i is the cell immediately following the last cell on new
56198        ** sibling page k. If the siblings are not leaf pages of an
56199        ** intkey b-tree, then cell i is a divider cell.  */
56200        pNew = apNew[++k];
56201        if( !leafData ) continue;
56202      }
56203      assert( j<nOld );
56204      assert( k<nNew );
56205
56206      /* If the cell was originally divider cell (and is not now) or
56207      ** an overflow cell, or if the cell was located on a different sibling
56208      ** page before the balancing, then the pointer map entries associated
56209      ** with any child or overflow pages need to be updated.  */
56210      if( isDivider || pOld->pgno!=pNew->pgno ){
56211        if( !leafCorrection ){
56212          ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
56213        }
56214        if( szCell[i]>pNew->minLocal ){
56215          ptrmapPutOvflPtr(pNew, apCell[i], &rc);
56216        }
56217      }
56218    }
56219
56220    if( !leafCorrection ){
56221      for(i=0; i<nNew; i++){
56222        u32 key = get4byte(&apNew[i]->aData[8]);
56223        ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
56224      }
56225    }
56226
56227#if 0
56228    /* The ptrmapCheckPages() contains assert() statements that verify that
56229    ** all pointer map pages are set correctly. This is helpful while
56230    ** debugging. This is usually disabled because a corrupt database may
56231    ** cause an assert() statement to fail.  */
56232    ptrmapCheckPages(apNew, nNew);
56233    ptrmapCheckPages(&pParent, 1);
56234#endif
56235  }
56236
56237  assert( pParent->isInit );
56238  TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
56239          nOld, nNew, nCell));
56240
56241  /*
56242  ** Cleanup before returning.
56243  */
56244balance_cleanup:
56245  sqlite3ScratchFree(apCell);
56246  for(i=0; i<nOld; i++){
56247    releasePage(apOld[i]);
56248  }
56249  for(i=0; i<nNew; i++){
56250    releasePage(apNew[i]);
56251  }
56252
56253  return rc;
56254}
56255#if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
56256#pragma optimize("", on)
56257#endif
56258
56259
56260/*
56261** This function is called when the root page of a b-tree structure is
56262** overfull (has one or more overflow pages).
56263**
56264** A new child page is allocated and the contents of the current root
56265** page, including overflow cells, are copied into the child. The root
56266** page is then overwritten to make it an empty page with the right-child
56267** pointer pointing to the new page.
56268**
56269** Before returning, all pointer-map entries corresponding to pages
56270** that the new child-page now contains pointers to are updated. The
56271** entry corresponding to the new right-child pointer of the root
56272** page is also updated.
56273**
56274** If successful, *ppChild is set to contain a reference to the child
56275** page and SQLITE_OK is returned. In this case the caller is required
56276** to call releasePage() on *ppChild exactly once. If an error occurs,
56277** an error code is returned and *ppChild is set to 0.
56278*/
56279static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
56280  int rc;                        /* Return value from subprocedures */
56281  MemPage *pChild = 0;           /* Pointer to a new child page */
56282  Pgno pgnoChild = 0;            /* Page number of the new child page */
56283  BtShared *pBt = pRoot->pBt;    /* The BTree */
56284
56285  assert( pRoot->nOverflow>0 );
56286  assert( sqlite3_mutex_held(pBt->mutex) );
56287
56288  /* Make pRoot, the root page of the b-tree, writable. Allocate a new
56289  ** page that will become the new right-child of pPage. Copy the contents
56290  ** of the node stored on pRoot into the new child page.
56291  */
56292  rc = sqlite3PagerWrite(pRoot->pDbPage);
56293  if( rc==SQLITE_OK ){
56294    rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
56295    copyNodeContent(pRoot, pChild, &rc);
56296    if( ISAUTOVACUUM ){
56297      ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
56298    }
56299  }
56300  if( rc ){
56301    *ppChild = 0;
56302    releasePage(pChild);
56303    return rc;
56304  }
56305  assert( sqlite3PagerIswriteable(pChild->pDbPage) );
56306  assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
56307  assert( pChild->nCell==pRoot->nCell );
56308
56309  TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
56310
56311  /* Copy the overflow cells from pRoot to pChild */
56312  memcpy(pChild->aiOvfl, pRoot->aiOvfl,
56313         pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
56314  memcpy(pChild->apOvfl, pRoot->apOvfl,
56315         pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
56316  pChild->nOverflow = pRoot->nOverflow;
56317
56318  /* Zero the contents of pRoot. Then install pChild as the right-child. */
56319  zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
56320  put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
56321
56322  *ppChild = pChild;
56323  return SQLITE_OK;
56324}
56325
56326/*
56327** The page that pCur currently points to has just been modified in
56328** some way. This function figures out if this modification means the
56329** tree needs to be balanced, and if so calls the appropriate balancing
56330** routine. Balancing routines are:
56331**
56332**   balance_quick()
56333**   balance_deeper()
56334**   balance_nonroot()
56335*/
56336static int balance(BtCursor *pCur){
56337  int rc = SQLITE_OK;
56338  const int nMin = pCur->pBt->usableSize * 2 / 3;
56339  u8 aBalanceQuickSpace[13];
56340  u8 *pFree = 0;
56341
56342  TESTONLY( int balance_quick_called = 0 );
56343  TESTONLY( int balance_deeper_called = 0 );
56344
56345  do {
56346    int iPage = pCur->iPage;
56347    MemPage *pPage = pCur->apPage[iPage];
56348
56349    if( iPage==0 ){
56350      if( pPage->nOverflow ){
56351        /* The root page of the b-tree is overfull. In this case call the
56352        ** balance_deeper() function to create a new child for the root-page
56353        ** and copy the current contents of the root-page to it. The
56354        ** next iteration of the do-loop will balance the child page.
56355        */
56356        assert( (balance_deeper_called++)==0 );
56357        rc = balance_deeper(pPage, &pCur->apPage[1]);
56358        if( rc==SQLITE_OK ){
56359          pCur->iPage = 1;
56360          pCur->aiIdx[0] = 0;
56361          pCur->aiIdx[1] = 0;
56362          assert( pCur->apPage[1]->nOverflow );
56363        }
56364      }else{
56365        break;
56366      }
56367    }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
56368      break;
56369    }else{
56370      MemPage * const pParent = pCur->apPage[iPage-1];
56371      int const iIdx = pCur->aiIdx[iPage-1];
56372
56373      rc = sqlite3PagerWrite(pParent->pDbPage);
56374      if( rc==SQLITE_OK ){
56375#ifndef SQLITE_OMIT_QUICKBALANCE
56376        if( pPage->hasData
56377         && pPage->nOverflow==1
56378         && pPage->aiOvfl[0]==pPage->nCell
56379         && pParent->pgno!=1
56380         && pParent->nCell==iIdx
56381        ){
56382          /* Call balance_quick() to create a new sibling of pPage on which
56383          ** to store the overflow cell. balance_quick() inserts a new cell
56384          ** into pParent, which may cause pParent overflow. If this
56385          ** happens, the next interation of the do-loop will balance pParent
56386          ** use either balance_nonroot() or balance_deeper(). Until this
56387          ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
56388          ** buffer.
56389          **
56390          ** The purpose of the following assert() is to check that only a
56391          ** single call to balance_quick() is made for each call to this
56392          ** function. If this were not verified, a subtle bug involving reuse
56393          ** of the aBalanceQuickSpace[] might sneak in.
56394          */
56395          assert( (balance_quick_called++)==0 );
56396          rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
56397        }else
56398#endif
56399        {
56400          /* In this case, call balance_nonroot() to redistribute cells
56401          ** between pPage and up to 2 of its sibling pages. This involves
56402          ** modifying the contents of pParent, which may cause pParent to
56403          ** become overfull or underfull. The next iteration of the do-loop
56404          ** will balance the parent page to correct this.
56405          **
56406          ** If the parent page becomes overfull, the overflow cell or cells
56407          ** are stored in the pSpace buffer allocated immediately below.
56408          ** A subsequent iteration of the do-loop will deal with this by
56409          ** calling balance_nonroot() (balance_deeper() may be called first,
56410          ** but it doesn't deal with overflow cells - just moves them to a
56411          ** different page). Once this subsequent call to balance_nonroot()
56412          ** has completed, it is safe to release the pSpace buffer used by
56413          ** the previous call, as the overflow cell data will have been
56414          ** copied either into the body of a database page or into the new
56415          ** pSpace buffer passed to the latter call to balance_nonroot().
56416          */
56417          u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
56418          rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1, pCur->hints);
56419          if( pFree ){
56420            /* If pFree is not NULL, it points to the pSpace buffer used
56421            ** by a previous call to balance_nonroot(). Its contents are
56422            ** now stored either on real database pages or within the
56423            ** new pSpace buffer, so it may be safely freed here. */
56424            sqlite3PageFree(pFree);
56425          }
56426
56427          /* The pSpace buffer will be freed after the next call to
56428          ** balance_nonroot(), or just before this function returns, whichever
56429          ** comes first. */
56430          pFree = pSpace;
56431        }
56432      }
56433
56434      pPage->nOverflow = 0;
56435
56436      /* The next iteration of the do-loop balances the parent page. */
56437      releasePage(pPage);
56438      pCur->iPage--;
56439    }
56440  }while( rc==SQLITE_OK );
56441
56442  if( pFree ){
56443    sqlite3PageFree(pFree);
56444  }
56445  return rc;
56446}
56447
56448
56449/*
56450** Insert a new record into the BTree.  The key is given by (pKey,nKey)
56451** and the data is given by (pData,nData).  The cursor is used only to
56452** define what table the record should be inserted into.  The cursor
56453** is left pointing at a random location.
56454**
56455** For an INTKEY table, only the nKey value of the key is used.  pKey is
56456** ignored.  For a ZERODATA table, the pData and nData are both ignored.
56457**
56458** If the seekResult parameter is non-zero, then a successful call to
56459** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
56460** been performed. seekResult is the search result returned (a negative
56461** number if pCur points at an entry that is smaller than (pKey, nKey), or
56462** a positive value if pCur points at an etry that is larger than
56463** (pKey, nKey)).
56464**
56465** If the seekResult parameter is non-zero, then the caller guarantees that
56466** cursor pCur is pointing at the existing copy of a row that is to be
56467** overwritten.  If the seekResult parameter is 0, then cursor pCur may
56468** point to any entry or to no entry at all and so this function has to seek
56469** the cursor before the new key can be inserted.
56470*/
56471SQLITE_PRIVATE int sqlite3BtreeInsert(
56472  BtCursor *pCur,                /* Insert data into the table of this cursor */
56473  const void *pKey, i64 nKey,    /* The key of the new record */
56474  const void *pData, int nData,  /* The data of the new record */
56475  int nZero,                     /* Number of extra 0 bytes to append to data */
56476  int appendBias,                /* True if this is likely an append */
56477  int seekResult                 /* Result of prior MovetoUnpacked() call */
56478){
56479  int rc;
56480  int loc = seekResult;          /* -1: before desired location  +1: after */
56481  int szNew = 0;
56482  int idx;
56483  MemPage *pPage;
56484  Btree *p = pCur->pBtree;
56485  BtShared *pBt = p->pBt;
56486  unsigned char *oldCell;
56487  unsigned char *newCell = 0;
56488
56489  if( pCur->eState==CURSOR_FAULT ){
56490    assert( pCur->skipNext!=SQLITE_OK );
56491    return pCur->skipNext;
56492  }
56493
56494  assert( cursorHoldsMutex(pCur) );
56495  assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE
56496              && (pBt->btsFlags & BTS_READ_ONLY)==0 );
56497  assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
56498
56499  /* Assert that the caller has been consistent. If this cursor was opened
56500  ** expecting an index b-tree, then the caller should be inserting blob
56501  ** keys with no associated data. If the cursor was opened expecting an
56502  ** intkey table, the caller should be inserting integer keys with a
56503  ** blob of associated data.  */
56504  assert( (pKey==0)==(pCur->pKeyInfo==0) );
56505
56506  /* Save the positions of any other cursors open on this table.
56507  **
56508  ** In some cases, the call to btreeMoveto() below is a no-op. For
56509  ** example, when inserting data into a table with auto-generated integer
56510  ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
56511  ** integer key to use. It then calls this function to actually insert the
56512  ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
56513  ** that the cursor is already where it needs to be and returns without
56514  ** doing any work. To avoid thwarting these optimizations, it is important
56515  ** not to clear the cursor here.
56516  */
56517  rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
56518  if( rc ) return rc;
56519
56520  /* If this is an insert into a table b-tree, invalidate any incrblob
56521  ** cursors open on the row being replaced (assuming this is a replace
56522  ** operation - if it is not, the following is a no-op).  */
56523  if( pCur->pKeyInfo==0 ){
56524    invalidateIncrblobCursors(p, nKey, 0);
56525  }
56526
56527  if( !loc ){
56528    rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
56529    if( rc ) return rc;
56530  }
56531  assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
56532
56533  pPage = pCur->apPage[pCur->iPage];
56534  assert( pPage->intKey || nKey>=0 );
56535  assert( pPage->leaf || !pPage->intKey );
56536
56537  TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
56538          pCur->pgnoRoot, nKey, nData, pPage->pgno,
56539          loc==0 ? "overwrite" : "new entry"));
56540  assert( pPage->isInit );
56541  allocateTempSpace(pBt);
56542  newCell = pBt->pTmpSpace;
56543  if( newCell==0 ) return SQLITE_NOMEM;
56544  rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
56545  if( rc ) goto end_insert;
56546  assert( szNew==cellSizePtr(pPage, newCell) );
56547  assert( szNew <= MX_CELL_SIZE(pBt) );
56548  idx = pCur->aiIdx[pCur->iPage];
56549  if( loc==0 ){
56550    u16 szOld;
56551    assert( idx<pPage->nCell );
56552    rc = sqlite3PagerWrite(pPage->pDbPage);
56553    if( rc ){
56554      goto end_insert;
56555    }
56556    oldCell = findCell(pPage, idx);
56557    if( !pPage->leaf ){
56558      memcpy(newCell, oldCell, 4);
56559    }
56560    szOld = cellSizePtr(pPage, oldCell);
56561    rc = clearCell(pPage, oldCell);
56562    dropCell(pPage, idx, szOld, &rc);
56563    if( rc ) goto end_insert;
56564  }else if( loc<0 && pPage->nCell>0 ){
56565    assert( pPage->leaf );
56566    idx = ++pCur->aiIdx[pCur->iPage];
56567  }else{
56568    assert( pPage->leaf );
56569  }
56570  insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
56571  assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
56572
56573  /* If no error has occurred and pPage has an overflow cell, call balance()
56574  ** to redistribute the cells within the tree. Since balance() may move
56575  ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
56576  ** variables.
56577  **
56578  ** Previous versions of SQLite called moveToRoot() to move the cursor
56579  ** back to the root page as balance() used to invalidate the contents
56580  ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
56581  ** set the cursor state to "invalid". This makes common insert operations
56582  ** slightly faster.
56583  **
56584  ** There is a subtle but important optimization here too. When inserting
56585  ** multiple records into an intkey b-tree using a single cursor (as can
56586  ** happen while processing an "INSERT INTO ... SELECT" statement), it
56587  ** is advantageous to leave the cursor pointing to the last entry in
56588  ** the b-tree if possible. If the cursor is left pointing to the last
56589  ** entry in the table, and the next row inserted has an integer key
56590  ** larger than the largest existing key, it is possible to insert the
56591  ** row without seeking the cursor. This can be a big performance boost.
56592  */
56593  pCur->info.nSize = 0;
56594  pCur->validNKey = 0;
56595  if( rc==SQLITE_OK && pPage->nOverflow ){
56596    rc = balance(pCur);
56597
56598    /* Must make sure nOverflow is reset to zero even if the balance()
56599    ** fails. Internal data structure corruption will result otherwise.
56600    ** Also, set the cursor state to invalid. This stops saveCursorPosition()
56601    ** from trying to save the current position of the cursor.  */
56602    pCur->apPage[pCur->iPage]->nOverflow = 0;
56603    pCur->eState = CURSOR_INVALID;
56604  }
56605  assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
56606
56607end_insert:
56608  return rc;
56609}
56610
56611/*
56612** Delete the entry that the cursor is pointing to.  The cursor
56613** is left pointing at a arbitrary location.
56614*/
56615SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
56616  Btree *p = pCur->pBtree;
56617  BtShared *pBt = p->pBt;
56618  int rc;                              /* Return code */
56619  MemPage *pPage;                      /* Page to delete cell from */
56620  unsigned char *pCell;                /* Pointer to cell to delete */
56621  int iCellIdx;                        /* Index of cell to delete */
56622  int iCellDepth;                      /* Depth of node containing pCell */
56623
56624  assert( cursorHoldsMutex(pCur) );
56625  assert( pBt->inTransaction==TRANS_WRITE );
56626  assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
56627  assert( pCur->wrFlag );
56628  assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
56629  assert( !hasReadConflicts(p, pCur->pgnoRoot) );
56630
56631  if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell)
56632   || NEVER(pCur->eState!=CURSOR_VALID)
56633  ){
56634    return SQLITE_ERROR;  /* Something has gone awry. */
56635  }
56636
56637  iCellDepth = pCur->iPage;
56638  iCellIdx = pCur->aiIdx[iCellDepth];
56639  pPage = pCur->apPage[iCellDepth];
56640  pCell = findCell(pPage, iCellIdx);
56641
56642  /* If the page containing the entry to delete is not a leaf page, move
56643  ** the cursor to the largest entry in the tree that is smaller than
56644  ** the entry being deleted. This cell will replace the cell being deleted
56645  ** from the internal node. The 'previous' entry is used for this instead
56646  ** of the 'next' entry, as the previous entry is always a part of the
56647  ** sub-tree headed by the child page of the cell being deleted. This makes
56648  ** balancing the tree following the delete operation easier.  */
56649  if( !pPage->leaf ){
56650    int notUsed;
56651    rc = sqlite3BtreePrevious(pCur, &notUsed);
56652    if( rc ) return rc;
56653  }
56654
56655  /* Save the positions of any other cursors open on this table before
56656  ** making any modifications. Make the page containing the entry to be
56657  ** deleted writable. Then free any overflow pages associated with the
56658  ** entry and finally remove the cell itself from within the page.
56659  */
56660  rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
56661  if( rc ) return rc;
56662
56663  /* If this is a delete operation to remove a row from a table b-tree,
56664  ** invalidate any incrblob cursors open on the row being deleted.  */
56665  if( pCur->pKeyInfo==0 ){
56666    invalidateIncrblobCursors(p, pCur->info.nKey, 0);
56667  }
56668
56669  rc = sqlite3PagerWrite(pPage->pDbPage);
56670  if( rc ) return rc;
56671  rc = clearCell(pPage, pCell);
56672  dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
56673  if( rc ) return rc;
56674
56675  /* If the cell deleted was not located on a leaf page, then the cursor
56676  ** is currently pointing to the largest entry in the sub-tree headed
56677  ** by the child-page of the cell that was just deleted from an internal
56678  ** node. The cell from the leaf node needs to be moved to the internal
56679  ** node to replace the deleted cell.  */
56680  if( !pPage->leaf ){
56681    MemPage *pLeaf = pCur->apPage[pCur->iPage];
56682    int nCell;
56683    Pgno n = pCur->apPage[iCellDepth+1]->pgno;
56684    unsigned char *pTmp;
56685
56686    pCell = findCell(pLeaf, pLeaf->nCell-1);
56687    nCell = cellSizePtr(pLeaf, pCell);
56688    assert( MX_CELL_SIZE(pBt) >= nCell );
56689
56690    allocateTempSpace(pBt);
56691    pTmp = pBt->pTmpSpace;
56692
56693    rc = sqlite3PagerWrite(pLeaf->pDbPage);
56694    insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
56695    dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
56696    if( rc ) return rc;
56697  }
56698
56699  /* Balance the tree. If the entry deleted was located on a leaf page,
56700  ** then the cursor still points to that page. In this case the first
56701  ** call to balance() repairs the tree, and the if(...) condition is
56702  ** never true.
56703  **
56704  ** Otherwise, if the entry deleted was on an internal node page, then
56705  ** pCur is pointing to the leaf page from which a cell was removed to
56706  ** replace the cell deleted from the internal node. This is slightly
56707  ** tricky as the leaf node may be underfull, and the internal node may
56708  ** be either under or overfull. In this case run the balancing algorithm
56709  ** on the leaf node first. If the balance proceeds far enough up the
56710  ** tree that we can be sure that any problem in the internal node has
56711  ** been corrected, so be it. Otherwise, after balancing the leaf node,
56712  ** walk the cursor up the tree to the internal node and balance it as
56713  ** well.  */
56714  rc = balance(pCur);
56715  if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
56716    while( pCur->iPage>iCellDepth ){
56717      releasePage(pCur->apPage[pCur->iPage--]);
56718    }
56719    rc = balance(pCur);
56720  }
56721
56722  if( rc==SQLITE_OK ){
56723    moveToRoot(pCur);
56724  }
56725  return rc;
56726}
56727
56728/*
56729** Create a new BTree table.  Write into *piTable the page
56730** number for the root page of the new table.
56731**
56732** The type of type is determined by the flags parameter.  Only the
56733** following values of flags are currently in use.  Other values for
56734** flags might not work:
56735**
56736**     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
56737**     BTREE_ZERODATA                  Used for SQL indices
56738*/
56739static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
56740  BtShared *pBt = p->pBt;
56741  MemPage *pRoot;
56742  Pgno pgnoRoot;
56743  int rc;
56744  int ptfFlags;          /* Page-type flage for the root page of new table */
56745
56746  assert( sqlite3BtreeHoldsMutex(p) );
56747  assert( pBt->inTransaction==TRANS_WRITE );
56748  assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
56749
56750#ifdef SQLITE_OMIT_AUTOVACUUM
56751  rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
56752  if( rc ){
56753    return rc;
56754  }
56755#else
56756  if( pBt->autoVacuum ){
56757    Pgno pgnoMove;      /* Move a page here to make room for the root-page */
56758    MemPage *pPageMove; /* The page to move to. */
56759
56760    /* Creating a new table may probably require moving an existing database
56761    ** to make room for the new tables root page. In case this page turns
56762    ** out to be an overflow page, delete all overflow page-map caches
56763    ** held by open cursors.
56764    */
56765    invalidateAllOverflowCache(pBt);
56766
56767    /* Read the value of meta[3] from the database to determine where the
56768    ** root page of the new table should go. meta[3] is the largest root-page
56769    ** created so far, so the new root-page is (meta[3]+1).
56770    */
56771    sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
56772    pgnoRoot++;
56773
56774    /* The new root-page may not be allocated on a pointer-map page, or the
56775    ** PENDING_BYTE page.
56776    */
56777    while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
56778        pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
56779      pgnoRoot++;
56780    }
56781    assert( pgnoRoot>=3 );
56782
56783    /* Allocate a page. The page that currently resides at pgnoRoot will
56784    ** be moved to the allocated page (unless the allocated page happens
56785    ** to reside at pgnoRoot).
56786    */
56787    rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
56788    if( rc!=SQLITE_OK ){
56789      return rc;
56790    }
56791
56792    if( pgnoMove!=pgnoRoot ){
56793      /* pgnoRoot is the page that will be used for the root-page of
56794      ** the new table (assuming an error did not occur). But we were
56795      ** allocated pgnoMove. If required (i.e. if it was not allocated
56796      ** by extending the file), the current page at position pgnoMove
56797      ** is already journaled.
56798      */
56799      u8 eType = 0;
56800      Pgno iPtrPage = 0;
56801
56802      /* Save the positions of any open cursors. This is required in
56803      ** case they are holding a reference to an xFetch reference
56804      ** corresponding to page pgnoRoot.  */
56805      rc = saveAllCursors(pBt, 0, 0);
56806      releasePage(pPageMove);
56807      if( rc!=SQLITE_OK ){
56808        return rc;
56809      }
56810
56811      /* Move the page currently at pgnoRoot to pgnoMove. */
56812      rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0, 0);
56813      if( rc!=SQLITE_OK ){
56814        return rc;
56815      }
56816      rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
56817      if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
56818        rc = SQLITE_CORRUPT_BKPT;
56819      }
56820      if( rc!=SQLITE_OK ){
56821        releasePage(pRoot);
56822        return rc;
56823      }
56824      assert( eType!=PTRMAP_ROOTPAGE );
56825      assert( eType!=PTRMAP_FREEPAGE );
56826      rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
56827      releasePage(pRoot);
56828
56829      /* Obtain the page at pgnoRoot */
56830      if( rc!=SQLITE_OK ){
56831        return rc;
56832      }
56833      rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0, 0);
56834      if( rc!=SQLITE_OK ){
56835        return rc;
56836      }
56837      rc = sqlite3PagerWrite(pRoot->pDbPage);
56838      if( rc!=SQLITE_OK ){
56839        releasePage(pRoot);
56840        return rc;
56841      }
56842    }else{
56843      pRoot = pPageMove;
56844    }
56845
56846    /* Update the pointer-map and meta-data with the new root-page number. */
56847    ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
56848    if( rc ){
56849      releasePage(pRoot);
56850      return rc;
56851    }
56852
56853    /* When the new root page was allocated, page 1 was made writable in
56854    ** order either to increase the database filesize, or to decrement the
56855    ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
56856    */
56857    assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
56858    rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
56859    if( NEVER(rc) ){
56860      releasePage(pRoot);
56861      return rc;
56862    }
56863
56864  }else{
56865    rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
56866    if( rc ) return rc;
56867  }
56868#endif
56869  assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
56870  if( createTabFlags & BTREE_INTKEY ){
56871    ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
56872  }else{
56873    ptfFlags = PTF_ZERODATA | PTF_LEAF;
56874  }
56875  zeroPage(pRoot, ptfFlags);
56876  sqlite3PagerUnref(pRoot->pDbPage);
56877  assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
56878  *piTable = (int)pgnoRoot;
56879  return SQLITE_OK;
56880}
56881SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
56882  int rc;
56883  sqlite3BtreeEnter(p);
56884  rc = btreeCreateTable(p, piTable, flags);
56885  sqlite3BtreeLeave(p);
56886  return rc;
56887}
56888
56889/*
56890** Erase the given database page and all its children.  Return
56891** the page to the freelist.
56892*/
56893static int clearDatabasePage(
56894  BtShared *pBt,           /* The BTree that contains the table */
56895  Pgno pgno,               /* Page number to clear */
56896  int freePageFlag,        /* Deallocate page if true */
56897  int *pnChange            /* Add number of Cells freed to this counter */
56898){
56899  MemPage *pPage;
56900  int rc;
56901  unsigned char *pCell;
56902  int i;
56903
56904  assert( sqlite3_mutex_held(pBt->mutex) );
56905  if( pgno>btreePagecount(pBt) ){
56906    return SQLITE_CORRUPT_BKPT;
56907  }
56908
56909  rc = getAndInitPage(pBt, pgno, &pPage, 0);
56910  if( rc ) return rc;
56911  for(i=0; i<pPage->nCell; i++){
56912    pCell = findCell(pPage, i);
56913    if( !pPage->leaf ){
56914      rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
56915      if( rc ) goto cleardatabasepage_out;
56916    }
56917    rc = clearCell(pPage, pCell);
56918    if( rc ) goto cleardatabasepage_out;
56919  }
56920  if( !pPage->leaf ){
56921    rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
56922    if( rc ) goto cleardatabasepage_out;
56923  }else if( pnChange ){
56924    assert( pPage->intKey );
56925    *pnChange += pPage->nCell;
56926  }
56927  if( freePageFlag ){
56928    freePage(pPage, &rc);
56929  }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
56930    zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
56931  }
56932
56933cleardatabasepage_out:
56934  releasePage(pPage);
56935  return rc;
56936}
56937
56938/*
56939** Delete all information from a single table in the database.  iTable is
56940** the page number of the root of the table.  After this routine returns,
56941** the root page is empty, but still exists.
56942**
56943** This routine will fail with SQLITE_LOCKED if there are any open
56944** read cursors on the table.  Open write cursors are moved to the
56945** root of the table.
56946**
56947** If pnChange is not NULL, then table iTable must be an intkey table. The
56948** integer value pointed to by pnChange is incremented by the number of
56949** entries in the table.
56950*/
56951SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
56952  int rc;
56953  BtShared *pBt = p->pBt;
56954  sqlite3BtreeEnter(p);
56955  assert( p->inTrans==TRANS_WRITE );
56956
56957  rc = saveAllCursors(pBt, (Pgno)iTable, 0);
56958
56959  if( SQLITE_OK==rc ){
56960    /* Invalidate all incrblob cursors open on table iTable (assuming iTable
56961    ** is the root of a table b-tree - if it is not, the following call is
56962    ** a no-op).  */
56963    invalidateIncrblobCursors(p, 0, 1);
56964    rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
56965  }
56966  sqlite3BtreeLeave(p);
56967  return rc;
56968}
56969
56970/*
56971** Erase all information in a table and add the root of the table to
56972** the freelist.  Except, the root of the principle table (the one on
56973** page 1) is never added to the freelist.
56974**
56975** This routine will fail with SQLITE_LOCKED if there are any open
56976** cursors on the table.
56977**
56978** If AUTOVACUUM is enabled and the page at iTable is not the last
56979** root page in the database file, then the last root page
56980** in the database file is moved into the slot formerly occupied by
56981** iTable and that last slot formerly occupied by the last root page
56982** is added to the freelist instead of iTable.  In this say, all
56983** root pages are kept at the beginning of the database file, which
56984** is necessary for AUTOVACUUM to work right.  *piMoved is set to the
56985** page number that used to be the last root page in the file before
56986** the move.  If no page gets moved, *piMoved is set to 0.
56987** The last root page is recorded in meta[3] and the value of
56988** meta[3] is updated by this procedure.
56989*/
56990static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
56991  int rc;
56992  MemPage *pPage = 0;
56993  BtShared *pBt = p->pBt;
56994
56995  assert( sqlite3BtreeHoldsMutex(p) );
56996  assert( p->inTrans==TRANS_WRITE );
56997
56998  /* It is illegal to drop a table if any cursors are open on the
56999  ** database. This is because in auto-vacuum mode the backend may
57000  ** need to move another root-page to fill a gap left by the deleted
57001  ** root page. If an open cursor was using this page a problem would
57002  ** occur.
57003  **
57004  ** This error is caught long before control reaches this point.
57005  */
57006  if( NEVER(pBt->pCursor) ){
57007    sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
57008    return SQLITE_LOCKED_SHAREDCACHE;
57009  }
57010
57011  rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0, 0);
57012  if( rc ) return rc;
57013  rc = sqlite3BtreeClearTable(p, iTable, 0);
57014  if( rc ){
57015    releasePage(pPage);
57016    return rc;
57017  }
57018
57019  *piMoved = 0;
57020
57021  if( iTable>1 ){
57022#ifdef SQLITE_OMIT_AUTOVACUUM
57023    freePage(pPage, &rc);
57024    releasePage(pPage);
57025#else
57026    if( pBt->autoVacuum ){
57027      Pgno maxRootPgno;
57028      sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
57029
57030      if( iTable==maxRootPgno ){
57031        /* If the table being dropped is the table with the largest root-page
57032        ** number in the database, put the root page on the free list.
57033        */
57034        freePage(pPage, &rc);
57035        releasePage(pPage);
57036        if( rc!=SQLITE_OK ){
57037          return rc;
57038        }
57039      }else{
57040        /* The table being dropped does not have the largest root-page
57041        ** number in the database. So move the page that does into the
57042        ** gap left by the deleted root-page.
57043        */
57044        MemPage *pMove;
57045        releasePage(pPage);
57046        rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0, 0);
57047        if( rc!=SQLITE_OK ){
57048          return rc;
57049        }
57050        rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
57051        releasePage(pMove);
57052        if( rc!=SQLITE_OK ){
57053          return rc;
57054        }
57055        pMove = 0;
57056        rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0, 0);
57057        freePage(pMove, &rc);
57058        releasePage(pMove);
57059        if( rc!=SQLITE_OK ){
57060          return rc;
57061        }
57062        *piMoved = maxRootPgno;
57063      }
57064
57065      /* Set the new 'max-root-page' value in the database header. This
57066      ** is the old value less one, less one more if that happens to
57067      ** be a root-page number, less one again if that is the
57068      ** PENDING_BYTE_PAGE.
57069      */
57070      maxRootPgno--;
57071      while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
57072             || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
57073        maxRootPgno--;
57074      }
57075      assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
57076
57077      rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
57078    }else{
57079      freePage(pPage, &rc);
57080      releasePage(pPage);
57081    }
57082#endif
57083  }else{
57084    /* If sqlite3BtreeDropTable was called on page 1.
57085    ** This really never should happen except in a corrupt
57086    ** database.
57087    */
57088    zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
57089    releasePage(pPage);
57090  }
57091  return rc;
57092}
57093SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
57094  int rc;
57095  sqlite3BtreeEnter(p);
57096  rc = btreeDropTable(p, iTable, piMoved);
57097  sqlite3BtreeLeave(p);
57098  return rc;
57099}
57100
57101
57102/*
57103** This function may only be called if the b-tree connection already
57104** has a read or write transaction open on the database.
57105**
57106** Read the meta-information out of a database file.  Meta[0]
57107** is the number of free pages currently in the database.  Meta[1]
57108** through meta[15] are available for use by higher layers.  Meta[0]
57109** is read-only, the others are read/write.
57110**
57111** The schema layer numbers meta values differently.  At the schema
57112** layer (and the SetCookie and ReadCookie opcodes) the number of
57113** free pages is not visible.  So Cookie[0] is the same as Meta[1].
57114*/
57115SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
57116  BtShared *pBt = p->pBt;
57117
57118  sqlite3BtreeEnter(p);
57119  assert( p->inTrans>TRANS_NONE );
57120  assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
57121  assert( pBt->pPage1 );
57122  assert( idx>=0 && idx<=15 );
57123
57124  *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
57125
57126  /* If auto-vacuum is disabled in this build and this is an auto-vacuum
57127  ** database, mark the database as read-only.  */
57128#ifdef SQLITE_OMIT_AUTOVACUUM
57129  if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
57130    pBt->btsFlags |= BTS_READ_ONLY;
57131  }
57132#endif
57133
57134  sqlite3BtreeLeave(p);
57135}
57136
57137/*
57138** Write meta-information back into the database.  Meta[0] is
57139** read-only and may not be written.
57140*/
57141SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
57142  BtShared *pBt = p->pBt;
57143  unsigned char *pP1;
57144  int rc;
57145  assert( idx>=1 && idx<=15 );
57146  sqlite3BtreeEnter(p);
57147  assert( p->inTrans==TRANS_WRITE );
57148  assert( pBt->pPage1!=0 );
57149  pP1 = pBt->pPage1->aData;
57150  rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
57151  if( rc==SQLITE_OK ){
57152    put4byte(&pP1[36 + idx*4], iMeta);
57153#ifndef SQLITE_OMIT_AUTOVACUUM
57154    if( idx==BTREE_INCR_VACUUM ){
57155      assert( pBt->autoVacuum || iMeta==0 );
57156      assert( iMeta==0 || iMeta==1 );
57157      pBt->incrVacuum = (u8)iMeta;
57158    }
57159#endif
57160  }
57161  sqlite3BtreeLeave(p);
57162  return rc;
57163}
57164
57165#ifndef SQLITE_OMIT_BTREECOUNT
57166/*
57167** The first argument, pCur, is a cursor opened on some b-tree. Count the
57168** number of entries in the b-tree and write the result to *pnEntry.
57169**
57170** SQLITE_OK is returned if the operation is successfully executed.
57171** Otherwise, if an error is encountered (i.e. an IO error or database
57172** corruption) an SQLite error code is returned.
57173*/
57174SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
57175  i64 nEntry = 0;                      /* Value to return in *pnEntry */
57176  int rc;                              /* Return code */
57177
57178  if( pCur->pgnoRoot==0 ){
57179    *pnEntry = 0;
57180    return SQLITE_OK;
57181  }
57182  rc = moveToRoot(pCur);
57183
57184  /* Unless an error occurs, the following loop runs one iteration for each
57185  ** page in the B-Tree structure (not including overflow pages).
57186  */
57187  while( rc==SQLITE_OK ){
57188    int iIdx;                          /* Index of child node in parent */
57189    MemPage *pPage;                    /* Current page of the b-tree */
57190
57191    /* If this is a leaf page or the tree is not an int-key tree, then
57192    ** this page contains countable entries. Increment the entry counter
57193    ** accordingly.
57194    */
57195    pPage = pCur->apPage[pCur->iPage];
57196    if( pPage->leaf || !pPage->intKey ){
57197      nEntry += pPage->nCell;
57198    }
57199
57200    /* pPage is a leaf node. This loop navigates the cursor so that it
57201    ** points to the first interior cell that it points to the parent of
57202    ** the next page in the tree that has not yet been visited. The
57203    ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
57204    ** of the page, or to the number of cells in the page if the next page
57205    ** to visit is the right-child of its parent.
57206    **
57207    ** If all pages in the tree have been visited, return SQLITE_OK to the
57208    ** caller.
57209    */
57210    if( pPage->leaf ){
57211      do {
57212        if( pCur->iPage==0 ){
57213          /* All pages of the b-tree have been visited. Return successfully. */
57214          *pnEntry = nEntry;
57215          return SQLITE_OK;
57216        }
57217        moveToParent(pCur);
57218      }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
57219
57220      pCur->aiIdx[pCur->iPage]++;
57221      pPage = pCur->apPage[pCur->iPage];
57222    }
57223
57224    /* Descend to the child node of the cell that the cursor currently
57225    ** points at. This is the right-child if (iIdx==pPage->nCell).
57226    */
57227    iIdx = pCur->aiIdx[pCur->iPage];
57228    if( iIdx==pPage->nCell ){
57229      rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
57230    }else{
57231      rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
57232    }
57233  }
57234
57235  /* An error has occurred. Return an error code. */
57236  return rc;
57237}
57238#endif
57239
57240/*
57241** Return the pager associated with a BTree.  This routine is used for
57242** testing and debugging only.
57243*/
57244SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
57245  return p->pBt->pPager;
57246}
57247
57248#ifndef SQLITE_OMIT_INTEGRITY_CHECK
57249/*
57250** Append a message to the error message string.
57251*/
57252static void checkAppendMsg(
57253  IntegrityCk *pCheck,
57254  char *zMsg1,
57255  const char *zFormat,
57256  ...
57257){
57258  va_list ap;
57259  if( !pCheck->mxErr ) return;
57260  pCheck->mxErr--;
57261  pCheck->nErr++;
57262  va_start(ap, zFormat);
57263  if( pCheck->errMsg.nChar ){
57264    sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
57265  }
57266  if( zMsg1 ){
57267    sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
57268  }
57269  sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
57270  va_end(ap);
57271  if( pCheck->errMsg.mallocFailed ){
57272    pCheck->mallocFailed = 1;
57273  }
57274}
57275#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
57276
57277#ifndef SQLITE_OMIT_INTEGRITY_CHECK
57278
57279/*
57280** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
57281** corresponds to page iPg is already set.
57282*/
57283static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
57284  assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
57285  return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
57286}
57287
57288/*
57289** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
57290*/
57291static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
57292  assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
57293  pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
57294}
57295
57296
57297/*
57298** Add 1 to the reference count for page iPage.  If this is the second
57299** reference to the page, add an error message to pCheck->zErrMsg.
57300** Return 1 if there are 2 ore more references to the page and 0 if
57301** if this is the first reference to the page.
57302**
57303** Also check that the page number is in bounds.
57304*/
57305static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
57306  if( iPage==0 ) return 1;
57307  if( iPage>pCheck->nPage ){
57308    checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
57309    return 1;
57310  }
57311  if( getPageReferenced(pCheck, iPage) ){
57312    checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
57313    return 1;
57314  }
57315  setPageReferenced(pCheck, iPage);
57316  return 0;
57317}
57318
57319#ifndef SQLITE_OMIT_AUTOVACUUM
57320/*
57321** Check that the entry in the pointer-map for page iChild maps to
57322** page iParent, pointer type ptrType. If not, append an error message
57323** to pCheck.
57324*/
57325static void checkPtrmap(
57326  IntegrityCk *pCheck,   /* Integrity check context */
57327  Pgno iChild,           /* Child page number */
57328  u8 eType,              /* Expected pointer map type */
57329  Pgno iParent,          /* Expected pointer map parent page number */
57330  char *zContext         /* Context description (used for error msg) */
57331){
57332  int rc;
57333  u8 ePtrmapType;
57334  Pgno iPtrmapParent;
57335
57336  rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
57337  if( rc!=SQLITE_OK ){
57338    if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
57339    checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
57340    return;
57341  }
57342
57343  if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
57344    checkAppendMsg(pCheck, zContext,
57345      "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
57346      iChild, eType, iParent, ePtrmapType, iPtrmapParent);
57347  }
57348}
57349#endif
57350
57351/*
57352** Check the integrity of the freelist or of an overflow page list.
57353** Verify that the number of pages on the list is N.
57354*/
57355static void checkList(
57356  IntegrityCk *pCheck,  /* Integrity checking context */
57357  int isFreeList,       /* True for a freelist.  False for overflow page list */
57358  int iPage,            /* Page number for first page in the list */
57359  int N,                /* Expected number of pages in the list */
57360  char *zContext        /* Context for error messages */
57361){
57362  int i;
57363  int expected = N;
57364  int iFirst = iPage;
57365  while( N-- > 0 && pCheck->mxErr ){
57366    DbPage *pOvflPage;
57367    unsigned char *pOvflData;
57368    if( iPage<1 ){
57369      checkAppendMsg(pCheck, zContext,
57370         "%d of %d pages missing from overflow list starting at %d",
57371          N+1, expected, iFirst);
57372      break;
57373    }
57374    if( checkRef(pCheck, iPage, zContext) ) break;
57375    if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
57376      checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
57377      break;
57378    }
57379    pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
57380    if( isFreeList ){
57381      int n = get4byte(&pOvflData[4]);
57382#ifndef SQLITE_OMIT_AUTOVACUUM
57383      if( pCheck->pBt->autoVacuum ){
57384        checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
57385      }
57386#endif
57387      if( n>(int)pCheck->pBt->usableSize/4-2 ){
57388        checkAppendMsg(pCheck, zContext,
57389           "freelist leaf count too big on page %d", iPage);
57390        N--;
57391      }else{
57392        for(i=0; i<n; i++){
57393          Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
57394#ifndef SQLITE_OMIT_AUTOVACUUM
57395          if( pCheck->pBt->autoVacuum ){
57396            checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
57397          }
57398#endif
57399          checkRef(pCheck, iFreePage, zContext);
57400        }
57401        N -= n;
57402      }
57403    }
57404#ifndef SQLITE_OMIT_AUTOVACUUM
57405    else{
57406      /* If this database supports auto-vacuum and iPage is not the last
57407      ** page in this overflow list, check that the pointer-map entry for
57408      ** the following page matches iPage.
57409      */
57410      if( pCheck->pBt->autoVacuum && N>0 ){
57411        i = get4byte(pOvflData);
57412        checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
57413      }
57414    }
57415#endif
57416    iPage = get4byte(pOvflData);
57417    sqlite3PagerUnref(pOvflPage);
57418  }
57419}
57420#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
57421
57422#ifndef SQLITE_OMIT_INTEGRITY_CHECK
57423/*
57424** Do various sanity checks on a single page of a tree.  Return
57425** the tree depth.  Root pages return 0.  Parents of root pages
57426** return 1, and so forth.
57427**
57428** These checks are done:
57429**
57430**      1.  Make sure that cells and freeblocks do not overlap
57431**          but combine to completely cover the page.
57432**  NO  2.  Make sure cell keys are in order.
57433**  NO  3.  Make sure no key is less than or equal to zLowerBound.
57434**  NO  4.  Make sure no key is greater than or equal to zUpperBound.
57435**      5.  Check the integrity of overflow pages.
57436**      6.  Recursively call checkTreePage on all children.
57437**      7.  Verify that the depth of all children is the same.
57438**      8.  Make sure this page is at least 33% full or else it is
57439**          the root of the tree.
57440*/
57441static int checkTreePage(
57442  IntegrityCk *pCheck,  /* Context for the sanity check */
57443  int iPage,            /* Page number of the page to check */
57444  char *zParentContext, /* Parent context */
57445  i64 *pnParentMinKey,
57446  i64 *pnParentMaxKey
57447){
57448  MemPage *pPage;
57449  int i, rc, depth, d2, pgno, cnt;
57450  int hdr, cellStart;
57451  int nCell;
57452  u8 *data;
57453  BtShared *pBt;
57454  int usableSize;
57455  char zContext[100];
57456  char *hit = 0;
57457  i64 nMinKey = 0;
57458  i64 nMaxKey = 0;
57459
57460  sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
57461
57462  /* Check that the page exists
57463  */
57464  pBt = pCheck->pBt;
57465  usableSize = pBt->usableSize;
57466  if( iPage==0 ) return 0;
57467  if( checkRef(pCheck, iPage, zParentContext) ) return 0;
57468  if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0, 0))!=0 ){
57469    checkAppendMsg(pCheck, zContext,
57470       "unable to get the page. error code=%d", rc);
57471    return 0;
57472  }
57473
57474  /* Clear MemPage.isInit to make sure the corruption detection code in
57475  ** btreeInitPage() is executed.  */
57476  pPage->isInit = 0;
57477  if( (rc = btreeInitPage(pPage))!=0 ){
57478    assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
57479    checkAppendMsg(pCheck, zContext,
57480                   "btreeInitPage() returns error code %d", rc);
57481    releasePage(pPage);
57482    return 0;
57483  }
57484
57485  /* Check out all the cells.
57486  */
57487  depth = 0;
57488  for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
57489    u8 *pCell;
57490    u32 sz;
57491    CellInfo info;
57492
57493    /* Check payload overflow pages
57494    */
57495    sqlite3_snprintf(sizeof(zContext), zContext,
57496             "On tree page %d cell %d: ", iPage, i);
57497    pCell = findCell(pPage,i);
57498    btreeParseCellPtr(pPage, pCell, &info);
57499    sz = info.nData;
57500    if( !pPage->intKey ) sz += (int)info.nKey;
57501    /* For intKey pages, check that the keys are in order.
57502    */
57503    else if( i==0 ) nMinKey = nMaxKey = info.nKey;
57504    else{
57505      if( info.nKey <= nMaxKey ){
57506        checkAppendMsg(pCheck, zContext,
57507            "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
57508      }
57509      nMaxKey = info.nKey;
57510    }
57511    assert( sz==info.nPayload );
57512    if( (sz>info.nLocal)
57513     && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
57514    ){
57515      int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
57516      Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
57517#ifndef SQLITE_OMIT_AUTOVACUUM
57518      if( pBt->autoVacuum ){
57519        checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
57520      }
57521#endif
57522      checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
57523    }
57524
57525    /* Check sanity of left child page.
57526    */
57527    if( !pPage->leaf ){
57528      pgno = get4byte(pCell);
57529#ifndef SQLITE_OMIT_AUTOVACUUM
57530      if( pBt->autoVacuum ){
57531        checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
57532      }
57533#endif
57534      d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey);
57535      if( i>0 && d2!=depth ){
57536        checkAppendMsg(pCheck, zContext, "Child page depth differs");
57537      }
57538      depth = d2;
57539    }
57540  }
57541
57542  if( !pPage->leaf ){
57543    pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
57544    sqlite3_snprintf(sizeof(zContext), zContext,
57545                     "On page %d at right child: ", iPage);
57546#ifndef SQLITE_OMIT_AUTOVACUUM
57547    if( pBt->autoVacuum ){
57548      checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
57549    }
57550#endif
57551    checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
57552  }
57553
57554  /* For intKey leaf pages, check that the min/max keys are in order
57555  ** with any left/parent/right pages.
57556  */
57557  if( pPage->leaf && pPage->intKey ){
57558    /* if we are a left child page */
57559    if( pnParentMinKey ){
57560      /* if we are the left most child page */
57561      if( !pnParentMaxKey ){
57562        if( nMaxKey > *pnParentMinKey ){
57563          checkAppendMsg(pCheck, zContext,
57564              "Rowid %lld out of order (max larger than parent min of %lld)",
57565              nMaxKey, *pnParentMinKey);
57566        }
57567      }else{
57568        if( nMinKey <= *pnParentMinKey ){
57569          checkAppendMsg(pCheck, zContext,
57570              "Rowid %lld out of order (min less than parent min of %lld)",
57571              nMinKey, *pnParentMinKey);
57572        }
57573        if( nMaxKey > *pnParentMaxKey ){
57574          checkAppendMsg(pCheck, zContext,
57575              "Rowid %lld out of order (max larger than parent max of %lld)",
57576              nMaxKey, *pnParentMaxKey);
57577        }
57578        *pnParentMinKey = nMaxKey;
57579      }
57580    /* else if we're a right child page */
57581    } else if( pnParentMaxKey ){
57582      if( nMinKey <= *pnParentMaxKey ){
57583        checkAppendMsg(pCheck, zContext,
57584            "Rowid %lld out of order (min less than parent max of %lld)",
57585            nMinKey, *pnParentMaxKey);
57586      }
57587    }
57588  }
57589
57590  /* Check for complete coverage of the page
57591  */
57592  data = pPage->aData;
57593  hdr = pPage->hdrOffset;
57594  hit = sqlite3PageMalloc( pBt->pageSize );
57595  if( hit==0 ){
57596    pCheck->mallocFailed = 1;
57597  }else{
57598    int contentOffset = get2byteNotZero(&data[hdr+5]);
57599    assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
57600    memset(hit+contentOffset, 0, usableSize-contentOffset);
57601    memset(hit, 1, contentOffset);
57602    nCell = get2byte(&data[hdr+3]);
57603    cellStart = hdr + 12 - 4*pPage->leaf;
57604    for(i=0; i<nCell; i++){
57605      int pc = get2byte(&data[cellStart+i*2]);
57606      u32 size = 65536;
57607      int j;
57608      if( pc<=usableSize-4 ){
57609        size = cellSizePtr(pPage, &data[pc]);
57610      }
57611      if( (int)(pc+size-1)>=usableSize ){
57612        checkAppendMsg(pCheck, 0,
57613            "Corruption detected in cell %d on page %d",i,iPage);
57614      }else{
57615        for(j=pc+size-1; j>=pc; j--) hit[j]++;
57616      }
57617    }
57618    i = get2byte(&data[hdr+1]);
57619    while( i>0 ){
57620      int size, j;
57621      assert( i<=usableSize-4 );     /* Enforced by btreeInitPage() */
57622      size = get2byte(&data[i+2]);
57623      assert( i+size<=usableSize );  /* Enforced by btreeInitPage() */
57624      for(j=i+size-1; j>=i; j--) hit[j]++;
57625      j = get2byte(&data[i]);
57626      assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
57627      assert( j<=usableSize-4 );   /* Enforced by btreeInitPage() */
57628      i = j;
57629    }
57630    for(i=cnt=0; i<usableSize; i++){
57631      if( hit[i]==0 ){
57632        cnt++;
57633      }else if( hit[i]>1 ){
57634        checkAppendMsg(pCheck, 0,
57635          "Multiple uses for byte %d of page %d", i, iPage);
57636        break;
57637      }
57638    }
57639    if( cnt!=data[hdr+7] ){
57640      checkAppendMsg(pCheck, 0,
57641          "Fragmentation of %d bytes reported as %d on page %d",
57642          cnt, data[hdr+7], iPage);
57643    }
57644  }
57645  sqlite3PageFree(hit);
57646  releasePage(pPage);
57647  return depth+1;
57648}
57649#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
57650
57651#ifndef SQLITE_OMIT_INTEGRITY_CHECK
57652/*
57653** This routine does a complete check of the given BTree file.  aRoot[] is
57654** an array of pages numbers were each page number is the root page of
57655** a table.  nRoot is the number of entries in aRoot.
57656**
57657** A read-only or read-write transaction must be opened before calling
57658** this function.
57659**
57660** Write the number of error seen in *pnErr.  Except for some memory
57661** allocation errors,  an error message held in memory obtained from
57662** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
57663** returned.  If a memory allocation error occurs, NULL is returned.
57664*/
57665SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
57666  Btree *p,     /* The btree to be checked */
57667  int *aRoot,   /* An array of root pages numbers for individual trees */
57668  int nRoot,    /* Number of entries in aRoot[] */
57669  int mxErr,    /* Stop reporting errors after this many */
57670  int *pnErr    /* Write number of errors seen to this variable */
57671){
57672  Pgno i;
57673  int nRef;
57674  IntegrityCk sCheck;
57675  BtShared *pBt = p->pBt;
57676  char zErr[100];
57677
57678  sqlite3BtreeEnter(p);
57679  assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
57680  nRef = sqlite3PagerRefcount(pBt->pPager);
57681  sCheck.pBt = pBt;
57682  sCheck.pPager = pBt->pPager;
57683  sCheck.nPage = btreePagecount(sCheck.pBt);
57684  sCheck.mxErr = mxErr;
57685  sCheck.nErr = 0;
57686  sCheck.mallocFailed = 0;
57687  *pnErr = 0;
57688  if( sCheck.nPage==0 ){
57689    sqlite3BtreeLeave(p);
57690    return 0;
57691  }
57692
57693  sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
57694  if( !sCheck.aPgRef ){
57695    *pnErr = 1;
57696    sqlite3BtreeLeave(p);
57697    return 0;
57698  }
57699  i = PENDING_BYTE_PAGE(pBt);
57700  if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
57701  sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
57702  sCheck.errMsg.useMalloc = 2;
57703
57704  /* Check the integrity of the freelist
57705  */
57706  checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
57707            get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
57708
57709  /* Check all the tables.
57710  */
57711  for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
57712    if( aRoot[i]==0 ) continue;
57713#ifndef SQLITE_OMIT_AUTOVACUUM
57714    if( pBt->autoVacuum && aRoot[i]>1 ){
57715      checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
57716    }
57717#endif
57718    checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL);
57719  }
57720
57721  /* Make sure every page in the file is referenced
57722  */
57723  for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
57724#ifdef SQLITE_OMIT_AUTOVACUUM
57725    if( getPageReferenced(&sCheck, i)==0 ){
57726      checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
57727    }
57728#else
57729    /* If the database supports auto-vacuum, make sure no tables contain
57730    ** references to pointer-map pages.
57731    */
57732    if( getPageReferenced(&sCheck, i)==0 &&
57733       (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
57734      checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
57735    }
57736    if( getPageReferenced(&sCheck, i)!=0 &&
57737       (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
57738      checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
57739    }
57740#endif
57741  }
57742
57743  /* Make sure this analysis did not leave any unref() pages.
57744  ** This is an internal consistency check; an integrity check
57745  ** of the integrity check.
57746  */
57747  if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
57748    checkAppendMsg(&sCheck, 0,
57749      "Outstanding page count goes from %d to %d during this analysis",
57750      nRef, sqlite3PagerRefcount(pBt->pPager)
57751    );
57752  }
57753
57754  /* Clean  up and report errors.
57755  */
57756  sqlite3BtreeLeave(p);
57757  sqlite3_free(sCheck.aPgRef);
57758  if( sCheck.mallocFailed ){
57759    sqlite3StrAccumReset(&sCheck.errMsg);
57760    *pnErr = sCheck.nErr+1;
57761    return 0;
57762  }
57763  *pnErr = sCheck.nErr;
57764  if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
57765  return sqlite3StrAccumFinish(&sCheck.errMsg);
57766}
57767#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
57768
57769/*
57770** Return the full pathname of the underlying database file.  Return
57771** an empty string if the database is in-memory or a TEMP database.
57772**
57773** The pager filename is invariant as long as the pager is
57774** open so it is safe to access without the BtShared mutex.
57775*/
57776SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
57777  assert( p->pBt->pPager!=0 );
57778  return sqlite3PagerFilename(p->pBt->pPager, 1);
57779}
57780
57781/*
57782** Return the pathname of the journal file for this database. The return
57783** value of this routine is the same regardless of whether the journal file
57784** has been created or not.
57785**
57786** The pager journal filename is invariant as long as the pager is
57787** open so it is safe to access without the BtShared mutex.
57788*/
57789SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
57790  assert( p->pBt->pPager!=0 );
57791  return sqlite3PagerJournalname(p->pBt->pPager);
57792}
57793
57794/*
57795** Return non-zero if a transaction is active.
57796*/
57797SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
57798  assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
57799  return (p && (p->inTrans==TRANS_WRITE));
57800}
57801
57802#ifndef SQLITE_OMIT_WAL
57803/*
57804** Run a checkpoint on the Btree passed as the first argument.
57805**
57806** Return SQLITE_LOCKED if this or any other connection has an open
57807** transaction on the shared-cache the argument Btree is connected to.
57808**
57809** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
57810*/
57811SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
57812  int rc = SQLITE_OK;
57813  if( p ){
57814    BtShared *pBt = p->pBt;
57815    sqlite3BtreeEnter(p);
57816    if( pBt->inTransaction!=TRANS_NONE ){
57817      rc = SQLITE_LOCKED;
57818    }else{
57819      rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
57820    }
57821    sqlite3BtreeLeave(p);
57822  }
57823  return rc;
57824}
57825#endif
57826
57827/*
57828** Return non-zero if a read (or write) transaction is active.
57829*/
57830SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
57831  assert( p );
57832  assert( sqlite3_mutex_held(p->db->mutex) );
57833  return p->inTrans!=TRANS_NONE;
57834}
57835
57836SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
57837  assert( p );
57838  assert( sqlite3_mutex_held(p->db->mutex) );
57839  return p->nBackup!=0;
57840}
57841
57842/*
57843** This function returns a pointer to a blob of memory associated with
57844** a single shared-btree. The memory is used by client code for its own
57845** purposes (for example, to store a high-level schema associated with
57846** the shared-btree). The btree layer manages reference counting issues.
57847**
57848** The first time this is called on a shared-btree, nBytes bytes of memory
57849** are allocated, zeroed, and returned to the caller. For each subsequent
57850** call the nBytes parameter is ignored and a pointer to the same blob
57851** of memory returned.
57852**
57853** If the nBytes parameter is 0 and the blob of memory has not yet been
57854** allocated, a null pointer is returned. If the blob has already been
57855** allocated, it is returned as normal.
57856**
57857** Just before the shared-btree is closed, the function passed as the
57858** xFree argument when the memory allocation was made is invoked on the
57859** blob of allocated memory. The xFree function should not call sqlite3_free()
57860** on the memory, the btree layer does that.
57861*/
57862SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
57863  BtShared *pBt = p->pBt;
57864  sqlite3BtreeEnter(p);
57865  if( !pBt->pSchema && nBytes ){
57866    pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
57867    pBt->xFreeSchema = xFree;
57868  }
57869  sqlite3BtreeLeave(p);
57870  return pBt->pSchema;
57871}
57872
57873/*
57874** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
57875** btree as the argument handle holds an exclusive lock on the
57876** sqlite_master table. Otherwise SQLITE_OK.
57877*/
57878SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
57879  int rc;
57880  assert( sqlite3_mutex_held(p->db->mutex) );
57881  sqlite3BtreeEnter(p);
57882  rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
57883  assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
57884  sqlite3BtreeLeave(p);
57885  return rc;
57886}
57887
57888
57889#ifndef SQLITE_OMIT_SHARED_CACHE
57890/*
57891** Obtain a lock on the table whose root page is iTab.  The
57892** lock is a write lock if isWritelock is true or a read lock
57893** if it is false.
57894*/
57895SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
57896  int rc = SQLITE_OK;
57897  assert( p->inTrans!=TRANS_NONE );
57898  if( p->sharable ){
57899    u8 lockType = READ_LOCK + isWriteLock;
57900    assert( READ_LOCK+1==WRITE_LOCK );
57901    assert( isWriteLock==0 || isWriteLock==1 );
57902
57903    sqlite3BtreeEnter(p);
57904    rc = querySharedCacheTableLock(p, iTab, lockType);
57905    if( rc==SQLITE_OK ){
57906      rc = setSharedCacheTableLock(p, iTab, lockType);
57907    }
57908    sqlite3BtreeLeave(p);
57909  }
57910  return rc;
57911}
57912#endif
57913
57914#ifndef SQLITE_OMIT_INCRBLOB
57915/*
57916** Argument pCsr must be a cursor opened for writing on an
57917** INTKEY table currently pointing at a valid table entry.
57918** This function modifies the data stored as part of that entry.
57919**
57920** Only the data content may only be modified, it is not possible to
57921** change the length of the data stored. If this function is called with
57922** parameters that attempt to write past the end of the existing data,
57923** no modifications are made and SQLITE_CORRUPT is returned.
57924*/
57925SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
57926  int rc;
57927  assert( cursorHoldsMutex(pCsr) );
57928  assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
57929  assert( pCsr->isIncrblobHandle );
57930
57931  rc = restoreCursorPosition(pCsr);
57932  if( rc!=SQLITE_OK ){
57933    return rc;
57934  }
57935  assert( pCsr->eState!=CURSOR_REQUIRESEEK );
57936  if( pCsr->eState!=CURSOR_VALID ){
57937    return SQLITE_ABORT;
57938  }
57939
57940  /* Save the positions of all other cursors open on this table. This is
57941  ** required in case any of them are holding references to an xFetch
57942  ** version of the b-tree page modified by the accessPayload call below.
57943  **
57944  ** Note that pCsr must be open on a BTREE_INTKEY table and saveCursorPosition()
57945  ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
57946  ** saveAllCursors can only return SQLITE_OK.
57947  */
57948  VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
57949  assert( rc==SQLITE_OK );
57950
57951  /* Check some assumptions:
57952  **   (a) the cursor is open for writing,
57953  **   (b) there is a read/write transaction open,
57954  **   (c) the connection holds a write-lock on the table (if required),
57955  **   (d) there are no conflicting read-locks, and
57956  **   (e) the cursor points at a valid row of an intKey table.
57957  */
57958  if( !pCsr->wrFlag ){
57959    return SQLITE_READONLY;
57960  }
57961  assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
57962              && pCsr->pBt->inTransaction==TRANS_WRITE );
57963  assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
57964  assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
57965  assert( pCsr->apPage[pCsr->iPage]->intKey );
57966
57967  return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
57968}
57969
57970/*
57971** Set a flag on this cursor to cache the locations of pages from the
57972** overflow list for the current row. This is used by cursors opened
57973** for incremental blob IO only.
57974**
57975** This function sets a flag only. The actual page location cache
57976** (stored in BtCursor.aOverflow[]) is allocated and used by function
57977** accessPayload() (the worker function for sqlite3BtreeData() and
57978** sqlite3BtreePutData()).
57979*/
57980SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
57981  assert( cursorHoldsMutex(pCur) );
57982  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
57983  invalidateOverflowCache(pCur);
57984  pCur->isIncrblobHandle = 1;
57985}
57986#endif
57987
57988/*
57989** Set both the "read version" (single byte at byte offset 18) and
57990** "write version" (single byte at byte offset 19) fields in the database
57991** header to iVersion.
57992*/
57993SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
57994  BtShared *pBt = pBtree->pBt;
57995  int rc;                         /* Return code */
57996
57997  assert( iVersion==1 || iVersion==2 );
57998
57999  /* If setting the version fields to 1, do not automatically open the
58000  ** WAL connection, even if the version fields are currently set to 2.
58001  */
58002  pBt->btsFlags &= ~BTS_NO_WAL;
58003  if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
58004
58005  rc = sqlite3BtreeBeginTrans(pBtree, 0);
58006  if( rc==SQLITE_OK ){
58007    u8 *aData = pBt->pPage1->aData;
58008    if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
58009      rc = sqlite3BtreeBeginTrans(pBtree, 2);
58010      if( rc==SQLITE_OK ){
58011        rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
58012        if( rc==SQLITE_OK ){
58013          aData[18] = (u8)iVersion;
58014          aData[19] = (u8)iVersion;
58015        }
58016      }
58017    }
58018  }
58019
58020  pBt->btsFlags &= ~BTS_NO_WAL;
58021  return rc;
58022}
58023
58024/*
58025** set the mask of hint flags for cursor pCsr. Currently the only valid
58026** values are 0 and BTREE_BULKLOAD.
58027*/
58028SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *pCsr, unsigned int mask){
58029  assert( mask==BTREE_BULKLOAD || mask==0 );
58030  pCsr->hints = mask;
58031}
58032
58033/************** End of btree.c ***********************************************/
58034/************** Begin file backup.c ******************************************/
58035/*
58036** 2009 January 28
58037**
58038** The author disclaims copyright to this source code.  In place of
58039** a legal notice, here is a blessing:
58040**
58041**    May you do good and not evil.
58042**    May you find forgiveness for yourself and forgive others.
58043**    May you share freely, never taking more than you give.
58044**
58045*************************************************************************
58046** This file contains the implementation of the sqlite3_backup_XXX()
58047** API functions and the related features.
58048*/
58049
58050/* Macro to find the minimum of two numeric values.
58051*/
58052#ifndef MIN
58053# define MIN(x,y) ((x)<(y)?(x):(y))
58054#endif
58055
58056/*
58057** Structure allocated for each backup operation.
58058*/
58059struct sqlite3_backup {
58060  sqlite3* pDestDb;        /* Destination database handle */
58061  Btree *pDest;            /* Destination b-tree file */
58062  u32 iDestSchema;         /* Original schema cookie in destination */
58063  int bDestLocked;         /* True once a write-transaction is open on pDest */
58064
58065  Pgno iNext;              /* Page number of the next source page to copy */
58066  sqlite3* pSrcDb;         /* Source database handle */
58067  Btree *pSrc;             /* Source b-tree file */
58068
58069  int rc;                  /* Backup process error code */
58070
58071  /* These two variables are set by every call to backup_step(). They are
58072  ** read by calls to backup_remaining() and backup_pagecount().
58073  */
58074  Pgno nRemaining;         /* Number of pages left to copy */
58075  Pgno nPagecount;         /* Total number of pages to copy */
58076
58077  int isAttached;          /* True once backup has been registered with pager */
58078  sqlite3_backup *pNext;   /* Next backup associated with source pager */
58079};
58080
58081/*
58082** THREAD SAFETY NOTES:
58083**
58084**   Once it has been created using backup_init(), a single sqlite3_backup
58085**   structure may be accessed via two groups of thread-safe entry points:
58086**
58087**     * Via the sqlite3_backup_XXX() API function backup_step() and
58088**       backup_finish(). Both these functions obtain the source database
58089**       handle mutex and the mutex associated with the source BtShared
58090**       structure, in that order.
58091**
58092**     * Via the BackupUpdate() and BackupRestart() functions, which are
58093**       invoked by the pager layer to report various state changes in
58094**       the page cache associated with the source database. The mutex
58095**       associated with the source database BtShared structure will always
58096**       be held when either of these functions are invoked.
58097**
58098**   The other sqlite3_backup_XXX() API functions, backup_remaining() and
58099**   backup_pagecount() are not thread-safe functions. If they are called
58100**   while some other thread is calling backup_step() or backup_finish(),
58101**   the values returned may be invalid. There is no way for a call to
58102**   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
58103**   or backup_pagecount().
58104**
58105**   Depending on the SQLite configuration, the database handles and/or
58106**   the Btree objects may have their own mutexes that require locking.
58107**   Non-sharable Btrees (in-memory databases for example), do not have
58108**   associated mutexes.
58109*/
58110
58111/*
58112** Return a pointer corresponding to database zDb (i.e. "main", "temp")
58113** in connection handle pDb. If such a database cannot be found, return
58114** a NULL pointer and write an error message to pErrorDb.
58115**
58116** If the "temp" database is requested, it may need to be opened by this
58117** function. If an error occurs while doing so, return 0 and write an
58118** error message to pErrorDb.
58119*/
58120static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
58121  int i = sqlite3FindDbName(pDb, zDb);
58122
58123  if( i==1 ){
58124    Parse *pParse;
58125    int rc = 0;
58126    pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
58127    if( pParse==0 ){
58128      sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory");
58129      rc = SQLITE_NOMEM;
58130    }else{
58131      pParse->db = pDb;
58132      if( sqlite3OpenTempDatabase(pParse) ){
58133        sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
58134        rc = SQLITE_ERROR;
58135      }
58136      sqlite3DbFree(pErrorDb, pParse->zErrMsg);
58137      sqlite3StackFree(pErrorDb, pParse);
58138    }
58139    if( rc ){
58140      return 0;
58141    }
58142  }
58143
58144  if( i<0 ){
58145    sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
58146    return 0;
58147  }
58148
58149  return pDb->aDb[i].pBt;
58150}
58151
58152/*
58153** Attempt to set the page size of the destination to match the page size
58154** of the source.
58155*/
58156static int setDestPgsz(sqlite3_backup *p){
58157  int rc;
58158  rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
58159  return rc;
58160}
58161
58162/*
58163** Create an sqlite3_backup process to copy the contents of zSrcDb from
58164** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
58165** a pointer to the new sqlite3_backup object.
58166**
58167** If an error occurs, NULL is returned and an error code and error message
58168** stored in database handle pDestDb.
58169*/
58170SQLITE_API sqlite3_backup *sqlite3_backup_init(
58171  sqlite3* pDestDb,                     /* Database to write to */
58172  const char *zDestDb,                  /* Name of database within pDestDb */
58173  sqlite3* pSrcDb,                      /* Database connection to read from */
58174  const char *zSrcDb                    /* Name of database within pSrcDb */
58175){
58176  sqlite3_backup *p;                    /* Value to return */
58177
58178  /* Lock the source database handle. The destination database
58179  ** handle is not locked in this routine, but it is locked in
58180  ** sqlite3_backup_step(). The user is required to ensure that no
58181  ** other thread accesses the destination handle for the duration
58182  ** of the backup operation.  Any attempt to use the destination
58183  ** database connection while a backup is in progress may cause
58184  ** a malfunction or a deadlock.
58185  */
58186  sqlite3_mutex_enter(pSrcDb->mutex);
58187  sqlite3_mutex_enter(pDestDb->mutex);
58188
58189  if( pSrcDb==pDestDb ){
58190    sqlite3Error(
58191        pDestDb, SQLITE_ERROR, "source and destination must be distinct"
58192    );
58193    p = 0;
58194  }else {
58195    /* Allocate space for a new sqlite3_backup object...
58196    ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
58197    ** call to sqlite3_backup_init() and is destroyed by a call to
58198    ** sqlite3_backup_finish(). */
58199    p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
58200    if( !p ){
58201      sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
58202    }
58203  }
58204
58205  /* If the allocation succeeded, populate the new object. */
58206  if( p ){
58207    p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
58208    p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
58209    p->pDestDb = pDestDb;
58210    p->pSrcDb = pSrcDb;
58211    p->iNext = 1;
58212    p->isAttached = 0;
58213
58214    if( 0==p->pSrc || 0==p->pDest || setDestPgsz(p)==SQLITE_NOMEM ){
58215      /* One (or both) of the named databases did not exist or an OOM
58216      ** error was hit.  The error has already been written into the
58217      ** pDestDb handle.  All that is left to do here is free the
58218      ** sqlite3_backup structure.
58219      */
58220      sqlite3_free(p);
58221      p = 0;
58222    }
58223  }
58224  if( p ){
58225    p->pSrc->nBackup++;
58226  }
58227
58228  sqlite3_mutex_leave(pDestDb->mutex);
58229  sqlite3_mutex_leave(pSrcDb->mutex);
58230  return p;
58231}
58232
58233/*
58234** Argument rc is an SQLite error code. Return true if this error is
58235** considered fatal if encountered during a backup operation. All errors
58236** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
58237*/
58238static int isFatalError(int rc){
58239  return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
58240}
58241
58242/*
58243** Parameter zSrcData points to a buffer containing the data for
58244** page iSrcPg from the source database. Copy this data into the
58245** destination database.
58246*/
58247static int backupOnePage(
58248  sqlite3_backup *p,              /* Backup handle */
58249  Pgno iSrcPg,                    /* Source database page to backup */
58250  const u8 *zSrcData,             /* Source database page data */
58251  int bUpdate                     /* True for an update, false otherwise */
58252){
58253  Pager * const pDestPager = sqlite3BtreePager(p->pDest);
58254  const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
58255  int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
58256  const int nCopy = MIN(nSrcPgsz, nDestPgsz);
58257  const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
58258#ifdef SQLITE_HAS_CODEC
58259  /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
58260  ** guaranteed that the shared-mutex is held by this thread, handle
58261  ** p->pSrc may not actually be the owner.  */
58262  int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
58263  int nDestReserve = sqlite3BtreeGetReserve(p->pDest);
58264#endif
58265  int rc = SQLITE_OK;
58266  i64 iOff;
58267
58268  assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
58269  assert( p->bDestLocked );
58270  assert( !isFatalError(p->rc) );
58271  assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
58272  assert( zSrcData );
58273
58274  /* Catch the case where the destination is an in-memory database and the
58275  ** page sizes of the source and destination differ.
58276  */
58277  if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
58278    rc = SQLITE_READONLY;
58279  }
58280
58281#ifdef SQLITE_HAS_CODEC
58282  /* Backup is not possible if the page size of the destination is changing
58283  ** and a codec is in use.
58284  */
58285  if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
58286    rc = SQLITE_READONLY;
58287  }
58288
58289  /* Backup is not possible if the number of bytes of reserve space differ
58290  ** between source and destination.  If there is a difference, try to
58291  ** fix the destination to agree with the source.  If that is not possible,
58292  ** then the backup cannot proceed.
58293  */
58294  if( nSrcReserve!=nDestReserve ){
58295    u32 newPgsz = nSrcPgsz;
58296    rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
58297    if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
58298  }
58299#endif
58300
58301  /* This loop runs once for each destination page spanned by the source
58302  ** page. For each iteration, variable iOff is set to the byte offset
58303  ** of the destination page.
58304  */
58305  for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
58306    DbPage *pDestPg = 0;
58307    Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
58308    if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
58309    if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
58310     && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
58311    ){
58312      const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
58313      u8 *zDestData = sqlite3PagerGetData(pDestPg);
58314      u8 *zOut = &zDestData[iOff%nDestPgsz];
58315
58316      /* Copy the data from the source page into the destination page.
58317      ** Then clear the Btree layer MemPage.isInit flag. Both this module
58318      ** and the pager code use this trick (clearing the first byte
58319      ** of the page 'extra' space to invalidate the Btree layers
58320      ** cached parse of the page). MemPage.isInit is marked
58321      ** "MUST BE FIRST" for this purpose.
58322      */
58323      memcpy(zOut, zIn, nCopy);
58324      ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
58325      if( iOff==0 && bUpdate==0 ){
58326        sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
58327      }
58328    }
58329    sqlite3PagerUnref(pDestPg);
58330  }
58331
58332  return rc;
58333}
58334
58335/*
58336** If pFile is currently larger than iSize bytes, then truncate it to
58337** exactly iSize bytes. If pFile is not larger than iSize bytes, then
58338** this function is a no-op.
58339**
58340** Return SQLITE_OK if everything is successful, or an SQLite error
58341** code if an error occurs.
58342*/
58343static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
58344  i64 iCurrent;
58345  int rc = sqlite3OsFileSize(pFile, &iCurrent);
58346  if( rc==SQLITE_OK && iCurrent>iSize ){
58347    rc = sqlite3OsTruncate(pFile, iSize);
58348  }
58349  return rc;
58350}
58351
58352/*
58353** Register this backup object with the associated source pager for
58354** callbacks when pages are changed or the cache invalidated.
58355*/
58356static void attachBackupObject(sqlite3_backup *p){
58357  sqlite3_backup **pp;
58358  assert( sqlite3BtreeHoldsMutex(p->pSrc) );
58359  pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
58360  p->pNext = *pp;
58361  *pp = p;
58362  p->isAttached = 1;
58363}
58364
58365/*
58366** Copy nPage pages from the source b-tree to the destination.
58367*/
58368SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
58369  int rc;
58370  int destMode;       /* Destination journal mode */
58371  int pgszSrc = 0;    /* Source page size */
58372  int pgszDest = 0;   /* Destination page size */
58373
58374  sqlite3_mutex_enter(p->pSrcDb->mutex);
58375  sqlite3BtreeEnter(p->pSrc);
58376  if( p->pDestDb ){
58377    sqlite3_mutex_enter(p->pDestDb->mutex);
58378  }
58379
58380  rc = p->rc;
58381  if( !isFatalError(rc) ){
58382    Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */
58383    Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */
58384    int ii;                            /* Iterator variable */
58385    int nSrcPage = -1;                 /* Size of source db in pages */
58386    int bCloseTrans = 0;               /* True if src db requires unlocking */
58387
58388    /* If the source pager is currently in a write-transaction, return
58389    ** SQLITE_BUSY immediately.
58390    */
58391    if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
58392      rc = SQLITE_BUSY;
58393    }else{
58394      rc = SQLITE_OK;
58395    }
58396
58397    /* Lock the destination database, if it is not locked already. */
58398    if( SQLITE_OK==rc && p->bDestLocked==0
58399     && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
58400    ){
58401      p->bDestLocked = 1;
58402      sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
58403    }
58404
58405    /* If there is no open read-transaction on the source database, open
58406    ** one now. If a transaction is opened here, then it will be closed
58407    ** before this function exits.
58408    */
58409    if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
58410      rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
58411      bCloseTrans = 1;
58412    }
58413
58414    /* Do not allow backup if the destination database is in WAL mode
58415    ** and the page sizes are different between source and destination */
58416    pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
58417    pgszDest = sqlite3BtreeGetPageSize(p->pDest);
58418    destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
58419    if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
58420      rc = SQLITE_READONLY;
58421    }
58422
58423    /* Now that there is a read-lock on the source database, query the
58424    ** source pager for the number of pages in the database.
58425    */
58426    nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
58427    assert( nSrcPage>=0 );
58428    for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
58429      const Pgno iSrcPg = p->iNext;                 /* Source page number */
58430      if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
58431        DbPage *pSrcPg;                             /* Source page object */
58432        rc = sqlite3PagerAcquire(pSrcPager, iSrcPg, &pSrcPg,
58433                                 PAGER_ACQUIRE_READONLY);
58434        if( rc==SQLITE_OK ){
58435          rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
58436          sqlite3PagerUnref(pSrcPg);
58437        }
58438      }
58439      p->iNext++;
58440    }
58441    if( rc==SQLITE_OK ){
58442      p->nPagecount = nSrcPage;
58443      p->nRemaining = nSrcPage+1-p->iNext;
58444      if( p->iNext>(Pgno)nSrcPage ){
58445        rc = SQLITE_DONE;
58446      }else if( !p->isAttached ){
58447        attachBackupObject(p);
58448      }
58449    }
58450
58451    /* Update the schema version field in the destination database. This
58452    ** is to make sure that the schema-version really does change in
58453    ** the case where the source and destination databases have the
58454    ** same schema version.
58455    */
58456    if( rc==SQLITE_DONE ){
58457      if( nSrcPage==0 ){
58458        rc = sqlite3BtreeNewDb(p->pDest);
58459        nSrcPage = 1;
58460      }
58461      if( rc==SQLITE_OK || rc==SQLITE_DONE ){
58462        rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
58463      }
58464      if( rc==SQLITE_OK ){
58465        if( p->pDestDb ){
58466          sqlite3ResetAllSchemasOfConnection(p->pDestDb);
58467        }
58468        if( destMode==PAGER_JOURNALMODE_WAL ){
58469          rc = sqlite3BtreeSetVersion(p->pDest, 2);
58470        }
58471      }
58472      if( rc==SQLITE_OK ){
58473        int nDestTruncate;
58474        /* Set nDestTruncate to the final number of pages in the destination
58475        ** database. The complication here is that the destination page
58476        ** size may be different to the source page size.
58477        **
58478        ** If the source page size is smaller than the destination page size,
58479        ** round up. In this case the call to sqlite3OsTruncate() below will
58480        ** fix the size of the file. However it is important to call
58481        ** sqlite3PagerTruncateImage() here so that any pages in the
58482        ** destination file that lie beyond the nDestTruncate page mark are
58483        ** journalled by PagerCommitPhaseOne() before they are destroyed
58484        ** by the file truncation.
58485        */
58486        assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
58487        assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
58488        if( pgszSrc<pgszDest ){
58489          int ratio = pgszDest/pgszSrc;
58490          nDestTruncate = (nSrcPage+ratio-1)/ratio;
58491          if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
58492            nDestTruncate--;
58493          }
58494        }else{
58495          nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
58496        }
58497        assert( nDestTruncate>0 );
58498
58499        if( pgszSrc<pgszDest ){
58500          /* If the source page-size is smaller than the destination page-size,
58501          ** two extra things may need to happen:
58502          **
58503          **   * The destination may need to be truncated, and
58504          **
58505          **   * Data stored on the pages immediately following the
58506          **     pending-byte page in the source database may need to be
58507          **     copied into the destination database.
58508          */
58509          const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
58510          sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
58511          Pgno iPg;
58512          int nDstPage;
58513          i64 iOff;
58514          i64 iEnd;
58515
58516          assert( pFile );
58517          assert( nDestTruncate==0
58518              || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
58519                nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
58520             && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
58521          ));
58522
58523          /* This block ensures that all data required to recreate the original
58524          ** database has been stored in the journal for pDestPager and the
58525          ** journal synced to disk. So at this point we may safely modify
58526          ** the database file in any way, knowing that if a power failure
58527          ** occurs, the original database will be reconstructed from the
58528          ** journal file.  */
58529          sqlite3PagerPagecount(pDestPager, &nDstPage);
58530          for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
58531            if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
58532              DbPage *pPg;
58533              rc = sqlite3PagerGet(pDestPager, iPg, &pPg);
58534              if( rc==SQLITE_OK ){
58535                rc = sqlite3PagerWrite(pPg);
58536                sqlite3PagerUnref(pPg);
58537              }
58538            }
58539          }
58540          if( rc==SQLITE_OK ){
58541            rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
58542          }
58543
58544          /* Write the extra pages and truncate the database file as required */
58545          iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
58546          for(
58547            iOff=PENDING_BYTE+pgszSrc;
58548            rc==SQLITE_OK && iOff<iEnd;
58549            iOff+=pgszSrc
58550          ){
58551            PgHdr *pSrcPg = 0;
58552            const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
58553            rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
58554            if( rc==SQLITE_OK ){
58555              u8 *zData = sqlite3PagerGetData(pSrcPg);
58556              rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
58557            }
58558            sqlite3PagerUnref(pSrcPg);
58559          }
58560          if( rc==SQLITE_OK ){
58561            rc = backupTruncateFile(pFile, iSize);
58562          }
58563
58564          /* Sync the database file to disk. */
58565          if( rc==SQLITE_OK ){
58566            rc = sqlite3PagerSync(pDestPager);
58567          }
58568        }else{
58569          sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
58570          rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
58571        }
58572
58573        /* Finish committing the transaction to the destination database. */
58574        if( SQLITE_OK==rc
58575         && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
58576        ){
58577          rc = SQLITE_DONE;
58578        }
58579      }
58580    }
58581
58582    /* If bCloseTrans is true, then this function opened a read transaction
58583    ** on the source database. Close the read transaction here. There is
58584    ** no need to check the return values of the btree methods here, as
58585    ** "committing" a read-only transaction cannot fail.
58586    */
58587    if( bCloseTrans ){
58588      TESTONLY( int rc2 );
58589      TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
58590      TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
58591      assert( rc2==SQLITE_OK );
58592    }
58593
58594    if( rc==SQLITE_IOERR_NOMEM ){
58595      rc = SQLITE_NOMEM;
58596    }
58597    p->rc = rc;
58598  }
58599  if( p->pDestDb ){
58600    sqlite3_mutex_leave(p->pDestDb->mutex);
58601  }
58602  sqlite3BtreeLeave(p->pSrc);
58603  sqlite3_mutex_leave(p->pSrcDb->mutex);
58604  return rc;
58605}
58606
58607/*
58608** Release all resources associated with an sqlite3_backup* handle.
58609*/
58610SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
58611  sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */
58612  sqlite3 *pSrcDb;                     /* Source database connection */
58613  int rc;                              /* Value to return */
58614
58615  /* Enter the mutexes */
58616  if( p==0 ) return SQLITE_OK;
58617  pSrcDb = p->pSrcDb;
58618  sqlite3_mutex_enter(pSrcDb->mutex);
58619  sqlite3BtreeEnter(p->pSrc);
58620  if( p->pDestDb ){
58621    sqlite3_mutex_enter(p->pDestDb->mutex);
58622  }
58623
58624  /* Detach this backup from the source pager. */
58625  if( p->pDestDb ){
58626    p->pSrc->nBackup--;
58627  }
58628  if( p->isAttached ){
58629    pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
58630    while( *pp!=p ){
58631      pp = &(*pp)->pNext;
58632    }
58633    *pp = p->pNext;
58634  }
58635
58636  /* If a transaction is still open on the Btree, roll it back. */
58637  sqlite3BtreeRollback(p->pDest, SQLITE_OK);
58638
58639  /* Set the error code of the destination database handle. */
58640  rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
58641  sqlite3Error(p->pDestDb, rc, 0);
58642
58643  /* Exit the mutexes and free the backup context structure. */
58644  if( p->pDestDb ){
58645    sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
58646  }
58647  sqlite3BtreeLeave(p->pSrc);
58648  if( p->pDestDb ){
58649    /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
58650    ** call to sqlite3_backup_init() and is destroyed by a call to
58651    ** sqlite3_backup_finish(). */
58652    sqlite3_free(p);
58653  }
58654  sqlite3LeaveMutexAndCloseZombie(pSrcDb);
58655  return rc;
58656}
58657
58658/*
58659** Return the number of pages still to be backed up as of the most recent
58660** call to sqlite3_backup_step().
58661*/
58662SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
58663  return p->nRemaining;
58664}
58665
58666/*
58667** Return the total number of pages in the source database as of the most
58668** recent call to sqlite3_backup_step().
58669*/
58670SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
58671  return p->nPagecount;
58672}
58673
58674/*
58675** This function is called after the contents of page iPage of the
58676** source database have been modified. If page iPage has already been
58677** copied into the destination database, then the data written to the
58678** destination is now invalidated. The destination copy of iPage needs
58679** to be updated with the new data before the backup operation is
58680** complete.
58681**
58682** It is assumed that the mutex associated with the BtShared object
58683** corresponding to the source database is held when this function is
58684** called.
58685*/
58686SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
58687  sqlite3_backup *p;                   /* Iterator variable */
58688  for(p=pBackup; p; p=p->pNext){
58689    assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
58690    if( !isFatalError(p->rc) && iPage<p->iNext ){
58691      /* The backup process p has already copied page iPage. But now it
58692      ** has been modified by a transaction on the source pager. Copy
58693      ** the new data into the backup.
58694      */
58695      int rc;
58696      assert( p->pDestDb );
58697      sqlite3_mutex_enter(p->pDestDb->mutex);
58698      rc = backupOnePage(p, iPage, aData, 1);
58699      sqlite3_mutex_leave(p->pDestDb->mutex);
58700      assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
58701      if( rc!=SQLITE_OK ){
58702        p->rc = rc;
58703      }
58704    }
58705  }
58706}
58707
58708/*
58709** Restart the backup process. This is called when the pager layer
58710** detects that the database has been modified by an external database
58711** connection. In this case there is no way of knowing which of the
58712** pages that have been copied into the destination database are still
58713** valid and which are not, so the entire process needs to be restarted.
58714**
58715** It is assumed that the mutex associated with the BtShared object
58716** corresponding to the source database is held when this function is
58717** called.
58718*/
58719SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
58720  sqlite3_backup *p;                   /* Iterator variable */
58721  for(p=pBackup; p; p=p->pNext){
58722    assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
58723    p->iNext = 1;
58724  }
58725}
58726
58727#ifndef SQLITE_OMIT_VACUUM
58728/*
58729** Copy the complete content of pBtFrom into pBtTo.  A transaction
58730** must be active for both files.
58731**
58732** The size of file pTo may be reduced by this operation. If anything
58733** goes wrong, the transaction on pTo is rolled back. If successful, the
58734** transaction is committed before returning.
58735*/
58736SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
58737  int rc;
58738  sqlite3_file *pFd;              /* File descriptor for database pTo */
58739  sqlite3_backup b;
58740  sqlite3BtreeEnter(pTo);
58741  sqlite3BtreeEnter(pFrom);
58742
58743  assert( sqlite3BtreeIsInTrans(pTo) );
58744  pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
58745  if( pFd->pMethods ){
58746    i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
58747    rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
58748    if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
58749    if( rc ) goto copy_finished;
58750  }
58751
58752  /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
58753  ** to 0. This is used by the implementations of sqlite3_backup_step()
58754  ** and sqlite3_backup_finish() to detect that they are being called
58755  ** from this function, not directly by the user.
58756  */
58757  memset(&b, 0, sizeof(b));
58758  b.pSrcDb = pFrom->db;
58759  b.pSrc = pFrom;
58760  b.pDest = pTo;
58761  b.iNext = 1;
58762
58763  /* 0x7FFFFFFF is the hard limit for the number of pages in a database
58764  ** file. By passing this as the number of pages to copy to
58765  ** sqlite3_backup_step(), we can guarantee that the copy finishes
58766  ** within a single call (unless an error occurs). The assert() statement
58767  ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
58768  ** or an error code.
58769  */
58770  sqlite3_backup_step(&b, 0x7FFFFFFF);
58771  assert( b.rc!=SQLITE_OK );
58772  rc = sqlite3_backup_finish(&b);
58773  if( rc==SQLITE_OK ){
58774    pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
58775  }else{
58776    sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
58777  }
58778
58779  assert( sqlite3BtreeIsInTrans(pTo)==0 );
58780copy_finished:
58781  sqlite3BtreeLeave(pFrom);
58782  sqlite3BtreeLeave(pTo);
58783  return rc;
58784}
58785#endif /* SQLITE_OMIT_VACUUM */
58786
58787/************** End of backup.c **********************************************/
58788/************** Begin file vdbemem.c *****************************************/
58789/*
58790** 2004 May 26
58791**
58792** The author disclaims copyright to this source code.  In place of
58793** a legal notice, here is a blessing:
58794**
58795**    May you do good and not evil.
58796**    May you find forgiveness for yourself and forgive others.
58797**    May you share freely, never taking more than you give.
58798**
58799*************************************************************************
58800**
58801** This file contains code use to manipulate "Mem" structure.  A "Mem"
58802** stores a single value in the VDBE.  Mem is an opaque structure visible
58803** only within the VDBE.  Interface routines refer to a Mem using the
58804** name sqlite_value
58805*/
58806
58807/*
58808** If pMem is an object with a valid string representation, this routine
58809** ensures the internal encoding for the string representation is
58810** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
58811**
58812** If pMem is not a string object, or the encoding of the string
58813** representation is already stored using the requested encoding, then this
58814** routine is a no-op.
58815**
58816** SQLITE_OK is returned if the conversion is successful (or not required).
58817** SQLITE_NOMEM may be returned if a malloc() fails during conversion
58818** between formats.
58819*/
58820SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
58821#ifndef SQLITE_OMIT_UTF16
58822  int rc;
58823#endif
58824  assert( (pMem->flags&MEM_RowSet)==0 );
58825  assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
58826           || desiredEnc==SQLITE_UTF16BE );
58827  if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
58828    return SQLITE_OK;
58829  }
58830  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
58831#ifdef SQLITE_OMIT_UTF16
58832  return SQLITE_ERROR;
58833#else
58834
58835  /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
58836  ** then the encoding of the value may not have changed.
58837  */
58838  rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
58839  assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
58840  assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
58841  assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
58842  return rc;
58843#endif
58844}
58845
58846/*
58847** Make sure pMem->z points to a writable allocation of at least
58848** n bytes.
58849**
58850** If the third argument passed to this function is true, then memory
58851** cell pMem must contain a string or blob. In this case the content is
58852** preserved. Otherwise, if the third parameter to this function is false,
58853** any current string or blob value may be discarded.
58854**
58855** This function sets the MEM_Dyn flag and clears any xDel callback.
58856** It also clears MEM_Ephem and MEM_Static. If the preserve flag is
58857** not set, Mem.n is zeroed.
58858*/
58859SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
58860  assert( 1 >=
58861    ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
58862    (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) +
58863    ((pMem->flags&MEM_Ephem) ? 1 : 0) +
58864    ((pMem->flags&MEM_Static) ? 1 : 0)
58865  );
58866  assert( (pMem->flags&MEM_RowSet)==0 );
58867
58868  /* If the preserve flag is set to true, then the memory cell must already
58869  ** contain a valid string or blob value.  */
58870  assert( preserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
58871
58872  if( n<32 ) n = 32;
58873  if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
58874    if( preserve && pMem->z==pMem->zMalloc ){
58875      pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
58876      preserve = 0;
58877    }else{
58878      sqlite3DbFree(pMem->db, pMem->zMalloc);
58879      pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
58880    }
58881  }
58882
58883  if( pMem->z && preserve && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
58884    memcpy(pMem->zMalloc, pMem->z, pMem->n);
58885  }
58886  if( pMem->flags&MEM_Dyn && pMem->xDel ){
58887    assert( pMem->xDel!=SQLITE_DYNAMIC );
58888    pMem->xDel((void *)(pMem->z));
58889  }
58890
58891  pMem->z = pMem->zMalloc;
58892  if( pMem->z==0 ){
58893    pMem->flags = MEM_Null;
58894  }else{
58895    pMem->flags &= ~(MEM_Ephem|MEM_Static);
58896  }
58897  pMem->xDel = 0;
58898  return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);
58899}
58900
58901/*
58902** Make the given Mem object MEM_Dyn.  In other words, make it so
58903** that any TEXT or BLOB content is stored in memory obtained from
58904** malloc().  In this way, we know that the memory is safe to be
58905** overwritten or altered.
58906**
58907** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
58908*/
58909SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
58910  int f;
58911  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
58912  assert( (pMem->flags&MEM_RowSet)==0 );
58913  ExpandBlob(pMem);
58914  f = pMem->flags;
58915  if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
58916    if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
58917      return SQLITE_NOMEM;
58918    }
58919    pMem->z[pMem->n] = 0;
58920    pMem->z[pMem->n+1] = 0;
58921    pMem->flags |= MEM_Term;
58922#ifdef SQLITE_DEBUG
58923    pMem->pScopyFrom = 0;
58924#endif
58925  }
58926
58927  return SQLITE_OK;
58928}
58929
58930/*
58931** If the given Mem* has a zero-filled tail, turn it into an ordinary
58932** blob stored in dynamically allocated space.
58933*/
58934#ifndef SQLITE_OMIT_INCRBLOB
58935SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
58936  if( pMem->flags & MEM_Zero ){
58937    int nByte;
58938    assert( pMem->flags&MEM_Blob );
58939    assert( (pMem->flags&MEM_RowSet)==0 );
58940    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
58941
58942    /* Set nByte to the number of bytes required to store the expanded blob. */
58943    nByte = pMem->n + pMem->u.nZero;
58944    if( nByte<=0 ){
58945      nByte = 1;
58946    }
58947    if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
58948      return SQLITE_NOMEM;
58949    }
58950
58951    memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
58952    pMem->n += pMem->u.nZero;
58953    pMem->flags &= ~(MEM_Zero|MEM_Term);
58954  }
58955  return SQLITE_OK;
58956}
58957#endif
58958
58959
58960/*
58961** Make sure the given Mem is \u0000 terminated.
58962*/
58963SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
58964  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
58965  if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
58966    return SQLITE_OK;   /* Nothing to do */
58967  }
58968  if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
58969    return SQLITE_NOMEM;
58970  }
58971  pMem->z[pMem->n] = 0;
58972  pMem->z[pMem->n+1] = 0;
58973  pMem->flags |= MEM_Term;
58974  return SQLITE_OK;
58975}
58976
58977/*
58978** Add MEM_Str to the set of representations for the given Mem.  Numbers
58979** are converted using sqlite3_snprintf().  Converting a BLOB to a string
58980** is a no-op.
58981**
58982** Existing representations MEM_Int and MEM_Real are *not* invalidated.
58983**
58984** A MEM_Null value will never be passed to this function. This function is
58985** used for converting values to text for returning to the user (i.e. via
58986** sqlite3_value_text()), or for ensuring that values to be used as btree
58987** keys are strings. In the former case a NULL pointer is returned the
58988** user and the later is an internal programming error.
58989*/
58990SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
58991  int rc = SQLITE_OK;
58992  int fg = pMem->flags;
58993  const int nByte = 32;
58994
58995  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
58996  assert( !(fg&MEM_Zero) );
58997  assert( !(fg&(MEM_Str|MEM_Blob)) );
58998  assert( fg&(MEM_Int|MEM_Real) );
58999  assert( (pMem->flags&MEM_RowSet)==0 );
59000  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
59001
59002
59003  if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
59004    return SQLITE_NOMEM;
59005  }
59006
59007  /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
59008  ** string representation of the value. Then, if the required encoding
59009  ** is UTF-16le or UTF-16be do a translation.
59010  **
59011  ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
59012  */
59013  if( fg & MEM_Int ){
59014    sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
59015  }else{
59016    assert( fg & MEM_Real );
59017    sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
59018  }
59019  pMem->n = sqlite3Strlen30(pMem->z);
59020  pMem->enc = SQLITE_UTF8;
59021  pMem->flags |= MEM_Str|MEM_Term;
59022  sqlite3VdbeChangeEncoding(pMem, enc);
59023  return rc;
59024}
59025
59026/*
59027** Memory cell pMem contains the context of an aggregate function.
59028** This routine calls the finalize method for that function.  The
59029** result of the aggregate is stored back into pMem.
59030**
59031** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
59032** otherwise.
59033*/
59034SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
59035  int rc = SQLITE_OK;
59036  if( ALWAYS(pFunc && pFunc->xFinalize) ){
59037    sqlite3_context ctx;
59038    assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
59039    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59040    memset(&ctx, 0, sizeof(ctx));
59041    ctx.s.flags = MEM_Null;
59042    ctx.s.db = pMem->db;
59043    ctx.pMem = pMem;
59044    ctx.pFunc = pFunc;
59045    pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
59046    assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
59047    sqlite3DbFree(pMem->db, pMem->zMalloc);
59048    memcpy(pMem, &ctx.s, sizeof(ctx.s));
59049    rc = ctx.isError;
59050  }
59051  return rc;
59052}
59053
59054/*
59055** If the memory cell contains a string value that must be freed by
59056** invoking an external callback, free it now. Calling this function
59057** does not free any Mem.zMalloc buffer.
59058*/
59059SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
59060  assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
59061  if( p->flags&MEM_Agg ){
59062    sqlite3VdbeMemFinalize(p, p->u.pDef);
59063    assert( (p->flags & MEM_Agg)==0 );
59064    sqlite3VdbeMemRelease(p);
59065  }else if( p->flags&MEM_Dyn && p->xDel ){
59066    assert( (p->flags&MEM_RowSet)==0 );
59067    assert( p->xDel!=SQLITE_DYNAMIC );
59068    p->xDel((void *)p->z);
59069    p->xDel = 0;
59070  }else if( p->flags&MEM_RowSet ){
59071    sqlite3RowSetClear(p->u.pRowSet);
59072  }else if( p->flags&MEM_Frame ){
59073    sqlite3VdbeMemSetNull(p);
59074  }
59075}
59076
59077/*
59078** Release any memory held by the Mem. This may leave the Mem in an
59079** inconsistent state, for example with (Mem.z==0) and
59080** (Mem.type==SQLITE_TEXT).
59081*/
59082SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
59083  VdbeMemRelease(p);
59084  sqlite3DbFree(p->db, p->zMalloc);
59085  p->z = 0;
59086  p->zMalloc = 0;
59087  p->xDel = 0;
59088}
59089
59090/*
59091** Convert a 64-bit IEEE double into a 64-bit signed integer.
59092** If the double is too large, return 0x8000000000000000.
59093**
59094** Most systems appear to do this simply by assigning
59095** variables and without the extra range tests.  But
59096** there are reports that windows throws an expection
59097** if the floating point value is out of range. (See ticket #2880.)
59098** Because we do not completely understand the problem, we will
59099** take the conservative approach and always do range tests
59100** before attempting the conversion.
59101*/
59102static i64 doubleToInt64(double r){
59103#ifdef SQLITE_OMIT_FLOATING_POINT
59104  /* When floating-point is omitted, double and int64 are the same thing */
59105  return r;
59106#else
59107  /*
59108  ** Many compilers we encounter do not define constants for the
59109  ** minimum and maximum 64-bit integers, or they define them
59110  ** inconsistently.  And many do not understand the "LL" notation.
59111  ** So we define our own static constants here using nothing
59112  ** larger than a 32-bit integer constant.
59113  */
59114  static const i64 maxInt = LARGEST_INT64;
59115  static const i64 minInt = SMALLEST_INT64;
59116
59117  if( r<(double)minInt ){
59118    return minInt;
59119  }else if( r>(double)maxInt ){
59120    /* minInt is correct here - not maxInt.  It turns out that assigning
59121    ** a very large positive number to an integer results in a very large
59122    ** negative integer.  This makes no sense, but it is what x86 hardware
59123    ** does so for compatibility we will do the same in software. */
59124    return minInt;
59125  }else{
59126    return (i64)r;
59127  }
59128#endif
59129}
59130
59131/*
59132** Return some kind of integer value which is the best we can do
59133** at representing the value that *pMem describes as an integer.
59134** If pMem is an integer, then the value is exact.  If pMem is
59135** a floating-point then the value returned is the integer part.
59136** If pMem is a string or blob, then we make an attempt to convert
59137** it into a integer and return that.  If pMem represents an
59138** an SQL-NULL value, return 0.
59139**
59140** If pMem represents a string value, its encoding might be changed.
59141*/
59142SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
59143  int flags;
59144  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59145  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
59146  flags = pMem->flags;
59147  if( flags & MEM_Int ){
59148    return pMem->u.i;
59149  }else if( flags & MEM_Real ){
59150    return doubleToInt64(pMem->r);
59151  }else if( flags & (MEM_Str|MEM_Blob) ){
59152    i64 value = 0;
59153    assert( pMem->z || pMem->n==0 );
59154    testcase( pMem->z==0 );
59155    sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
59156    return value;
59157  }else{
59158    return 0;
59159  }
59160}
59161
59162/*
59163** Return the best representation of pMem that we can get into a
59164** double.  If pMem is already a double or an integer, return its
59165** value.  If it is a string or blob, try to convert it to a double.
59166** If it is a NULL, return 0.0.
59167*/
59168SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
59169  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59170  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
59171  if( pMem->flags & MEM_Real ){
59172    return pMem->r;
59173  }else if( pMem->flags & MEM_Int ){
59174    return (double)pMem->u.i;
59175  }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
59176    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
59177    double val = (double)0;
59178    sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
59179    return val;
59180  }else{
59181    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
59182    return (double)0;
59183  }
59184}
59185
59186/*
59187** The MEM structure is already a MEM_Real.  Try to also make it a
59188** MEM_Int if we can.
59189*/
59190SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
59191  assert( pMem->flags & MEM_Real );
59192  assert( (pMem->flags & MEM_RowSet)==0 );
59193  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59194  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
59195
59196  pMem->u.i = doubleToInt64(pMem->r);
59197
59198  /* Only mark the value as an integer if
59199  **
59200  **    (1) the round-trip conversion real->int->real is a no-op, and
59201  **    (2) The integer is neither the largest nor the smallest
59202  **        possible integer (ticket #3922)
59203  **
59204  ** The second and third terms in the following conditional enforces
59205  ** the second condition under the assumption that addition overflow causes
59206  ** values to wrap around.  On x86 hardware, the third term is always
59207  ** true and could be omitted.  But we leave it in because other
59208  ** architectures might behave differently.
59209  */
59210  if( pMem->r==(double)pMem->u.i
59211   && pMem->u.i>SMALLEST_INT64
59212#if defined(__i486__) || defined(__x86_64__)
59213   && ALWAYS(pMem->u.i<LARGEST_INT64)
59214#else
59215   && pMem->u.i<LARGEST_INT64
59216#endif
59217  ){
59218    pMem->flags |= MEM_Int;
59219  }
59220}
59221
59222/*
59223** Convert pMem to type integer.  Invalidate any prior representations.
59224*/
59225SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
59226  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59227  assert( (pMem->flags & MEM_RowSet)==0 );
59228  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
59229
59230  pMem->u.i = sqlite3VdbeIntValue(pMem);
59231  MemSetTypeFlag(pMem, MEM_Int);
59232  return SQLITE_OK;
59233}
59234
59235/*
59236** Convert pMem so that it is of type MEM_Real.
59237** Invalidate any prior representations.
59238*/
59239SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
59240  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59241  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
59242
59243  pMem->r = sqlite3VdbeRealValue(pMem);
59244  MemSetTypeFlag(pMem, MEM_Real);
59245  return SQLITE_OK;
59246}
59247
59248/*
59249** Convert pMem so that it has types MEM_Real or MEM_Int or both.
59250** Invalidate any prior representations.
59251**
59252** Every effort is made to force the conversion, even if the input
59253** is a string that does not look completely like a number.  Convert
59254** as much of the string as we can and ignore the rest.
59255*/
59256SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
59257  if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
59258    assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
59259    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59260    if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
59261      MemSetTypeFlag(pMem, MEM_Int);
59262    }else{
59263      pMem->r = sqlite3VdbeRealValue(pMem);
59264      MemSetTypeFlag(pMem, MEM_Real);
59265      sqlite3VdbeIntegerAffinity(pMem);
59266    }
59267  }
59268  assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
59269  pMem->flags &= ~(MEM_Str|MEM_Blob);
59270  return SQLITE_OK;
59271}
59272
59273/*
59274** Delete any previous value and set the value stored in *pMem to NULL.
59275*/
59276SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
59277  if( pMem->flags & MEM_Frame ){
59278    VdbeFrame *pFrame = pMem->u.pFrame;
59279    pFrame->pParent = pFrame->v->pDelFrame;
59280    pFrame->v->pDelFrame = pFrame;
59281  }
59282  if( pMem->flags & MEM_RowSet ){
59283    sqlite3RowSetClear(pMem->u.pRowSet);
59284  }
59285  MemSetTypeFlag(pMem, MEM_Null);
59286  pMem->type = SQLITE_NULL;
59287}
59288
59289/*
59290** Delete any previous value and set the value to be a BLOB of length
59291** n containing all zeros.
59292*/
59293SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
59294  sqlite3VdbeMemRelease(pMem);
59295  pMem->flags = MEM_Blob|MEM_Zero;
59296  pMem->type = SQLITE_BLOB;
59297  pMem->n = 0;
59298  if( n<0 ) n = 0;
59299  pMem->u.nZero = n;
59300  pMem->enc = SQLITE_UTF8;
59301
59302#ifdef SQLITE_OMIT_INCRBLOB
59303  sqlite3VdbeMemGrow(pMem, n, 0);
59304  if( pMem->z ){
59305    pMem->n = n;
59306    memset(pMem->z, 0, n);
59307  }
59308#endif
59309}
59310
59311/*
59312** Delete any previous value and set the value stored in *pMem to val,
59313** manifest type INTEGER.
59314*/
59315SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
59316  sqlite3VdbeMemRelease(pMem);
59317  pMem->u.i = val;
59318  pMem->flags = MEM_Int;
59319  pMem->type = SQLITE_INTEGER;
59320}
59321
59322#ifndef SQLITE_OMIT_FLOATING_POINT
59323/*
59324** Delete any previous value and set the value stored in *pMem to val,
59325** manifest type REAL.
59326*/
59327SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
59328  if( sqlite3IsNaN(val) ){
59329    sqlite3VdbeMemSetNull(pMem);
59330  }else{
59331    sqlite3VdbeMemRelease(pMem);
59332    pMem->r = val;
59333    pMem->flags = MEM_Real;
59334    pMem->type = SQLITE_FLOAT;
59335  }
59336}
59337#endif
59338
59339/*
59340** Delete any previous value and set the value of pMem to be an
59341** empty boolean index.
59342*/
59343SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
59344  sqlite3 *db = pMem->db;
59345  assert( db!=0 );
59346  assert( (pMem->flags & MEM_RowSet)==0 );
59347  sqlite3VdbeMemRelease(pMem);
59348  pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
59349  if( db->mallocFailed ){
59350    pMem->flags = MEM_Null;
59351  }else{
59352    assert( pMem->zMalloc );
59353    pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc,
59354                                       sqlite3DbMallocSize(db, pMem->zMalloc));
59355    assert( pMem->u.pRowSet!=0 );
59356    pMem->flags = MEM_RowSet;
59357  }
59358}
59359
59360/*
59361** Return true if the Mem object contains a TEXT or BLOB that is
59362** too large - whose size exceeds SQLITE_MAX_LENGTH.
59363*/
59364SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
59365  assert( p->db!=0 );
59366  if( p->flags & (MEM_Str|MEM_Blob) ){
59367    int n = p->n;
59368    if( p->flags & MEM_Zero ){
59369      n += p->u.nZero;
59370    }
59371    return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
59372  }
59373  return 0;
59374}
59375
59376#ifdef SQLITE_DEBUG
59377/*
59378** This routine prepares a memory cell for modication by breaking
59379** its link to a shallow copy and by marking any current shallow
59380** copies of this cell as invalid.
59381**
59382** This is used for testing and debugging only - to make sure shallow
59383** copies are not misused.
59384*/
59385SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
59386  int i;
59387  Mem *pX;
59388  for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
59389    if( pX->pScopyFrom==pMem ){
59390      pX->flags |= MEM_Invalid;
59391      pX->pScopyFrom = 0;
59392    }
59393  }
59394  pMem->pScopyFrom = 0;
59395}
59396#endif /* SQLITE_DEBUG */
59397
59398/*
59399** Size of struct Mem not including the Mem.zMalloc member.
59400*/
59401#define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
59402
59403/*
59404** Make an shallow copy of pFrom into pTo.  Prior contents of
59405** pTo are freed.  The pFrom->z field is not duplicated.  If
59406** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
59407** and flags gets srcType (either MEM_Ephem or MEM_Static).
59408*/
59409SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
59410  assert( (pFrom->flags & MEM_RowSet)==0 );
59411  VdbeMemRelease(pTo);
59412  memcpy(pTo, pFrom, MEMCELLSIZE);
59413  pTo->xDel = 0;
59414  if( (pFrom->flags&MEM_Static)==0 ){
59415    pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
59416    assert( srcType==MEM_Ephem || srcType==MEM_Static );
59417    pTo->flags |= srcType;
59418  }
59419}
59420
59421/*
59422** Make a full copy of pFrom into pTo.  Prior contents of pTo are
59423** freed before the copy is made.
59424*/
59425SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
59426  int rc = SQLITE_OK;
59427
59428  assert( (pFrom->flags & MEM_RowSet)==0 );
59429  VdbeMemRelease(pTo);
59430  memcpy(pTo, pFrom, MEMCELLSIZE);
59431  pTo->flags &= ~MEM_Dyn;
59432
59433  if( pTo->flags&(MEM_Str|MEM_Blob) ){
59434    if( 0==(pFrom->flags&MEM_Static) ){
59435      pTo->flags |= MEM_Ephem;
59436      rc = sqlite3VdbeMemMakeWriteable(pTo);
59437    }
59438  }
59439
59440  return rc;
59441}
59442
59443/*
59444** Transfer the contents of pFrom to pTo. Any existing value in pTo is
59445** freed. If pFrom contains ephemeral data, a copy is made.
59446**
59447** pFrom contains an SQL NULL when this routine returns.
59448*/
59449SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
59450  assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
59451  assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
59452  assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
59453
59454  sqlite3VdbeMemRelease(pTo);
59455  memcpy(pTo, pFrom, sizeof(Mem));
59456  pFrom->flags = MEM_Null;
59457  pFrom->xDel = 0;
59458  pFrom->zMalloc = 0;
59459}
59460
59461/*
59462** Change the value of a Mem to be a string or a BLOB.
59463**
59464** The memory management strategy depends on the value of the xDel
59465** parameter. If the value passed is SQLITE_TRANSIENT, then the
59466** string is copied into a (possibly existing) buffer managed by the
59467** Mem structure. Otherwise, any existing buffer is freed and the
59468** pointer copied.
59469**
59470** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
59471** size limit) then no memory allocation occurs.  If the string can be
59472** stored without allocating memory, then it is.  If a memory allocation
59473** is required to store the string, then value of pMem is unchanged.  In
59474** either case, SQLITE_TOOBIG is returned.
59475*/
59476SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
59477  Mem *pMem,          /* Memory cell to set to string value */
59478  const char *z,      /* String pointer */
59479  int n,              /* Bytes in string, or negative */
59480  u8 enc,             /* Encoding of z.  0 for BLOBs */
59481  void (*xDel)(void*) /* Destructor function */
59482){
59483  int nByte = n;      /* New value for pMem->n */
59484  int iLimit;         /* Maximum allowed string or blob size */
59485  u16 flags = 0;      /* New value for pMem->flags */
59486
59487  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59488  assert( (pMem->flags & MEM_RowSet)==0 );
59489
59490  /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
59491  if( !z ){
59492    sqlite3VdbeMemSetNull(pMem);
59493    return SQLITE_OK;
59494  }
59495
59496  if( pMem->db ){
59497    iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
59498  }else{
59499    iLimit = SQLITE_MAX_LENGTH;
59500  }
59501  flags = (enc==0?MEM_Blob:MEM_Str);
59502  if( nByte<0 ){
59503    assert( enc!=0 );
59504    if( enc==SQLITE_UTF8 ){
59505      for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
59506    }else{
59507      for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
59508    }
59509    flags |= MEM_Term;
59510  }
59511
59512  /* The following block sets the new values of Mem.z and Mem.xDel. It
59513  ** also sets a flag in local variable "flags" to indicate the memory
59514  ** management (one of MEM_Dyn or MEM_Static).
59515  */
59516  if( xDel==SQLITE_TRANSIENT ){
59517    int nAlloc = nByte;
59518    if( flags&MEM_Term ){
59519      nAlloc += (enc==SQLITE_UTF8?1:2);
59520    }
59521    if( nByte>iLimit ){
59522      return SQLITE_TOOBIG;
59523    }
59524    if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
59525      return SQLITE_NOMEM;
59526    }
59527    memcpy(pMem->z, z, nAlloc);
59528  }else if( xDel==SQLITE_DYNAMIC ){
59529    sqlite3VdbeMemRelease(pMem);
59530    pMem->zMalloc = pMem->z = (char *)z;
59531    pMem->xDel = 0;
59532  }else{
59533    sqlite3VdbeMemRelease(pMem);
59534    pMem->z = (char *)z;
59535    pMem->xDel = xDel;
59536    flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
59537  }
59538
59539  pMem->n = nByte;
59540  pMem->flags = flags;
59541  pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
59542  pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
59543
59544#ifndef SQLITE_OMIT_UTF16
59545  if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
59546    return SQLITE_NOMEM;
59547  }
59548#endif
59549
59550  if( nByte>iLimit ){
59551    return SQLITE_TOOBIG;
59552  }
59553
59554  return SQLITE_OK;
59555}
59556
59557/*
59558** Compare the values contained by the two memory cells, returning
59559** negative, zero or positive if pMem1 is less than, equal to, or greater
59560** than pMem2. Sorting order is NULL's first, followed by numbers (integers
59561** and reals) sorted numerically, followed by text ordered by the collating
59562** sequence pColl and finally blob's ordered by memcmp().
59563**
59564** Two NULL values are considered equal by this function.
59565*/
59566SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
59567  int rc;
59568  int f1, f2;
59569  int combined_flags;
59570
59571  f1 = pMem1->flags;
59572  f2 = pMem2->flags;
59573  combined_flags = f1|f2;
59574  assert( (combined_flags & MEM_RowSet)==0 );
59575
59576  /* If one value is NULL, it is less than the other. If both values
59577  ** are NULL, return 0.
59578  */
59579  if( combined_flags&MEM_Null ){
59580    return (f2&MEM_Null) - (f1&MEM_Null);
59581  }
59582
59583  /* If one value is a number and the other is not, the number is less.
59584  ** If both are numbers, compare as reals if one is a real, or as integers
59585  ** if both values are integers.
59586  */
59587  if( combined_flags&(MEM_Int|MEM_Real) ){
59588    if( !(f1&(MEM_Int|MEM_Real)) ){
59589      return 1;
59590    }
59591    if( !(f2&(MEM_Int|MEM_Real)) ){
59592      return -1;
59593    }
59594    if( (f1 & f2 & MEM_Int)==0 ){
59595      double r1, r2;
59596      if( (f1&MEM_Real)==0 ){
59597        r1 = (double)pMem1->u.i;
59598      }else{
59599        r1 = pMem1->r;
59600      }
59601      if( (f2&MEM_Real)==0 ){
59602        r2 = (double)pMem2->u.i;
59603      }else{
59604        r2 = pMem2->r;
59605      }
59606      if( r1<r2 ) return -1;
59607      if( r1>r2 ) return 1;
59608      return 0;
59609    }else{
59610      assert( f1&MEM_Int );
59611      assert( f2&MEM_Int );
59612      if( pMem1->u.i < pMem2->u.i ) return -1;
59613      if( pMem1->u.i > pMem2->u.i ) return 1;
59614      return 0;
59615    }
59616  }
59617
59618  /* If one value is a string and the other is a blob, the string is less.
59619  ** If both are strings, compare using the collating functions.
59620  */
59621  if( combined_flags&MEM_Str ){
59622    if( (f1 & MEM_Str)==0 ){
59623      return 1;
59624    }
59625    if( (f2 & MEM_Str)==0 ){
59626      return -1;
59627    }
59628
59629    assert( pMem1->enc==pMem2->enc );
59630    assert( pMem1->enc==SQLITE_UTF8 ||
59631            pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
59632
59633    /* The collation sequence must be defined at this point, even if
59634    ** the user deletes the collation sequence after the vdbe program is
59635    ** compiled (this was not always the case).
59636    */
59637    assert( !pColl || pColl->xCmp );
59638
59639    if( pColl ){
59640      if( pMem1->enc==pColl->enc ){
59641        /* The strings are already in the correct encoding.  Call the
59642        ** comparison function directly */
59643        return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
59644      }else{
59645        const void *v1, *v2;
59646        int n1, n2;
59647        Mem c1;
59648        Mem c2;
59649        memset(&c1, 0, sizeof(c1));
59650        memset(&c2, 0, sizeof(c2));
59651        sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
59652        sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
59653        v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
59654        n1 = v1==0 ? 0 : c1.n;
59655        v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
59656        n2 = v2==0 ? 0 : c2.n;
59657        rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
59658        sqlite3VdbeMemRelease(&c1);
59659        sqlite3VdbeMemRelease(&c2);
59660        return rc;
59661      }
59662    }
59663    /* If a NULL pointer was passed as the collate function, fall through
59664    ** to the blob case and use memcmp().  */
59665  }
59666
59667  /* Both values must be blobs.  Compare using memcmp().  */
59668  rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
59669  if( rc==0 ){
59670    rc = pMem1->n - pMem2->n;
59671  }
59672  return rc;
59673}
59674
59675/*
59676** Move data out of a btree key or data field and into a Mem structure.
59677** The data or key is taken from the entry that pCur is currently pointing
59678** to.  offset and amt determine what portion of the data or key to retrieve.
59679** key is true to get the key or false to get data.  The result is written
59680** into the pMem element.
59681**
59682** The pMem structure is assumed to be uninitialized.  Any prior content
59683** is overwritten without being freed.
59684**
59685** If this routine fails for any reason (malloc returns NULL or unable
59686** to read from the disk) then the pMem is left in an inconsistent state.
59687*/
59688SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
59689  BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
59690  int offset,       /* Offset from the start of data to return bytes from. */
59691  int amt,          /* Number of bytes to return. */
59692  int key,          /* If true, retrieve from the btree key, not data. */
59693  Mem *pMem         /* OUT: Return data in this Mem structure. */
59694){
59695  char *zData;        /* Data from the btree layer */
59696  int available = 0;  /* Number of bytes available on the local btree page */
59697  int rc = SQLITE_OK; /* Return code */
59698
59699  assert( sqlite3BtreeCursorIsValid(pCur) );
59700
59701  /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
59702  ** that both the BtShared and database handle mutexes are held. */
59703  assert( (pMem->flags & MEM_RowSet)==0 );
59704  if( key ){
59705    zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
59706  }else{
59707    zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
59708  }
59709  assert( zData!=0 );
59710
59711  if( offset+amt<=available && (pMem->flags&MEM_Dyn)==0 ){
59712    sqlite3VdbeMemRelease(pMem);
59713    pMem->z = &zData[offset];
59714    pMem->flags = MEM_Blob|MEM_Ephem;
59715  }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
59716    pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
59717    pMem->enc = 0;
59718    pMem->type = SQLITE_BLOB;
59719    if( key ){
59720      rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
59721    }else{
59722      rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
59723    }
59724    pMem->z[amt] = 0;
59725    pMem->z[amt+1] = 0;
59726    if( rc!=SQLITE_OK ){
59727      sqlite3VdbeMemRelease(pMem);
59728    }
59729  }
59730  pMem->n = amt;
59731
59732  return rc;
59733}
59734
59735/* This function is only available internally, it is not part of the
59736** external API. It works in a similar way to sqlite3_value_text(),
59737** except the data returned is in the encoding specified by the second
59738** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
59739** SQLITE_UTF8.
59740**
59741** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
59742** If that is the case, then the result must be aligned on an even byte
59743** boundary.
59744*/
59745SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
59746  if( !pVal ) return 0;
59747
59748  assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
59749  assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
59750  assert( (pVal->flags & MEM_RowSet)==0 );
59751
59752  if( pVal->flags&MEM_Null ){
59753    return 0;
59754  }
59755  assert( (MEM_Blob>>3) == MEM_Str );
59756  pVal->flags |= (pVal->flags & MEM_Blob)>>3;
59757  ExpandBlob(pVal);
59758  if( pVal->flags&MEM_Str ){
59759    sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
59760    if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
59761      assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
59762      if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
59763        return 0;
59764      }
59765    }
59766    sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
59767  }else{
59768    assert( (pVal->flags&MEM_Blob)==0 );
59769    sqlite3VdbeMemStringify(pVal, enc);
59770    assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
59771  }
59772  assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
59773              || pVal->db->mallocFailed );
59774  if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
59775    return pVal->z;
59776  }else{
59777    return 0;
59778  }
59779}
59780
59781/*
59782** Create a new sqlite3_value object.
59783*/
59784SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
59785  Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
59786  if( p ){
59787    p->flags = MEM_Null;
59788    p->type = SQLITE_NULL;
59789    p->db = db;
59790  }
59791  return p;
59792}
59793
59794/*
59795** Create a new sqlite3_value object, containing the value of pExpr.
59796**
59797** This only works for very simple expressions that consist of one constant
59798** token (i.e. "5", "5.1", "'a string'"). If the expression can
59799** be converted directly into a value, then the value is allocated and
59800** a pointer written to *ppVal. The caller is responsible for deallocating
59801** the value by passing it to sqlite3ValueFree() later on. If the expression
59802** cannot be converted to a value, then *ppVal is set to NULL.
59803*/
59804SQLITE_PRIVATE int sqlite3ValueFromExpr(
59805  sqlite3 *db,              /* The database connection */
59806  Expr *pExpr,              /* The expression to evaluate */
59807  u8 enc,                   /* Encoding to use */
59808  u8 affinity,              /* Affinity to use */
59809  sqlite3_value **ppVal     /* Write the new value here */
59810){
59811  int op;
59812  char *zVal = 0;
59813  sqlite3_value *pVal = 0;
59814  int negInt = 1;
59815  const char *zNeg = "";
59816
59817  if( !pExpr ){
59818    *ppVal = 0;
59819    return SQLITE_OK;
59820  }
59821  op = pExpr->op;
59822
59823  /* op can only be TK_REGISTER if we have compiled with SQLITE_ENABLE_STAT3.
59824  ** The ifdef here is to enable us to achieve 100% branch test coverage even
59825  ** when SQLITE_ENABLE_STAT3 is omitted.
59826  */
59827#ifdef SQLITE_ENABLE_STAT3
59828  if( op==TK_REGISTER ) op = pExpr->op2;
59829#else
59830  if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
59831#endif
59832
59833  /* Handle negative integers in a single step.  This is needed in the
59834  ** case when the value is -9223372036854775808.
59835  */
59836  if( op==TK_UMINUS
59837   && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
59838    pExpr = pExpr->pLeft;
59839    op = pExpr->op;
59840    negInt = -1;
59841    zNeg = "-";
59842  }
59843
59844  if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
59845    pVal = sqlite3ValueNew(db);
59846    if( pVal==0 ) goto no_mem;
59847    if( ExprHasProperty(pExpr, EP_IntValue) ){
59848      sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
59849    }else{
59850      zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
59851      if( zVal==0 ) goto no_mem;
59852      sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
59853      if( op==TK_FLOAT ) pVal->type = SQLITE_FLOAT;
59854    }
59855    if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
59856      sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
59857    }else{
59858      sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
59859    }
59860    if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
59861    if( enc!=SQLITE_UTF8 ){
59862      sqlite3VdbeChangeEncoding(pVal, enc);
59863    }
59864  }else if( op==TK_UMINUS ) {
59865    /* This branch happens for multiple negative signs.  Ex: -(-5) */
59866    if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
59867      sqlite3VdbeMemNumerify(pVal);
59868      if( pVal->u.i==SMALLEST_INT64 ){
59869        pVal->flags &= MEM_Int;
59870        pVal->flags |= MEM_Real;
59871        pVal->r = (double)LARGEST_INT64;
59872      }else{
59873        pVal->u.i = -pVal->u.i;
59874      }
59875      pVal->r = -pVal->r;
59876      sqlite3ValueApplyAffinity(pVal, affinity, enc);
59877    }
59878  }else if( op==TK_NULL ){
59879    pVal = sqlite3ValueNew(db);
59880    if( pVal==0 ) goto no_mem;
59881  }
59882#ifndef SQLITE_OMIT_BLOB_LITERAL
59883  else if( op==TK_BLOB ){
59884    int nVal;
59885    assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
59886    assert( pExpr->u.zToken[1]=='\'' );
59887    pVal = sqlite3ValueNew(db);
59888    if( !pVal ) goto no_mem;
59889    zVal = &pExpr->u.zToken[2];
59890    nVal = sqlite3Strlen30(zVal)-1;
59891    assert( zVal[nVal]=='\'' );
59892    sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
59893                         0, SQLITE_DYNAMIC);
59894  }
59895#endif
59896
59897  if( pVal ){
59898    sqlite3VdbeMemStoreType(pVal);
59899  }
59900  *ppVal = pVal;
59901  return SQLITE_OK;
59902
59903no_mem:
59904  db->mallocFailed = 1;
59905  sqlite3DbFree(db, zVal);
59906  sqlite3ValueFree(pVal);
59907  *ppVal = 0;
59908  return SQLITE_NOMEM;
59909}
59910
59911/*
59912** Change the string value of an sqlite3_value object
59913*/
59914SQLITE_PRIVATE void sqlite3ValueSetStr(
59915  sqlite3_value *v,     /* Value to be set */
59916  int n,                /* Length of string z */
59917  const void *z,        /* Text of the new string */
59918  u8 enc,               /* Encoding to use */
59919  void (*xDel)(void*)   /* Destructor for the string */
59920){
59921  if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
59922}
59923
59924/*
59925** Free an sqlite3_value object
59926*/
59927SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
59928  if( !v ) return;
59929  sqlite3VdbeMemRelease((Mem *)v);
59930  sqlite3DbFree(((Mem*)v)->db, v);
59931}
59932
59933/*
59934** Return the number of bytes in the sqlite3_value object assuming
59935** that it uses the encoding "enc"
59936*/
59937SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
59938  Mem *p = (Mem*)pVal;
59939  if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
59940    if( p->flags & MEM_Zero ){
59941      return p->n + p->u.nZero;
59942    }else{
59943      return p->n;
59944    }
59945  }
59946  return 0;
59947}
59948
59949/************** End of vdbemem.c *********************************************/
59950/************** Begin file vdbeaux.c *****************************************/
59951/*
59952** 2003 September 6
59953**
59954** The author disclaims copyright to this source code.  In place of
59955** a legal notice, here is a blessing:
59956**
59957**    May you do good and not evil.
59958**    May you find forgiveness for yourself and forgive others.
59959**    May you share freely, never taking more than you give.
59960**
59961*************************************************************************
59962** This file contains code used for creating, destroying, and populating
59963** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)  Prior
59964** to version 2.8.7, all this code was combined into the vdbe.c source file.
59965** But that file was getting too big so this subroutines were split out.
59966*/
59967
59968/*
59969** Create a new virtual database engine.
59970*/
59971SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
59972  Vdbe *p;
59973  p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
59974  if( p==0 ) return 0;
59975  p->db = db;
59976  if( db->pVdbe ){
59977    db->pVdbe->pPrev = p;
59978  }
59979  p->pNext = db->pVdbe;
59980  p->pPrev = 0;
59981  db->pVdbe = p;
59982  p->magic = VDBE_MAGIC_INIT;
59983  return p;
59984}
59985
59986/*
59987** Remember the SQL string for a prepared statement.
59988*/
59989SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
59990  assert( isPrepareV2==1 || isPrepareV2==0 );
59991  if( p==0 ) return;
59992#if defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_ENABLE_SQLLOG)
59993  if( !isPrepareV2 ) return;
59994#endif
59995  assert( p->zSql==0 );
59996  p->zSql = sqlite3DbStrNDup(p->db, z, n);
59997  p->isPrepareV2 = (u8)isPrepareV2;
59998}
59999
60000/*
60001** Return the SQL associated with a prepared statement
60002*/
60003SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
60004  Vdbe *p = (Vdbe *)pStmt;
60005  return (p && p->isPrepareV2) ? p->zSql : 0;
60006}
60007
60008/*
60009** Swap all content between two VDBE structures.
60010*/
60011SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
60012  Vdbe tmp, *pTmp;
60013  char *zTmp;
60014  tmp = *pA;
60015  *pA = *pB;
60016  *pB = tmp;
60017  pTmp = pA->pNext;
60018  pA->pNext = pB->pNext;
60019  pB->pNext = pTmp;
60020  pTmp = pA->pPrev;
60021  pA->pPrev = pB->pPrev;
60022  pB->pPrev = pTmp;
60023  zTmp = pA->zSql;
60024  pA->zSql = pB->zSql;
60025  pB->zSql = zTmp;
60026  pB->isPrepareV2 = pA->isPrepareV2;
60027}
60028
60029#ifdef SQLITE_DEBUG
60030/*
60031** Turn tracing on or off
60032*/
60033SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
60034  p->trace = trace;
60035}
60036#endif
60037
60038/*
60039** Resize the Vdbe.aOp array so that it is at least one op larger than
60040** it was.
60041**
60042** If an out-of-memory error occurs while resizing the array, return
60043** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain
60044** unchanged (this is so that any opcodes already allocated can be
60045** correctly deallocated along with the rest of the Vdbe).
60046*/
60047static int growOpArray(Vdbe *p){
60048  VdbeOp *pNew;
60049  int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
60050  pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
60051  if( pNew ){
60052    p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
60053    p->aOp = pNew;
60054  }
60055  return (pNew ? SQLITE_OK : SQLITE_NOMEM);
60056}
60057
60058/*
60059** Add a new instruction to the list of instructions current in the
60060** VDBE.  Return the address of the new instruction.
60061**
60062** Parameters:
60063**
60064**    p               Pointer to the VDBE
60065**
60066**    op              The opcode for this instruction
60067**
60068**    p1, p2, p3      Operands
60069**
60070** Use the sqlite3VdbeResolveLabel() function to fix an address and
60071** the sqlite3VdbeChangeP4() function to change the value of the P4
60072** operand.
60073*/
60074SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
60075  int i;
60076  VdbeOp *pOp;
60077
60078  i = p->nOp;
60079  assert( p->magic==VDBE_MAGIC_INIT );
60080  assert( op>0 && op<0xff );
60081  if( p->nOpAlloc<=i ){
60082    if( growOpArray(p) ){
60083      return 1;
60084    }
60085  }
60086  p->nOp++;
60087  pOp = &p->aOp[i];
60088  pOp->opcode = (u8)op;
60089  pOp->p5 = 0;
60090  pOp->p1 = p1;
60091  pOp->p2 = p2;
60092  pOp->p3 = p3;
60093  pOp->p4.p = 0;
60094  pOp->p4type = P4_NOTUSED;
60095#ifdef SQLITE_DEBUG
60096  pOp->zComment = 0;
60097  if( p->db->flags & SQLITE_VdbeAddopTrace ){
60098    sqlite3VdbePrintOp(0, i, &p->aOp[i]);
60099  }
60100#endif
60101#ifdef VDBE_PROFILE
60102  pOp->cycles = 0;
60103  pOp->cnt = 0;
60104#endif
60105  return i;
60106}
60107SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
60108  return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
60109}
60110SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
60111  return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
60112}
60113SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
60114  return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
60115}
60116
60117
60118/*
60119** Add an opcode that includes the p4 value as a pointer.
60120*/
60121SQLITE_PRIVATE int sqlite3VdbeAddOp4(
60122  Vdbe *p,            /* Add the opcode to this VM */
60123  int op,             /* The new opcode */
60124  int p1,             /* The P1 operand */
60125  int p2,             /* The P2 operand */
60126  int p3,             /* The P3 operand */
60127  const char *zP4,    /* The P4 operand */
60128  int p4type          /* P4 operand type */
60129){
60130  int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
60131  sqlite3VdbeChangeP4(p, addr, zP4, p4type);
60132  return addr;
60133}
60134
60135/*
60136** Add an OP_ParseSchema opcode.  This routine is broken out from
60137** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
60138** as having been used.
60139**
60140** The zWhere string must have been obtained from sqlite3_malloc().
60141** This routine will take ownership of the allocated memory.
60142*/
60143SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
60144  int j;
60145  int addr = sqlite3VdbeAddOp3(p, OP_ParseSchema, iDb, 0, 0);
60146  sqlite3VdbeChangeP4(p, addr, zWhere, P4_DYNAMIC);
60147  for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
60148}
60149
60150/*
60151** Add an opcode that includes the p4 value as an integer.
60152*/
60153SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
60154  Vdbe *p,            /* Add the opcode to this VM */
60155  int op,             /* The new opcode */
60156  int p1,             /* The P1 operand */
60157  int p2,             /* The P2 operand */
60158  int p3,             /* The P3 operand */
60159  int p4              /* The P4 operand as an integer */
60160){
60161  int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
60162  sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
60163  return addr;
60164}
60165
60166/*
60167** Create a new symbolic label for an instruction that has yet to be
60168** coded.  The symbolic label is really just a negative number.  The
60169** label can be used as the P2 value of an operation.  Later, when
60170** the label is resolved to a specific address, the VDBE will scan
60171** through its operation list and change all values of P2 which match
60172** the label into the resolved address.
60173**
60174** The VDBE knows that a P2 value is a label because labels are
60175** always negative and P2 values are suppose to be non-negative.
60176** Hence, a negative P2 value is a label that has yet to be resolved.
60177**
60178** Zero is returned if a malloc() fails.
60179*/
60180SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
60181  int i = p->nLabel++;
60182  assert( p->magic==VDBE_MAGIC_INIT );
60183  if( (i & (i-1))==0 ){
60184    p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
60185                                       (i*2+1)*sizeof(p->aLabel[0]));
60186  }
60187  if( p->aLabel ){
60188    p->aLabel[i] = -1;
60189  }
60190  return -1-i;
60191}
60192
60193/*
60194** Resolve label "x" to be the address of the next instruction to
60195** be inserted.  The parameter "x" must have been obtained from
60196** a prior call to sqlite3VdbeMakeLabel().
60197*/
60198SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
60199  int j = -1-x;
60200  assert( p->magic==VDBE_MAGIC_INIT );
60201  assert( j>=0 && j<p->nLabel );
60202  if( p->aLabel ){
60203    p->aLabel[j] = p->nOp;
60204  }
60205}
60206
60207/*
60208** Mark the VDBE as one that can only be run one time.
60209*/
60210SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
60211  p->runOnlyOnce = 1;
60212}
60213
60214#ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
60215
60216/*
60217** The following type and function are used to iterate through all opcodes
60218** in a Vdbe main program and each of the sub-programs (triggers) it may
60219** invoke directly or indirectly. It should be used as follows:
60220**
60221**   Op *pOp;
60222**   VdbeOpIter sIter;
60223**
60224**   memset(&sIter, 0, sizeof(sIter));
60225**   sIter.v = v;                            // v is of type Vdbe*
60226**   while( (pOp = opIterNext(&sIter)) ){
60227**     // Do something with pOp
60228**   }
60229**   sqlite3DbFree(v->db, sIter.apSub);
60230**
60231*/
60232typedef struct VdbeOpIter VdbeOpIter;
60233struct VdbeOpIter {
60234  Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
60235  SubProgram **apSub;        /* Array of subprograms */
60236  int nSub;                  /* Number of entries in apSub */
60237  int iAddr;                 /* Address of next instruction to return */
60238  int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
60239};
60240static Op *opIterNext(VdbeOpIter *p){
60241  Vdbe *v = p->v;
60242  Op *pRet = 0;
60243  Op *aOp;
60244  int nOp;
60245
60246  if( p->iSub<=p->nSub ){
60247
60248    if( p->iSub==0 ){
60249      aOp = v->aOp;
60250      nOp = v->nOp;
60251    }else{
60252      aOp = p->apSub[p->iSub-1]->aOp;
60253      nOp = p->apSub[p->iSub-1]->nOp;
60254    }
60255    assert( p->iAddr<nOp );
60256
60257    pRet = &aOp[p->iAddr];
60258    p->iAddr++;
60259    if( p->iAddr==nOp ){
60260      p->iSub++;
60261      p->iAddr = 0;
60262    }
60263
60264    if( pRet->p4type==P4_SUBPROGRAM ){
60265      int nByte = (p->nSub+1)*sizeof(SubProgram*);
60266      int j;
60267      for(j=0; j<p->nSub; j++){
60268        if( p->apSub[j]==pRet->p4.pProgram ) break;
60269      }
60270      if( j==p->nSub ){
60271        p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
60272        if( !p->apSub ){
60273          pRet = 0;
60274        }else{
60275          p->apSub[p->nSub++] = pRet->p4.pProgram;
60276        }
60277      }
60278    }
60279  }
60280
60281  return pRet;
60282}
60283
60284/*
60285** Check if the program stored in the VM associated with pParse may
60286** throw an ABORT exception (causing the statement, but not entire transaction
60287** to be rolled back). This condition is true if the main program or any
60288** sub-programs contains any of the following:
60289**
60290**   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
60291**   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
60292**   *  OP_Destroy
60293**   *  OP_VUpdate
60294**   *  OP_VRename
60295**   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
60296**
60297** Then check that the value of Parse.mayAbort is true if an
60298** ABORT may be thrown, or false otherwise. Return true if it does
60299** match, or false otherwise. This function is intended to be used as
60300** part of an assert statement in the compiler. Similar to:
60301**
60302**   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
60303*/
60304SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
60305  int hasAbort = 0;
60306  Op *pOp;
60307  VdbeOpIter sIter;
60308  memset(&sIter, 0, sizeof(sIter));
60309  sIter.v = v;
60310
60311  while( (pOp = opIterNext(&sIter))!=0 ){
60312    int opcode = pOp->opcode;
60313    if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
60314#ifndef SQLITE_OMIT_FOREIGN_KEY
60315     || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1)
60316#endif
60317     || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
60318      && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
60319    ){
60320      hasAbort = 1;
60321      break;
60322    }
60323  }
60324  sqlite3DbFree(v->db, sIter.apSub);
60325
60326  /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
60327  ** If malloc failed, then the while() loop above may not have iterated
60328  ** through all opcodes and hasAbort may be set incorrectly. Return
60329  ** true for this case to prevent the assert() in the callers frame
60330  ** from failing.  */
60331  return ( v->db->mallocFailed || hasAbort==mayAbort );
60332}
60333#endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
60334
60335/*
60336** Loop through the program looking for P2 values that are negative
60337** on jump instructions.  Each such value is a label.  Resolve the
60338** label by setting the P2 value to its correct non-zero value.
60339**
60340** This routine is called once after all opcodes have been inserted.
60341**
60342** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
60343** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
60344** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
60345**
60346** The Op.opflags field is set on all opcodes.
60347*/
60348static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
60349  int i;
60350  int nMaxArgs = *pMaxFuncArgs;
60351  Op *pOp;
60352  int *aLabel = p->aLabel;
60353  p->readOnly = 1;
60354  for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
60355    u8 opcode = pOp->opcode;
60356
60357    pOp->opflags = sqlite3OpcodeProperty[opcode];
60358    if( opcode==OP_Function || opcode==OP_AggStep ){
60359      if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
60360    }else if( (opcode==OP_Transaction && pOp->p2!=0) || opcode==OP_Vacuum ){
60361      p->readOnly = 0;
60362#ifndef SQLITE_OMIT_VIRTUALTABLE
60363    }else if( opcode==OP_VUpdate ){
60364      if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
60365    }else if( opcode==OP_VFilter ){
60366      int n;
60367      assert( p->nOp - i >= 3 );
60368      assert( pOp[-1].opcode==OP_Integer );
60369      n = pOp[-1].p1;
60370      if( n>nMaxArgs ) nMaxArgs = n;
60371#endif
60372    }else if( opcode==OP_Next || opcode==OP_SorterNext ){
60373      pOp->p4.xAdvance = sqlite3BtreeNext;
60374      pOp->p4type = P4_ADVANCE;
60375    }else if( opcode==OP_Prev ){
60376      pOp->p4.xAdvance = sqlite3BtreePrevious;
60377      pOp->p4type = P4_ADVANCE;
60378    }
60379
60380    if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
60381      assert( -1-pOp->p2<p->nLabel );
60382      pOp->p2 = aLabel[-1-pOp->p2];
60383    }
60384  }
60385  sqlite3DbFree(p->db, p->aLabel);
60386  p->aLabel = 0;
60387
60388  *pMaxFuncArgs = nMaxArgs;
60389}
60390
60391/*
60392** Return the address of the next instruction to be inserted.
60393*/
60394SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
60395  assert( p->magic==VDBE_MAGIC_INIT );
60396  return p->nOp;
60397}
60398
60399/*
60400** This function returns a pointer to the array of opcodes associated with
60401** the Vdbe passed as the first argument. It is the callers responsibility
60402** to arrange for the returned array to be eventually freed using the
60403** vdbeFreeOpArray() function.
60404**
60405** Before returning, *pnOp is set to the number of entries in the returned
60406** array. Also, *pnMaxArg is set to the larger of its current value and
60407** the number of entries in the Vdbe.apArg[] array required to execute the
60408** returned program.
60409*/
60410SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
60411  VdbeOp *aOp = p->aOp;
60412  assert( aOp && !p->db->mallocFailed );
60413
60414  /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
60415  assert( p->btreeMask==0 );
60416
60417  resolveP2Values(p, pnMaxArg);
60418  *pnOp = p->nOp;
60419  p->aOp = 0;
60420  return aOp;
60421}
60422
60423/*
60424** Add a whole list of operations to the operation stack.  Return the
60425** address of the first operation added.
60426*/
60427SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
60428  int addr;
60429  assert( p->magic==VDBE_MAGIC_INIT );
60430  if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){
60431    return 0;
60432  }
60433  addr = p->nOp;
60434  if( ALWAYS(nOp>0) ){
60435    int i;
60436    VdbeOpList const *pIn = aOp;
60437    for(i=0; i<nOp; i++, pIn++){
60438      int p2 = pIn->p2;
60439      VdbeOp *pOut = &p->aOp[i+addr];
60440      pOut->opcode = pIn->opcode;
60441      pOut->p1 = pIn->p1;
60442      if( p2<0 && (sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP)!=0 ){
60443        pOut->p2 = addr + ADDR(p2);
60444      }else{
60445        pOut->p2 = p2;
60446      }
60447      pOut->p3 = pIn->p3;
60448      pOut->p4type = P4_NOTUSED;
60449      pOut->p4.p = 0;
60450      pOut->p5 = 0;
60451#ifdef SQLITE_DEBUG
60452      pOut->zComment = 0;
60453      if( p->db->flags & SQLITE_VdbeAddopTrace ){
60454        sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
60455      }
60456#endif
60457    }
60458    p->nOp += nOp;
60459  }
60460  return addr;
60461}
60462
60463/*
60464** Change the value of the P1 operand for a specific instruction.
60465** This routine is useful when a large program is loaded from a
60466** static array using sqlite3VdbeAddOpList but we want to make a
60467** few minor changes to the program.
60468*/
60469SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
60470  assert( p!=0 );
60471  if( ((u32)p->nOp)>addr ){
60472    p->aOp[addr].p1 = val;
60473  }
60474}
60475
60476/*
60477** Change the value of the P2 operand for a specific instruction.
60478** This routine is useful for setting a jump destination.
60479*/
60480SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
60481  assert( p!=0 );
60482  if( ((u32)p->nOp)>addr ){
60483    p->aOp[addr].p2 = val;
60484  }
60485}
60486
60487/*
60488** Change the value of the P3 operand for a specific instruction.
60489*/
60490SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
60491  assert( p!=0 );
60492  if( ((u32)p->nOp)>addr ){
60493    p->aOp[addr].p3 = val;
60494  }
60495}
60496
60497/*
60498** Change the value of the P5 operand for the most recently
60499** added operation.
60500*/
60501SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
60502  assert( p!=0 );
60503  if( p->aOp ){
60504    assert( p->nOp>0 );
60505    p->aOp[p->nOp-1].p5 = val;
60506  }
60507}
60508
60509/*
60510** Change the P2 operand of instruction addr so that it points to
60511** the address of the next instruction to be coded.
60512*/
60513SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
60514  assert( addr>=0 || p->db->mallocFailed );
60515  if( addr>=0 ) sqlite3VdbeChangeP2(p, addr, p->nOp);
60516}
60517
60518
60519/*
60520** If the input FuncDef structure is ephemeral, then free it.  If
60521** the FuncDef is not ephermal, then do nothing.
60522*/
60523static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
60524  if( ALWAYS(pDef) && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
60525    sqlite3DbFree(db, pDef);
60526  }
60527}
60528
60529static void vdbeFreeOpArray(sqlite3 *, Op *, int);
60530
60531/*
60532** Delete a P4 value if necessary.
60533*/
60534static void freeP4(sqlite3 *db, int p4type, void *p4){
60535  if( p4 ){
60536    assert( db );
60537    switch( p4type ){
60538      case P4_REAL:
60539      case P4_INT64:
60540      case P4_DYNAMIC:
60541      case P4_KEYINFO:
60542      case P4_INTARRAY:
60543      case P4_KEYINFO_HANDOFF: {
60544        sqlite3DbFree(db, p4);
60545        break;
60546      }
60547      case P4_MPRINTF: {
60548        if( db->pnBytesFreed==0 ) sqlite3_free(p4);
60549        break;
60550      }
60551      case P4_VDBEFUNC: {
60552        VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;
60553        freeEphemeralFunction(db, pVdbeFunc->pFunc);
60554        if( db->pnBytesFreed==0 ) sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
60555        sqlite3DbFree(db, pVdbeFunc);
60556        break;
60557      }
60558      case P4_FUNCDEF: {
60559        freeEphemeralFunction(db, (FuncDef*)p4);
60560        break;
60561      }
60562      case P4_MEM: {
60563        if( db->pnBytesFreed==0 ){
60564          sqlite3ValueFree((sqlite3_value*)p4);
60565        }else{
60566          Mem *p = (Mem*)p4;
60567          sqlite3DbFree(db, p->zMalloc);
60568          sqlite3DbFree(db, p);
60569        }
60570        break;
60571      }
60572      case P4_VTAB : {
60573        if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
60574        break;
60575      }
60576    }
60577  }
60578}
60579
60580/*
60581** Free the space allocated for aOp and any p4 values allocated for the
60582** opcodes contained within. If aOp is not NULL it is assumed to contain
60583** nOp entries.
60584*/
60585static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
60586  if( aOp ){
60587    Op *pOp;
60588    for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
60589      freeP4(db, pOp->p4type, pOp->p4.p);
60590#ifdef SQLITE_DEBUG
60591      sqlite3DbFree(db, pOp->zComment);
60592#endif
60593    }
60594  }
60595  sqlite3DbFree(db, aOp);
60596}
60597
60598/*
60599** Link the SubProgram object passed as the second argument into the linked
60600** list at Vdbe.pSubProgram. This list is used to delete all sub-program
60601** objects when the VM is no longer required.
60602*/
60603SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
60604  p->pNext = pVdbe->pProgram;
60605  pVdbe->pProgram = p;
60606}
60607
60608/*
60609** Change the opcode at addr into OP_Noop
60610*/
60611SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
60612  if( p->aOp ){
60613    VdbeOp *pOp = &p->aOp[addr];
60614    sqlite3 *db = p->db;
60615    freeP4(db, pOp->p4type, pOp->p4.p);
60616    memset(pOp, 0, sizeof(pOp[0]));
60617    pOp->opcode = OP_Noop;
60618  }
60619}
60620
60621/*
60622** Change the value of the P4 operand for a specific instruction.
60623** This routine is useful when a large program is loaded from a
60624** static array using sqlite3VdbeAddOpList but we want to make a
60625** few minor changes to the program.
60626**
60627** If n>=0 then the P4 operand is dynamic, meaning that a copy of
60628** the string is made into memory obtained from sqlite3_malloc().
60629** A value of n==0 means copy bytes of zP4 up to and including the
60630** first null byte.  If n>0 then copy n+1 bytes of zP4.
60631**
60632** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
60633** A copy is made of the KeyInfo structure into memory obtained from
60634** sqlite3_malloc, to be freed when the Vdbe is finalized.
60635** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
60636** stored in memory that the caller has obtained from sqlite3_malloc. The
60637** caller should not free the allocation, it will be freed when the Vdbe is
60638** finalized.
60639**
60640** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
60641** to a string or structure that is guaranteed to exist for the lifetime of
60642** the Vdbe. In these cases we can just copy the pointer.
60643**
60644** If addr<0 then change P4 on the most recently inserted instruction.
60645*/
60646SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
60647  Op *pOp;
60648  sqlite3 *db;
60649  assert( p!=0 );
60650  db = p->db;
60651  assert( p->magic==VDBE_MAGIC_INIT );
60652  if( p->aOp==0 || db->mallocFailed ){
60653    if ( n!=P4_KEYINFO && n!=P4_VTAB ) {
60654      freeP4(db, n, (void*)*(char**)&zP4);
60655    }
60656    return;
60657  }
60658  assert( p->nOp>0 );
60659  assert( addr<p->nOp );
60660  if( addr<0 ){
60661    addr = p->nOp - 1;
60662  }
60663  pOp = &p->aOp[addr];
60664  assert( pOp->p4type==P4_NOTUSED || pOp->p4type==P4_INT32 );
60665  freeP4(db, pOp->p4type, pOp->p4.p);
60666  pOp->p4.p = 0;
60667  if( n==P4_INT32 ){
60668    /* Note: this cast is safe, because the origin data point was an int
60669    ** that was cast to a (const char *). */
60670    pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
60671    pOp->p4type = P4_INT32;
60672  }else if( zP4==0 ){
60673    pOp->p4.p = 0;
60674    pOp->p4type = P4_NOTUSED;
60675  }else if( n==P4_KEYINFO ){
60676    KeyInfo *pKeyInfo;
60677    int nField, nByte;
60678
60679    nField = ((KeyInfo*)zP4)->nField;
60680    nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
60681    pKeyInfo = sqlite3DbMallocRaw(0, nByte);
60682    pOp->p4.pKeyInfo = pKeyInfo;
60683    if( pKeyInfo ){
60684      u8 *aSortOrder;
60685      memcpy((char*)pKeyInfo, zP4, nByte - nField);
60686      aSortOrder = pKeyInfo->aSortOrder;
60687      assert( aSortOrder!=0 );
60688      pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
60689      memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
60690      pOp->p4type = P4_KEYINFO;
60691    }else{
60692      p->db->mallocFailed = 1;
60693      pOp->p4type = P4_NOTUSED;
60694    }
60695  }else if( n==P4_KEYINFO_HANDOFF ){
60696    pOp->p4.p = (void*)zP4;
60697    pOp->p4type = P4_KEYINFO;
60698  }else if( n==P4_VTAB ){
60699    pOp->p4.p = (void*)zP4;
60700    pOp->p4type = P4_VTAB;
60701    sqlite3VtabLock((VTable *)zP4);
60702    assert( ((VTable *)zP4)->db==p->db );
60703  }else if( n<0 ){
60704    pOp->p4.p = (void*)zP4;
60705    pOp->p4type = (signed char)n;
60706  }else{
60707    if( n==0 ) n = sqlite3Strlen30(zP4);
60708    pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
60709    pOp->p4type = P4_DYNAMIC;
60710  }
60711}
60712
60713#ifndef NDEBUG
60714/*
60715** Change the comment on the most recently coded instruction.  Or
60716** insert a No-op and add the comment to that new instruction.  This
60717** makes the code easier to read during debugging.  None of this happens
60718** in a production build.
60719*/
60720static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
60721  assert( p->nOp>0 || p->aOp==0 );
60722  assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
60723  if( p->nOp ){
60724    assert( p->aOp );
60725    sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
60726    p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
60727  }
60728}
60729SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
60730  va_list ap;
60731  if( p ){
60732    va_start(ap, zFormat);
60733    vdbeVComment(p, zFormat, ap);
60734    va_end(ap);
60735  }
60736}
60737SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
60738  va_list ap;
60739  if( p ){
60740    sqlite3VdbeAddOp0(p, OP_Noop);
60741    va_start(ap, zFormat);
60742    vdbeVComment(p, zFormat, ap);
60743    va_end(ap);
60744  }
60745}
60746#endif  /* NDEBUG */
60747
60748/*
60749** Return the opcode for a given address.  If the address is -1, then
60750** return the most recently inserted opcode.
60751**
60752** If a memory allocation error has occurred prior to the calling of this
60753** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
60754** is readable but not writable, though it is cast to a writable value.
60755** The return of a dummy opcode allows the call to continue functioning
60756** after a OOM fault without having to check to see if the return from
60757** this routine is a valid pointer.  But because the dummy.opcode is 0,
60758** dummy will never be written to.  This is verified by code inspection and
60759** by running with Valgrind.
60760**
60761** About the #ifdef SQLITE_OMIT_TRACE:  Normally, this routine is never called
60762** unless p->nOp>0.  This is because in the absense of SQLITE_OMIT_TRACE,
60763** an OP_Trace instruction is always inserted by sqlite3VdbeGet() as soon as
60764** a new VDBE is created.  So we are free to set addr to p->nOp-1 without
60765** having to double-check to make sure that the result is non-negative. But
60766** if SQLITE_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to
60767** check the value of p->nOp-1 before continuing.
60768*/
60769SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
60770  /* C89 specifies that the constant "dummy" will be initialized to all
60771  ** zeros, which is correct.  MSVC generates a warning, nevertheless. */
60772  static VdbeOp dummy;  /* Ignore the MSVC warning about no initializer */
60773  assert( p->magic==VDBE_MAGIC_INIT );
60774  if( addr<0 ){
60775#ifdef SQLITE_OMIT_TRACE
60776    if( p->nOp==0 ) return (VdbeOp*)&dummy;
60777#endif
60778    addr = p->nOp - 1;
60779  }
60780  assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
60781  if( p->db->mallocFailed ){
60782    return (VdbeOp*)&dummy;
60783  }else{
60784    return &p->aOp[addr];
60785  }
60786}
60787
60788#if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
60789     || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
60790/*
60791** Compute a string that describes the P4 parameter for an opcode.
60792** Use zTemp for any required temporary buffer space.
60793*/
60794static char *displayP4(Op *pOp, char *zTemp, int nTemp){
60795  char *zP4 = zTemp;
60796  assert( nTemp>=20 );
60797  switch( pOp->p4type ){
60798    case P4_KEYINFO_STATIC:
60799    case P4_KEYINFO: {
60800      int i, j;
60801      KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
60802      assert( pKeyInfo->aSortOrder!=0 );
60803      sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
60804      i = sqlite3Strlen30(zTemp);
60805      for(j=0; j<pKeyInfo->nField; j++){
60806        CollSeq *pColl = pKeyInfo->aColl[j];
60807        const char *zColl = pColl ? pColl->zName : "nil";
60808        int n = sqlite3Strlen30(zColl);
60809        if( i+n>nTemp-6 ){
60810          memcpy(&zTemp[i],",...",4);
60811          break;
60812        }
60813        zTemp[i++] = ',';
60814        if( pKeyInfo->aSortOrder[j] ){
60815          zTemp[i++] = '-';
60816        }
60817        memcpy(&zTemp[i], zColl, n+1);
60818        i += n;
60819      }
60820      zTemp[i++] = ')';
60821      zTemp[i] = 0;
60822      assert( i<nTemp );
60823      break;
60824    }
60825    case P4_COLLSEQ: {
60826      CollSeq *pColl = pOp->p4.pColl;
60827      sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
60828      break;
60829    }
60830    case P4_FUNCDEF: {
60831      FuncDef *pDef = pOp->p4.pFunc;
60832      sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
60833      break;
60834    }
60835    case P4_INT64: {
60836      sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
60837      break;
60838    }
60839    case P4_INT32: {
60840      sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
60841      break;
60842    }
60843    case P4_REAL: {
60844      sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
60845      break;
60846    }
60847    case P4_MEM: {
60848      Mem *pMem = pOp->p4.pMem;
60849      if( pMem->flags & MEM_Str ){
60850        zP4 = pMem->z;
60851      }else if( pMem->flags & MEM_Int ){
60852        sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
60853      }else if( pMem->flags & MEM_Real ){
60854        sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
60855      }else if( pMem->flags & MEM_Null ){
60856        sqlite3_snprintf(nTemp, zTemp, "NULL");
60857      }else{
60858        assert( pMem->flags & MEM_Blob );
60859        zP4 = "(blob)";
60860      }
60861      break;
60862    }
60863#ifndef SQLITE_OMIT_VIRTUALTABLE
60864    case P4_VTAB: {
60865      sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
60866      sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
60867      break;
60868    }
60869#endif
60870    case P4_INTARRAY: {
60871      sqlite3_snprintf(nTemp, zTemp, "intarray");
60872      break;
60873    }
60874    case P4_SUBPROGRAM: {
60875      sqlite3_snprintf(nTemp, zTemp, "program");
60876      break;
60877    }
60878    case P4_ADVANCE: {
60879      zTemp[0] = 0;
60880      break;
60881    }
60882    default: {
60883      zP4 = pOp->p4.z;
60884      if( zP4==0 ){
60885        zP4 = zTemp;
60886        zTemp[0] = 0;
60887      }
60888    }
60889  }
60890  assert( zP4!=0 );
60891  return zP4;
60892}
60893#endif
60894
60895/*
60896** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
60897**
60898** The prepared statements need to know in advance the complete set of
60899** attached databases that will be use.  A mask of these databases
60900** is maintained in p->btreeMask.  The p->lockMask value is the subset of
60901** p->btreeMask of databases that will require a lock.
60902*/
60903SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
60904  assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
60905  assert( i<(int)sizeof(p->btreeMask)*8 );
60906  p->btreeMask |= ((yDbMask)1)<<i;
60907  if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
60908    p->lockMask |= ((yDbMask)1)<<i;
60909  }
60910}
60911
60912#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
60913/*
60914** If SQLite is compiled to support shared-cache mode and to be threadsafe,
60915** this routine obtains the mutex associated with each BtShared structure
60916** that may be accessed by the VM passed as an argument. In doing so it also
60917** sets the BtShared.db member of each of the BtShared structures, ensuring
60918** that the correct busy-handler callback is invoked if required.
60919**
60920** If SQLite is not threadsafe but does support shared-cache mode, then
60921** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
60922** of all of BtShared structures accessible via the database handle
60923** associated with the VM.
60924**
60925** If SQLite is not threadsafe and does not support shared-cache mode, this
60926** function is a no-op.
60927**
60928** The p->btreeMask field is a bitmask of all btrees that the prepared
60929** statement p will ever use.  Let N be the number of bits in p->btreeMask
60930** corresponding to btrees that use shared cache.  Then the runtime of
60931** this routine is N*N.  But as N is rarely more than 1, this should not
60932** be a problem.
60933*/
60934SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
60935  int i;
60936  yDbMask mask;
60937  sqlite3 *db;
60938  Db *aDb;
60939  int nDb;
60940  if( p->lockMask==0 ) return;  /* The common case */
60941  db = p->db;
60942  aDb = db->aDb;
60943  nDb = db->nDb;
60944  for(i=0, mask=1; i<nDb; i++, mask += mask){
60945    if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
60946      sqlite3BtreeEnter(aDb[i].pBt);
60947    }
60948  }
60949}
60950#endif
60951
60952#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
60953/*
60954** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
60955*/
60956SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
60957  int i;
60958  yDbMask mask;
60959  sqlite3 *db;
60960  Db *aDb;
60961  int nDb;
60962  if( p->lockMask==0 ) return;  /* The common case */
60963  db = p->db;
60964  aDb = db->aDb;
60965  nDb = db->nDb;
60966  for(i=0, mask=1; i<nDb; i++, mask += mask){
60967    if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
60968      sqlite3BtreeLeave(aDb[i].pBt);
60969    }
60970  }
60971}
60972#endif
60973
60974#if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
60975/*
60976** Print a single opcode.  This routine is used for debugging only.
60977*/
60978SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
60979  char *zP4;
60980  char zPtr[50];
60981  static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
60982  if( pOut==0 ) pOut = stdout;
60983  zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
60984  fprintf(pOut, zFormat1, pc,
60985      sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
60986#ifdef SQLITE_DEBUG
60987      pOp->zComment ? pOp->zComment : ""
60988#else
60989      ""
60990#endif
60991  );
60992  fflush(pOut);
60993}
60994#endif
60995
60996/*
60997** Release an array of N Mem elements
60998*/
60999static void releaseMemArray(Mem *p, int N){
61000  if( p && N ){
61001    Mem *pEnd;
61002    sqlite3 *db = p->db;
61003    u8 malloc_failed = db->mallocFailed;
61004    if( db->pnBytesFreed ){
61005      for(pEnd=&p[N]; p<pEnd; p++){
61006        sqlite3DbFree(db, p->zMalloc);
61007      }
61008      return;
61009    }
61010    for(pEnd=&p[N]; p<pEnd; p++){
61011      assert( (&p[1])==pEnd || p[0].db==p[1].db );
61012
61013      /* This block is really an inlined version of sqlite3VdbeMemRelease()
61014      ** that takes advantage of the fact that the memory cell value is
61015      ** being set to NULL after releasing any dynamic resources.
61016      **
61017      ** The justification for duplicating code is that according to
61018      ** callgrind, this causes a certain test case to hit the CPU 4.7
61019      ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
61020      ** sqlite3MemRelease() were called from here. With -O2, this jumps
61021      ** to 6.6 percent. The test case is inserting 1000 rows into a table
61022      ** with no indexes using a single prepared INSERT statement, bind()
61023      ** and reset(). Inserts are grouped into a transaction.
61024      */
61025      if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
61026        sqlite3VdbeMemRelease(p);
61027      }else if( p->zMalloc ){
61028        sqlite3DbFree(db, p->zMalloc);
61029        p->zMalloc = 0;
61030      }
61031
61032      p->flags = MEM_Invalid;
61033    }
61034    db->mallocFailed = malloc_failed;
61035  }
61036}
61037
61038/*
61039** Delete a VdbeFrame object and its contents. VdbeFrame objects are
61040** allocated by the OP_Program opcode in sqlite3VdbeExec().
61041*/
61042SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
61043  int i;
61044  Mem *aMem = VdbeFrameMem(p);
61045  VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
61046  for(i=0; i<p->nChildCsr; i++){
61047    sqlite3VdbeFreeCursor(p->v, apCsr[i]);
61048  }
61049  releaseMemArray(aMem, p->nChildMem);
61050  sqlite3DbFree(p->v->db, p);
61051}
61052
61053#ifndef SQLITE_OMIT_EXPLAIN
61054/*
61055** Give a listing of the program in the virtual machine.
61056**
61057** The interface is the same as sqlite3VdbeExec().  But instead of
61058** running the code, it invokes the callback once for each instruction.
61059** This feature is used to implement "EXPLAIN".
61060**
61061** When p->explain==1, each instruction is listed.  When
61062** p->explain==2, only OP_Explain instructions are listed and these
61063** are shown in a different format.  p->explain==2 is used to implement
61064** EXPLAIN QUERY PLAN.
61065**
61066** When p->explain==1, first the main program is listed, then each of
61067** the trigger subprograms are listed one by one.
61068*/
61069SQLITE_PRIVATE int sqlite3VdbeList(
61070  Vdbe *p                   /* The VDBE */
61071){
61072  int nRow;                            /* Stop when row count reaches this */
61073  int nSub = 0;                        /* Number of sub-vdbes seen so far */
61074  SubProgram **apSub = 0;              /* Array of sub-vdbes */
61075  Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
61076  sqlite3 *db = p->db;                 /* The database connection */
61077  int i;                               /* Loop counter */
61078  int rc = SQLITE_OK;                  /* Return code */
61079  Mem *pMem = &p->aMem[1];             /* First Mem of result set */
61080
61081  assert( p->explain );
61082  assert( p->magic==VDBE_MAGIC_RUN );
61083  assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
61084
61085  /* Even though this opcode does not use dynamic strings for
61086  ** the result, result columns may become dynamic if the user calls
61087  ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
61088  */
61089  releaseMemArray(pMem, 8);
61090  p->pResultSet = 0;
61091
61092  if( p->rc==SQLITE_NOMEM ){
61093    /* This happens if a malloc() inside a call to sqlite3_column_text() or
61094    ** sqlite3_column_text16() failed.  */
61095    db->mallocFailed = 1;
61096    return SQLITE_ERROR;
61097  }
61098
61099  /* When the number of output rows reaches nRow, that means the
61100  ** listing has finished and sqlite3_step() should return SQLITE_DONE.
61101  ** nRow is the sum of the number of rows in the main program, plus
61102  ** the sum of the number of rows in all trigger subprograms encountered
61103  ** so far.  The nRow value will increase as new trigger subprograms are
61104  ** encountered, but p->pc will eventually catch up to nRow.
61105  */
61106  nRow = p->nOp;
61107  if( p->explain==1 ){
61108    /* The first 8 memory cells are used for the result set.  So we will
61109    ** commandeer the 9th cell to use as storage for an array of pointers
61110    ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
61111    ** cells.  */
61112    assert( p->nMem>9 );
61113    pSub = &p->aMem[9];
61114    if( pSub->flags&MEM_Blob ){
61115      /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is
61116      ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
61117      nSub = pSub->n/sizeof(Vdbe*);
61118      apSub = (SubProgram **)pSub->z;
61119    }
61120    for(i=0; i<nSub; i++){
61121      nRow += apSub[i]->nOp;
61122    }
61123  }
61124
61125  do{
61126    i = p->pc++;
61127  }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
61128  if( i>=nRow ){
61129    p->rc = SQLITE_OK;
61130    rc = SQLITE_DONE;
61131  }else if( db->u1.isInterrupted ){
61132    p->rc = SQLITE_INTERRUPT;
61133    rc = SQLITE_ERROR;
61134    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
61135  }else{
61136    char *z;
61137    Op *pOp;
61138    if( i<p->nOp ){
61139      /* The output line number is small enough that we are still in the
61140      ** main program. */
61141      pOp = &p->aOp[i];
61142    }else{
61143      /* We are currently listing subprograms.  Figure out which one and
61144      ** pick up the appropriate opcode. */
61145      int j;
61146      i -= p->nOp;
61147      for(j=0; i>=apSub[j]->nOp; j++){
61148        i -= apSub[j]->nOp;
61149      }
61150      pOp = &apSub[j]->aOp[i];
61151    }
61152    if( p->explain==1 ){
61153      pMem->flags = MEM_Int;
61154      pMem->type = SQLITE_INTEGER;
61155      pMem->u.i = i;                                /* Program counter */
61156      pMem++;
61157
61158      pMem->flags = MEM_Static|MEM_Str|MEM_Term;
61159      pMem->z = (char*)sqlite3OpcodeName(pOp->opcode);  /* Opcode */
61160      assert( pMem->z!=0 );
61161      pMem->n = sqlite3Strlen30(pMem->z);
61162      pMem->type = SQLITE_TEXT;
61163      pMem->enc = SQLITE_UTF8;
61164      pMem++;
61165
61166      /* When an OP_Program opcode is encounter (the only opcode that has
61167      ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
61168      ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
61169      ** has not already been seen.
61170      */
61171      if( pOp->p4type==P4_SUBPROGRAM ){
61172        int nByte = (nSub+1)*sizeof(SubProgram*);
61173        int j;
61174        for(j=0; j<nSub; j++){
61175          if( apSub[j]==pOp->p4.pProgram ) break;
61176        }
61177        if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){
61178          apSub = (SubProgram **)pSub->z;
61179          apSub[nSub++] = pOp->p4.pProgram;
61180          pSub->flags |= MEM_Blob;
61181          pSub->n = nSub*sizeof(SubProgram*);
61182        }
61183      }
61184    }
61185
61186    pMem->flags = MEM_Int;
61187    pMem->u.i = pOp->p1;                          /* P1 */
61188    pMem->type = SQLITE_INTEGER;
61189    pMem++;
61190
61191    pMem->flags = MEM_Int;
61192    pMem->u.i = pOp->p2;                          /* P2 */
61193    pMem->type = SQLITE_INTEGER;
61194    pMem++;
61195
61196    pMem->flags = MEM_Int;
61197    pMem->u.i = pOp->p3;                          /* P3 */
61198    pMem->type = SQLITE_INTEGER;
61199    pMem++;
61200
61201    if( sqlite3VdbeMemGrow(pMem, 32, 0) ){            /* P4 */
61202      assert( p->db->mallocFailed );
61203      return SQLITE_ERROR;
61204    }
61205    pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
61206    z = displayP4(pOp, pMem->z, 32);
61207    if( z!=pMem->z ){
61208      sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
61209    }else{
61210      assert( pMem->z!=0 );
61211      pMem->n = sqlite3Strlen30(pMem->z);
61212      pMem->enc = SQLITE_UTF8;
61213    }
61214    pMem->type = SQLITE_TEXT;
61215    pMem++;
61216
61217    if( p->explain==1 ){
61218      if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
61219        assert( p->db->mallocFailed );
61220        return SQLITE_ERROR;
61221      }
61222      pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
61223      pMem->n = 2;
61224      sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
61225      pMem->type = SQLITE_TEXT;
61226      pMem->enc = SQLITE_UTF8;
61227      pMem++;
61228
61229#ifdef SQLITE_DEBUG
61230      if( pOp->zComment ){
61231        pMem->flags = MEM_Str|MEM_Term;
61232        pMem->z = pOp->zComment;
61233        pMem->n = sqlite3Strlen30(pMem->z);
61234        pMem->enc = SQLITE_UTF8;
61235        pMem->type = SQLITE_TEXT;
61236      }else
61237#endif
61238      {
61239        pMem->flags = MEM_Null;                       /* Comment */
61240        pMem->type = SQLITE_NULL;
61241      }
61242    }
61243
61244    p->nResColumn = 8 - 4*(p->explain-1);
61245    p->pResultSet = &p->aMem[1];
61246    p->rc = SQLITE_OK;
61247    rc = SQLITE_ROW;
61248  }
61249  return rc;
61250}
61251#endif /* SQLITE_OMIT_EXPLAIN */
61252
61253#ifdef SQLITE_DEBUG
61254/*
61255** Print the SQL that was used to generate a VDBE program.
61256*/
61257SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
61258  int nOp = p->nOp;
61259  VdbeOp *pOp;
61260  if( nOp<1 ) return;
61261  pOp = &p->aOp[0];
61262  if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
61263    const char *z = pOp->p4.z;
61264    while( sqlite3Isspace(*z) ) z++;
61265    printf("SQL: [%s]\n", z);
61266  }
61267}
61268#endif
61269
61270#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
61271/*
61272** Print an IOTRACE message showing SQL content.
61273*/
61274SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
61275  int nOp = p->nOp;
61276  VdbeOp *pOp;
61277  if( sqlite3IoTrace==0 ) return;
61278  if( nOp<1 ) return;
61279  pOp = &p->aOp[0];
61280  if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
61281    int i, j;
61282    char z[1000];
61283    sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
61284    for(i=0; sqlite3Isspace(z[i]); i++){}
61285    for(j=0; z[i]; i++){
61286      if( sqlite3Isspace(z[i]) ){
61287        if( z[i-1]!=' ' ){
61288          z[j++] = ' ';
61289        }
61290      }else{
61291        z[j++] = z[i];
61292      }
61293    }
61294    z[j] = 0;
61295    sqlite3IoTrace("SQL %s\n", z);
61296  }
61297}
61298#endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
61299
61300/*
61301** Allocate space from a fixed size buffer and return a pointer to
61302** that space.  If insufficient space is available, return NULL.
61303**
61304** The pBuf parameter is the initial value of a pointer which will
61305** receive the new memory.  pBuf is normally NULL.  If pBuf is not
61306** NULL, it means that memory space has already been allocated and that
61307** this routine should not allocate any new memory.  When pBuf is not
61308** NULL simply return pBuf.  Only allocate new memory space when pBuf
61309** is NULL.
61310**
61311** nByte is the number of bytes of space needed.
61312**
61313** *ppFrom points to available space and pEnd points to the end of the
61314** available space.  When space is allocated, *ppFrom is advanced past
61315** the end of the allocated space.
61316**
61317** *pnByte is a counter of the number of bytes of space that have failed
61318** to allocate.  If there is insufficient space in *ppFrom to satisfy the
61319** request, then increment *pnByte by the amount of the request.
61320*/
61321static void *allocSpace(
61322  void *pBuf,          /* Where return pointer will be stored */
61323  int nByte,           /* Number of bytes to allocate */
61324  u8 **ppFrom,         /* IN/OUT: Allocate from *ppFrom */
61325  u8 *pEnd,            /* Pointer to 1 byte past the end of *ppFrom buffer */
61326  int *pnByte          /* If allocation cannot be made, increment *pnByte */
61327){
61328  assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
61329  if( pBuf ) return pBuf;
61330  nByte = ROUND8(nByte);
61331  if( &(*ppFrom)[nByte] <= pEnd ){
61332    pBuf = (void*)*ppFrom;
61333    *ppFrom += nByte;
61334  }else{
61335    *pnByte += nByte;
61336  }
61337  return pBuf;
61338}
61339
61340/*
61341** Rewind the VDBE back to the beginning in preparation for
61342** running it.
61343*/
61344SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
61345#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
61346  int i;
61347#endif
61348  assert( p!=0 );
61349  assert( p->magic==VDBE_MAGIC_INIT );
61350
61351  /* There should be at least one opcode.
61352  */
61353  assert( p->nOp>0 );
61354
61355  /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
61356  p->magic = VDBE_MAGIC_RUN;
61357
61358#ifdef SQLITE_DEBUG
61359  for(i=1; i<p->nMem; i++){
61360    assert( p->aMem[i].db==p->db );
61361  }
61362#endif
61363  p->pc = -1;
61364  p->rc = SQLITE_OK;
61365  p->errorAction = OE_Abort;
61366  p->magic = VDBE_MAGIC_RUN;
61367  p->nChange = 0;
61368  p->cacheCtr = 1;
61369  p->minWriteFileFormat = 255;
61370  p->iStatement = 0;
61371  p->nFkConstraint = 0;
61372#ifdef VDBE_PROFILE
61373  for(i=0; i<p->nOp; i++){
61374    p->aOp[i].cnt = 0;
61375    p->aOp[i].cycles = 0;
61376  }
61377#endif
61378}
61379
61380/*
61381** Prepare a virtual machine for execution for the first time after
61382** creating the virtual machine.  This involves things such
61383** as allocating stack space and initializing the program counter.
61384** After the VDBE has be prepped, it can be executed by one or more
61385** calls to sqlite3VdbeExec().
61386**
61387** This function may be called exact once on a each virtual machine.
61388** After this routine is called the VM has been "packaged" and is ready
61389** to run.  After this routine is called, futher calls to
61390** sqlite3VdbeAddOp() functions are prohibited.  This routine disconnects
61391** the Vdbe from the Parse object that helped generate it so that the
61392** the Vdbe becomes an independent entity and the Parse object can be
61393** destroyed.
61394**
61395** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
61396** to its initial state after it has been run.
61397*/
61398SQLITE_PRIVATE void sqlite3VdbeMakeReady(
61399  Vdbe *p,                       /* The VDBE */
61400  Parse *pParse                  /* Parsing context */
61401){
61402  sqlite3 *db;                   /* The database connection */
61403  int nVar;                      /* Number of parameters */
61404  int nMem;                      /* Number of VM memory registers */
61405  int nCursor;                   /* Number of cursors required */
61406  int nArg;                      /* Number of arguments in subprograms */
61407  int nOnce;                     /* Number of OP_Once instructions */
61408  int n;                         /* Loop counter */
61409  u8 *zCsr;                      /* Memory available for allocation */
61410  u8 *zEnd;                      /* First byte past allocated memory */
61411  int nByte;                     /* How much extra memory is needed */
61412
61413  assert( p!=0 );
61414  assert( p->nOp>0 );
61415  assert( pParse!=0 );
61416  assert( p->magic==VDBE_MAGIC_INIT );
61417  db = p->db;
61418  assert( db->mallocFailed==0 );
61419  nVar = pParse->nVar;
61420  nMem = pParse->nMem;
61421  nCursor = pParse->nTab;
61422  nArg = pParse->nMaxArg;
61423  nOnce = pParse->nOnce;
61424  if( nOnce==0 ) nOnce = 1; /* Ensure at least one byte in p->aOnceFlag[] */
61425
61426  /* For each cursor required, also allocate a memory cell. Memory
61427  ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
61428  ** the vdbe program. Instead they are used to allocate space for
61429  ** VdbeCursor/BtCursor structures. The blob of memory associated with
61430  ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
61431  ** stores the blob of memory associated with cursor 1, etc.
61432  **
61433  ** See also: allocateCursor().
61434  */
61435  nMem += nCursor;
61436
61437  /* Allocate space for memory registers, SQL variables, VDBE cursors and
61438  ** an array to marshal SQL function arguments in.
61439  */
61440  zCsr = (u8*)&p->aOp[p->nOp];       /* Memory avaliable for allocation */
61441  zEnd = (u8*)&p->aOp[p->nOpAlloc];  /* First byte past end of zCsr[] */
61442
61443  resolveP2Values(p, &nArg);
61444  p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
61445  if( pParse->explain && nMem<10 ){
61446    nMem = 10;
61447  }
61448  memset(zCsr, 0, zEnd-zCsr);
61449  zCsr += (zCsr - (u8*)0)&7;
61450  assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
61451  p->expired = 0;
61452
61453  /* Memory for registers, parameters, cursor, etc, is allocated in two
61454  ** passes.  On the first pass, we try to reuse unused space at the
61455  ** end of the opcode array.  If we are unable to satisfy all memory
61456  ** requirements by reusing the opcode array tail, then the second
61457  ** pass will fill in the rest using a fresh allocation.
61458  **
61459  ** This two-pass approach that reuses as much memory as possible from
61460  ** the leftover space at the end of the opcode array can significantly
61461  ** reduce the amount of memory held by a prepared statement.
61462  */
61463  do {
61464    nByte = 0;
61465    p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
61466    p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
61467    p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
61468    p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
61469    p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
61470                          &zCsr, zEnd, &nByte);
61471    p->aOnceFlag = allocSpace(p->aOnceFlag, nOnce, &zCsr, zEnd, &nByte);
61472    if( nByte ){
61473      p->pFree = sqlite3DbMallocZero(db, nByte);
61474    }
61475    zCsr = p->pFree;
61476    zEnd = &zCsr[nByte];
61477  }while( nByte && !db->mallocFailed );
61478
61479  p->nCursor = nCursor;
61480  p->nOnceFlag = nOnce;
61481  if( p->aVar ){
61482    p->nVar = (ynVar)nVar;
61483    for(n=0; n<nVar; n++){
61484      p->aVar[n].flags = MEM_Null;
61485      p->aVar[n].db = db;
61486    }
61487  }
61488  if( p->azVar ){
61489    p->nzVar = pParse->nzVar;
61490    memcpy(p->azVar, pParse->azVar, p->nzVar*sizeof(p->azVar[0]));
61491    memset(pParse->azVar, 0, pParse->nzVar*sizeof(pParse->azVar[0]));
61492  }
61493  if( p->aMem ){
61494    p->aMem--;                      /* aMem[] goes from 1..nMem */
61495    p->nMem = nMem;                 /*       not from 0..nMem-1 */
61496    for(n=1; n<=nMem; n++){
61497      p->aMem[n].flags = MEM_Invalid;
61498      p->aMem[n].db = db;
61499    }
61500  }
61501  p->explain = pParse->explain;
61502  sqlite3VdbeRewind(p);
61503}
61504
61505/*
61506** Close a VDBE cursor and release all the resources that cursor
61507** happens to hold.
61508*/
61509SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
61510  if( pCx==0 ){
61511    return;
61512  }
61513  sqlite3VdbeSorterClose(p->db, pCx);
61514  if( pCx->pBt ){
61515    sqlite3BtreeClose(pCx->pBt);
61516    /* The pCx->pCursor will be close automatically, if it exists, by
61517    ** the call above. */
61518  }else if( pCx->pCursor ){
61519    sqlite3BtreeCloseCursor(pCx->pCursor);
61520  }
61521#ifndef SQLITE_OMIT_VIRTUALTABLE
61522  if( pCx->pVtabCursor ){
61523    sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
61524    const sqlite3_module *pModule = pCx->pModule;
61525    p->inVtabMethod = 1;
61526    pModule->xClose(pVtabCursor);
61527    p->inVtabMethod = 0;
61528  }
61529#endif
61530}
61531
61532/*
61533** Copy the values stored in the VdbeFrame structure to its Vdbe. This
61534** is used, for example, when a trigger sub-program is halted to restore
61535** control to the main program.
61536*/
61537SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
61538  Vdbe *v = pFrame->v;
61539  v->aOnceFlag = pFrame->aOnceFlag;
61540  v->nOnceFlag = pFrame->nOnceFlag;
61541  v->aOp = pFrame->aOp;
61542  v->nOp = pFrame->nOp;
61543  v->aMem = pFrame->aMem;
61544  v->nMem = pFrame->nMem;
61545  v->apCsr = pFrame->apCsr;
61546  v->nCursor = pFrame->nCursor;
61547  v->db->lastRowid = pFrame->lastRowid;
61548  v->nChange = pFrame->nChange;
61549  return pFrame->pc;
61550}
61551
61552/*
61553** Close all cursors.
61554**
61555** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
61556** cell array. This is necessary as the memory cell array may contain
61557** pointers to VdbeFrame objects, which may in turn contain pointers to
61558** open cursors.
61559*/
61560static void closeAllCursors(Vdbe *p){
61561  if( p->pFrame ){
61562    VdbeFrame *pFrame;
61563    for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
61564    sqlite3VdbeFrameRestore(pFrame);
61565  }
61566  p->pFrame = 0;
61567  p->nFrame = 0;
61568
61569  if( p->apCsr ){
61570    int i;
61571    for(i=0; i<p->nCursor; i++){
61572      VdbeCursor *pC = p->apCsr[i];
61573      if( pC ){
61574        sqlite3VdbeFreeCursor(p, pC);
61575        p->apCsr[i] = 0;
61576      }
61577    }
61578  }
61579  if( p->aMem ){
61580    releaseMemArray(&p->aMem[1], p->nMem);
61581  }
61582  while( p->pDelFrame ){
61583    VdbeFrame *pDel = p->pDelFrame;
61584    p->pDelFrame = pDel->pParent;
61585    sqlite3VdbeFrameDelete(pDel);
61586  }
61587}
61588
61589/*
61590** Clean up the VM after execution.
61591**
61592** This routine will automatically close any cursors, lists, and/or
61593** sorters that were left open.  It also deletes the values of
61594** variables in the aVar[] array.
61595*/
61596static void Cleanup(Vdbe *p){
61597  sqlite3 *db = p->db;
61598
61599#ifdef SQLITE_DEBUG
61600  /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
61601  ** Vdbe.aMem[] arrays have already been cleaned up.  */
61602  int i;
61603  if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
61604  if( p->aMem ){
61605    for(i=1; i<=p->nMem; i++) assert( p->aMem[i].flags==MEM_Invalid );
61606  }
61607#endif
61608
61609  sqlite3DbFree(db, p->zErrMsg);
61610  p->zErrMsg = 0;
61611  p->pResultSet = 0;
61612}
61613
61614/*
61615** Set the number of result columns that will be returned by this SQL
61616** statement. This is now set at compile time, rather than during
61617** execution of the vdbe program so that sqlite3_column_count() can
61618** be called on an SQL statement before sqlite3_step().
61619*/
61620SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
61621  Mem *pColName;
61622  int n;
61623  sqlite3 *db = p->db;
61624
61625  releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
61626  sqlite3DbFree(db, p->aColName);
61627  n = nResColumn*COLNAME_N;
61628  p->nResColumn = (u16)nResColumn;
61629  p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
61630  if( p->aColName==0 ) return;
61631  while( n-- > 0 ){
61632    pColName->flags = MEM_Null;
61633    pColName->db = p->db;
61634    pColName++;
61635  }
61636}
61637
61638/*
61639** Set the name of the idx'th column to be returned by the SQL statement.
61640** zName must be a pointer to a nul terminated string.
61641**
61642** This call must be made after a call to sqlite3VdbeSetNumCols().
61643**
61644** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
61645** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
61646** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
61647*/
61648SQLITE_PRIVATE int sqlite3VdbeSetColName(
61649  Vdbe *p,                         /* Vdbe being configured */
61650  int idx,                         /* Index of column zName applies to */
61651  int var,                         /* One of the COLNAME_* constants */
61652  const char *zName,               /* Pointer to buffer containing name */
61653  void (*xDel)(void*)              /* Memory management strategy for zName */
61654){
61655  int rc;
61656  Mem *pColName;
61657  assert( idx<p->nResColumn );
61658  assert( var<COLNAME_N );
61659  if( p->db->mallocFailed ){
61660    assert( !zName || xDel!=SQLITE_DYNAMIC );
61661    return SQLITE_NOMEM;
61662  }
61663  assert( p->aColName!=0 );
61664  pColName = &(p->aColName[idx+var*p->nResColumn]);
61665  rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
61666  assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
61667  return rc;
61668}
61669
61670/*
61671** A read or write transaction may or may not be active on database handle
61672** db. If a transaction is active, commit it. If there is a
61673** write-transaction spanning more than one database file, this routine
61674** takes care of the master journal trickery.
61675*/
61676static int vdbeCommit(sqlite3 *db, Vdbe *p){
61677  int i;
61678  int nTrans = 0;  /* Number of databases with an active write-transaction */
61679  int rc = SQLITE_OK;
61680  int needXcommit = 0;
61681
61682#ifdef SQLITE_OMIT_VIRTUALTABLE
61683  /* With this option, sqlite3VtabSync() is defined to be simply
61684  ** SQLITE_OK so p is not used.
61685  */
61686  UNUSED_PARAMETER(p);
61687#endif
61688
61689  /* Before doing anything else, call the xSync() callback for any
61690  ** virtual module tables written in this transaction. This has to
61691  ** be done before determining whether a master journal file is
61692  ** required, as an xSync() callback may add an attached database
61693  ** to the transaction.
61694  */
61695  rc = sqlite3VtabSync(db, &p->zErrMsg);
61696
61697  /* This loop determines (a) if the commit hook should be invoked and
61698  ** (b) how many database files have open write transactions, not
61699  ** including the temp database. (b) is important because if more than
61700  ** one database file has an open write transaction, a master journal
61701  ** file is required for an atomic commit.
61702  */
61703  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
61704    Btree *pBt = db->aDb[i].pBt;
61705    if( sqlite3BtreeIsInTrans(pBt) ){
61706      needXcommit = 1;
61707      if( i!=1 ) nTrans++;
61708      sqlite3BtreeEnter(pBt);
61709      rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
61710      sqlite3BtreeLeave(pBt);
61711    }
61712  }
61713  if( rc!=SQLITE_OK ){
61714    return rc;
61715  }
61716
61717  /* If there are any write-transactions at all, invoke the commit hook */
61718  if( needXcommit && db->xCommitCallback ){
61719    rc = db->xCommitCallback(db->pCommitArg);
61720    if( rc ){
61721      return SQLITE_CONSTRAINT_COMMITHOOK;
61722    }
61723  }
61724
61725  /* The simple case - no more than one database file (not counting the
61726  ** TEMP database) has a transaction active.   There is no need for the
61727  ** master-journal.
61728  **
61729  ** If the return value of sqlite3BtreeGetFilename() is a zero length
61730  ** string, it means the main database is :memory: or a temp file.  In
61731  ** that case we do not support atomic multi-file commits, so use the
61732  ** simple case then too.
61733  */
61734  if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
61735   || nTrans<=1
61736  ){
61737    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
61738      Btree *pBt = db->aDb[i].pBt;
61739      if( pBt ){
61740        rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
61741      }
61742    }
61743
61744    /* Do the commit only if all databases successfully complete phase 1.
61745    ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
61746    ** IO error while deleting or truncating a journal file. It is unlikely,
61747    ** but could happen. In this case abandon processing and return the error.
61748    */
61749    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
61750      Btree *pBt = db->aDb[i].pBt;
61751      if( pBt ){
61752        rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
61753      }
61754    }
61755    if( rc==SQLITE_OK ){
61756      sqlite3VtabCommit(db);
61757    }
61758  }
61759
61760  /* The complex case - There is a multi-file write-transaction active.
61761  ** This requires a master journal file to ensure the transaction is
61762  ** committed atomicly.
61763  */
61764#ifndef SQLITE_OMIT_DISKIO
61765  else{
61766    sqlite3_vfs *pVfs = db->pVfs;
61767    int needSync = 0;
61768    char *zMaster = 0;   /* File-name for the master journal */
61769    char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
61770    sqlite3_file *pMaster = 0;
61771    i64 offset = 0;
61772    int res;
61773    int retryCount = 0;
61774    int nMainFile;
61775
61776    /* Select a master journal file name */
61777    nMainFile = sqlite3Strlen30(zMainFile);
61778    zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
61779    if( zMaster==0 ) return SQLITE_NOMEM;
61780    do {
61781      u32 iRandom;
61782      if( retryCount ){
61783        if( retryCount>100 ){
61784          sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
61785          sqlite3OsDelete(pVfs, zMaster, 0);
61786          break;
61787        }else if( retryCount==1 ){
61788          sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
61789        }
61790      }
61791      retryCount++;
61792      sqlite3_randomness(sizeof(iRandom), &iRandom);
61793      sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
61794                               (iRandom>>8)&0xffffff, iRandom&0xff);
61795      /* The antipenultimate character of the master journal name must
61796      ** be "9" to avoid name collisions when using 8+3 filenames. */
61797      assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
61798      sqlite3FileSuffix3(zMainFile, zMaster);
61799      rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
61800    }while( rc==SQLITE_OK && res );
61801    if( rc==SQLITE_OK ){
61802      /* Open the master journal. */
61803      rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
61804          SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
61805          SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
61806      );
61807    }
61808    if( rc!=SQLITE_OK ){
61809      sqlite3DbFree(db, zMaster);
61810      return rc;
61811    }
61812
61813    /* Write the name of each database file in the transaction into the new
61814    ** master journal file. If an error occurs at this point close
61815    ** and delete the master journal file. All the individual journal files
61816    ** still have 'null' as the master journal pointer, so they will roll
61817    ** back independently if a failure occurs.
61818    */
61819    for(i=0; i<db->nDb; i++){
61820      Btree *pBt = db->aDb[i].pBt;
61821      if( sqlite3BtreeIsInTrans(pBt) ){
61822        char const *zFile = sqlite3BtreeGetJournalname(pBt);
61823        if( zFile==0 ){
61824          continue;  /* Ignore TEMP and :memory: databases */
61825        }
61826        assert( zFile[0]!=0 );
61827        if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
61828          needSync = 1;
61829        }
61830        rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
61831        offset += sqlite3Strlen30(zFile)+1;
61832        if( rc!=SQLITE_OK ){
61833          sqlite3OsCloseFree(pMaster);
61834          sqlite3OsDelete(pVfs, zMaster, 0);
61835          sqlite3DbFree(db, zMaster);
61836          return rc;
61837        }
61838      }
61839    }
61840
61841    /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
61842    ** flag is set this is not required.
61843    */
61844    if( needSync
61845     && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
61846     && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
61847    ){
61848      sqlite3OsCloseFree(pMaster);
61849      sqlite3OsDelete(pVfs, zMaster, 0);
61850      sqlite3DbFree(db, zMaster);
61851      return rc;
61852    }
61853
61854    /* Sync all the db files involved in the transaction. The same call
61855    ** sets the master journal pointer in each individual journal. If
61856    ** an error occurs here, do not delete the master journal file.
61857    **
61858    ** If the error occurs during the first call to
61859    ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
61860    ** master journal file will be orphaned. But we cannot delete it,
61861    ** in case the master journal file name was written into the journal
61862    ** file before the failure occurred.
61863    */
61864    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
61865      Btree *pBt = db->aDb[i].pBt;
61866      if( pBt ){
61867        rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
61868      }
61869    }
61870    sqlite3OsCloseFree(pMaster);
61871    assert( rc!=SQLITE_BUSY );
61872    if( rc!=SQLITE_OK ){
61873      sqlite3DbFree(db, zMaster);
61874      return rc;
61875    }
61876
61877    /* Delete the master journal file. This commits the transaction. After
61878    ** doing this the directory is synced again before any individual
61879    ** transaction files are deleted.
61880    */
61881    rc = sqlite3OsDelete(pVfs, zMaster, 1);
61882    sqlite3DbFree(db, zMaster);
61883    zMaster = 0;
61884    if( rc ){
61885      return rc;
61886    }
61887
61888    /* All files and directories have already been synced, so the following
61889    ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
61890    ** deleting or truncating journals. If something goes wrong while
61891    ** this is happening we don't really care. The integrity of the
61892    ** transaction is already guaranteed, but some stray 'cold' journals
61893    ** may be lying around. Returning an error code won't help matters.
61894    */
61895    disable_simulated_io_errors();
61896    sqlite3BeginBenignMalloc();
61897    for(i=0; i<db->nDb; i++){
61898      Btree *pBt = db->aDb[i].pBt;
61899      if( pBt ){
61900        sqlite3BtreeCommitPhaseTwo(pBt, 1);
61901      }
61902    }
61903    sqlite3EndBenignMalloc();
61904    enable_simulated_io_errors();
61905
61906    sqlite3VtabCommit(db);
61907  }
61908#endif
61909
61910  return rc;
61911}
61912
61913/*
61914** This routine checks that the sqlite3.activeVdbeCnt count variable
61915** matches the number of vdbe's in the list sqlite3.pVdbe that are
61916** currently active. An assertion fails if the two counts do not match.
61917** This is an internal self-check only - it is not an essential processing
61918** step.
61919**
61920** This is a no-op if NDEBUG is defined.
61921*/
61922#ifndef NDEBUG
61923static void checkActiveVdbeCnt(sqlite3 *db){
61924  Vdbe *p;
61925  int cnt = 0;
61926  int nWrite = 0;
61927  p = db->pVdbe;
61928  while( p ){
61929    if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
61930      cnt++;
61931      if( p->readOnly==0 ) nWrite++;
61932    }
61933    p = p->pNext;
61934  }
61935  assert( cnt==db->activeVdbeCnt );
61936  assert( nWrite==db->writeVdbeCnt );
61937}
61938#else
61939#define checkActiveVdbeCnt(x)
61940#endif
61941
61942/*
61943** If the Vdbe passed as the first argument opened a statement-transaction,
61944** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
61945** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
61946** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
61947** statement transaction is commtted.
61948**
61949** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
61950** Otherwise SQLITE_OK.
61951*/
61952SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
61953  sqlite3 *const db = p->db;
61954  int rc = SQLITE_OK;
61955
61956  /* If p->iStatement is greater than zero, then this Vdbe opened a
61957  ** statement transaction that should be closed here. The only exception
61958  ** is that an IO error may have occurred, causing an emergency rollback.
61959  ** In this case (db->nStatement==0), and there is nothing to do.
61960  */
61961  if( db->nStatement && p->iStatement ){
61962    int i;
61963    const int iSavepoint = p->iStatement-1;
61964
61965    assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
61966    assert( db->nStatement>0 );
61967    assert( p->iStatement==(db->nStatement+db->nSavepoint) );
61968
61969    for(i=0; i<db->nDb; i++){
61970      int rc2 = SQLITE_OK;
61971      Btree *pBt = db->aDb[i].pBt;
61972      if( pBt ){
61973        if( eOp==SAVEPOINT_ROLLBACK ){
61974          rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
61975        }
61976        if( rc2==SQLITE_OK ){
61977          rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
61978        }
61979        if( rc==SQLITE_OK ){
61980          rc = rc2;
61981        }
61982      }
61983    }
61984    db->nStatement--;
61985    p->iStatement = 0;
61986
61987    if( rc==SQLITE_OK ){
61988      if( eOp==SAVEPOINT_ROLLBACK ){
61989        rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
61990      }
61991      if( rc==SQLITE_OK ){
61992        rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
61993      }
61994    }
61995
61996    /* If the statement transaction is being rolled back, also restore the
61997    ** database handles deferred constraint counter to the value it had when
61998    ** the statement transaction was opened.  */
61999    if( eOp==SAVEPOINT_ROLLBACK ){
62000      db->nDeferredCons = p->nStmtDefCons;
62001    }
62002  }
62003  return rc;
62004}
62005
62006/*
62007** This function is called when a transaction opened by the database
62008** handle associated with the VM passed as an argument is about to be
62009** committed. If there are outstanding deferred foreign key constraint
62010** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
62011**
62012** If there are outstanding FK violations and this function returns
62013** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
62014** and write an error message to it. Then return SQLITE_ERROR.
62015*/
62016#ifndef SQLITE_OMIT_FOREIGN_KEY
62017SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
62018  sqlite3 *db = p->db;
62019  if( (deferred && db->nDeferredCons>0) || (!deferred && p->nFkConstraint>0) ){
62020    p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
62021    p->errorAction = OE_Abort;
62022    sqlite3SetString(&p->zErrMsg, db, "foreign key constraint failed");
62023    return SQLITE_ERROR;
62024  }
62025  return SQLITE_OK;
62026}
62027#endif
62028
62029/*
62030** This routine is called the when a VDBE tries to halt.  If the VDBE
62031** has made changes and is in autocommit mode, then commit those
62032** changes.  If a rollback is needed, then do the rollback.
62033**
62034** This routine is the only way to move the state of a VM from
62035** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
62036** call this on a VM that is in the SQLITE_MAGIC_HALT state.
62037**
62038** Return an error code.  If the commit could not complete because of
62039** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
62040** means the close did not happen and needs to be repeated.
62041*/
62042SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
62043  int rc;                         /* Used to store transient return codes */
62044  sqlite3 *db = p->db;
62045
62046  /* This function contains the logic that determines if a statement or
62047  ** transaction will be committed or rolled back as a result of the
62048  ** execution of this virtual machine.
62049  **
62050  ** If any of the following errors occur:
62051  **
62052  **     SQLITE_NOMEM
62053  **     SQLITE_IOERR
62054  **     SQLITE_FULL
62055  **     SQLITE_INTERRUPT
62056  **
62057  ** Then the internal cache might have been left in an inconsistent
62058  ** state.  We need to rollback the statement transaction, if there is
62059  ** one, or the complete transaction if there is no statement transaction.
62060  */
62061
62062  if( p->db->mallocFailed ){
62063    p->rc = SQLITE_NOMEM;
62064  }
62065  if( p->aOnceFlag ) memset(p->aOnceFlag, 0, p->nOnceFlag);
62066  closeAllCursors(p);
62067  if( p->magic!=VDBE_MAGIC_RUN ){
62068    return SQLITE_OK;
62069  }
62070  checkActiveVdbeCnt(db);
62071
62072  /* No commit or rollback needed if the program never started */
62073  if( p->pc>=0 ){
62074    int mrc;   /* Primary error code from p->rc */
62075    int eStatementOp = 0;
62076    int isSpecialError;            /* Set to true if a 'special' error */
62077
62078    /* Lock all btrees used by the statement */
62079    sqlite3VdbeEnter(p);
62080
62081    /* Check for one of the special errors */
62082    mrc = p->rc & 0xff;
62083    assert( p->rc!=SQLITE_IOERR_BLOCKED );  /* This error no longer exists */
62084    isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
62085                     || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
62086    if( isSpecialError ){
62087      /* If the query was read-only and the error code is SQLITE_INTERRUPT,
62088      ** no rollback is necessary. Otherwise, at least a savepoint
62089      ** transaction must be rolled back to restore the database to a
62090      ** consistent state.
62091      **
62092      ** Even if the statement is read-only, it is important to perform
62093      ** a statement or transaction rollback operation. If the error
62094      ** occurred while writing to the journal, sub-journal or database
62095      ** file as part of an effort to free up cache space (see function
62096      ** pagerStress() in pager.c), the rollback is required to restore
62097      ** the pager to a consistent state.
62098      */
62099      if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
62100        if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
62101          eStatementOp = SAVEPOINT_ROLLBACK;
62102        }else{
62103          /* We are forced to roll back the active transaction. Before doing
62104          ** so, abort any other statements this handle currently has active.
62105          */
62106          sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
62107          sqlite3CloseSavepoints(db);
62108          db->autoCommit = 1;
62109        }
62110      }
62111    }
62112
62113    /* Check for immediate foreign key violations. */
62114    if( p->rc==SQLITE_OK ){
62115      sqlite3VdbeCheckFk(p, 0);
62116    }
62117
62118    /* If the auto-commit flag is set and this is the only active writer
62119    ** VM, then we do either a commit or rollback of the current transaction.
62120    **
62121    ** Note: This block also runs if one of the special errors handled
62122    ** above has occurred.
62123    */
62124    if( !sqlite3VtabInSync(db)
62125     && db->autoCommit
62126     && db->writeVdbeCnt==(p->readOnly==0)
62127    ){
62128      if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
62129        rc = sqlite3VdbeCheckFk(p, 1);
62130        if( rc!=SQLITE_OK ){
62131          if( NEVER(p->readOnly) ){
62132            sqlite3VdbeLeave(p);
62133            return SQLITE_ERROR;
62134          }
62135          rc = SQLITE_CONSTRAINT_FOREIGNKEY;
62136        }else{
62137          /* The auto-commit flag is true, the vdbe program was successful
62138          ** or hit an 'OR FAIL' constraint and there are no deferred foreign
62139          ** key constraints to hold up the transaction. This means a commit
62140          ** is required. */
62141          rc = vdbeCommit(db, p);
62142        }
62143        if( rc==SQLITE_BUSY && p->readOnly ){
62144          sqlite3VdbeLeave(p);
62145          return SQLITE_BUSY;
62146        }else if( rc!=SQLITE_OK ){
62147          p->rc = rc;
62148          sqlite3RollbackAll(db, SQLITE_OK);
62149        }else{
62150          db->nDeferredCons = 0;
62151          sqlite3CommitInternalChanges(db);
62152        }
62153      }else{
62154        sqlite3RollbackAll(db, SQLITE_OK);
62155      }
62156      db->nStatement = 0;
62157    }else if( eStatementOp==0 ){
62158      if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
62159        eStatementOp = SAVEPOINT_RELEASE;
62160      }else if( p->errorAction==OE_Abort ){
62161        eStatementOp = SAVEPOINT_ROLLBACK;
62162      }else{
62163        sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
62164        sqlite3CloseSavepoints(db);
62165        db->autoCommit = 1;
62166      }
62167    }
62168
62169    /* If eStatementOp is non-zero, then a statement transaction needs to
62170    ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
62171    ** do so. If this operation returns an error, and the current statement
62172    ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
62173    ** current statement error code.
62174    */
62175    if( eStatementOp ){
62176      rc = sqlite3VdbeCloseStatement(p, eStatementOp);
62177      if( rc ){
62178        if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
62179          p->rc = rc;
62180          sqlite3DbFree(db, p->zErrMsg);
62181          p->zErrMsg = 0;
62182        }
62183        sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
62184        sqlite3CloseSavepoints(db);
62185        db->autoCommit = 1;
62186      }
62187    }
62188
62189    /* If this was an INSERT, UPDATE or DELETE and no statement transaction
62190    ** has been rolled back, update the database connection change-counter.
62191    */
62192    if( p->changeCntOn ){
62193      if( eStatementOp!=SAVEPOINT_ROLLBACK ){
62194        sqlite3VdbeSetChanges(db, p->nChange);
62195      }else{
62196        sqlite3VdbeSetChanges(db, 0);
62197      }
62198      p->nChange = 0;
62199    }
62200
62201    /* Release the locks */
62202    sqlite3VdbeLeave(p);
62203  }
62204
62205  /* We have successfully halted and closed the VM.  Record this fact. */
62206  if( p->pc>=0 ){
62207    db->activeVdbeCnt--;
62208    if( !p->readOnly ){
62209      db->writeVdbeCnt--;
62210    }
62211    assert( db->activeVdbeCnt>=db->writeVdbeCnt );
62212  }
62213  p->magic = VDBE_MAGIC_HALT;
62214  checkActiveVdbeCnt(db);
62215  if( p->db->mallocFailed ){
62216    p->rc = SQLITE_NOMEM;
62217  }
62218
62219  /* If the auto-commit flag is set to true, then any locks that were held
62220  ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
62221  ** to invoke any required unlock-notify callbacks.
62222  */
62223  if( db->autoCommit ){
62224    sqlite3ConnectionUnlocked(db);
62225  }
62226
62227  assert( db->activeVdbeCnt>0 || db->autoCommit==0 || db->nStatement==0 );
62228  return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
62229}
62230
62231
62232/*
62233** Each VDBE holds the result of the most recent sqlite3_step() call
62234** in p->rc.  This routine sets that result back to SQLITE_OK.
62235*/
62236SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
62237  p->rc = SQLITE_OK;
62238}
62239
62240/*
62241** Copy the error code and error message belonging to the VDBE passed
62242** as the first argument to its database handle (so that they will be
62243** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
62244**
62245** This function does not clear the VDBE error code or message, just
62246** copies them to the database handle.
62247*/
62248SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
62249  sqlite3 *db = p->db;
62250  int rc = p->rc;
62251  if( p->zErrMsg ){
62252    u8 mallocFailed = db->mallocFailed;
62253    sqlite3BeginBenignMalloc();
62254    sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
62255    sqlite3EndBenignMalloc();
62256    db->mallocFailed = mallocFailed;
62257    db->errCode = rc;
62258  }else{
62259    sqlite3Error(db, rc, 0);
62260  }
62261  return rc;
62262}
62263
62264#ifdef SQLITE_ENABLE_SQLLOG
62265/*
62266** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
62267** invoke it.
62268*/
62269static void vdbeInvokeSqllog(Vdbe *v){
62270  if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
62271    char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
62272    assert( v->db->init.busy==0 );
62273    if( zExpanded ){
62274      sqlite3GlobalConfig.xSqllog(
62275          sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
62276      );
62277      sqlite3DbFree(v->db, zExpanded);
62278    }
62279  }
62280}
62281#else
62282# define vdbeInvokeSqllog(x)
62283#endif
62284
62285/*
62286** Clean up a VDBE after execution but do not delete the VDBE just yet.
62287** Write any error messages into *pzErrMsg.  Return the result code.
62288**
62289** After this routine is run, the VDBE should be ready to be executed
62290** again.
62291**
62292** To look at it another way, this routine resets the state of the
62293** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
62294** VDBE_MAGIC_INIT.
62295*/
62296SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
62297  sqlite3 *db;
62298  db = p->db;
62299
62300  /* If the VM did not run to completion or if it encountered an
62301  ** error, then it might not have been halted properly.  So halt
62302  ** it now.
62303  */
62304  sqlite3VdbeHalt(p);
62305
62306  /* If the VDBE has be run even partially, then transfer the error code
62307  ** and error message from the VDBE into the main database structure.  But
62308  ** if the VDBE has just been set to run but has not actually executed any
62309  ** instructions yet, leave the main database error information unchanged.
62310  */
62311  if( p->pc>=0 ){
62312    vdbeInvokeSqllog(p);
62313    sqlite3VdbeTransferError(p);
62314    sqlite3DbFree(db, p->zErrMsg);
62315    p->zErrMsg = 0;
62316    if( p->runOnlyOnce ) p->expired = 1;
62317  }else if( p->rc && p->expired ){
62318    /* The expired flag was set on the VDBE before the first call
62319    ** to sqlite3_step(). For consistency (since sqlite3_step() was
62320    ** called), set the database error in this case as well.
62321    */
62322    sqlite3Error(db, p->rc, 0);
62323    sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
62324    sqlite3DbFree(db, p->zErrMsg);
62325    p->zErrMsg = 0;
62326  }
62327
62328  /* Reclaim all memory used by the VDBE
62329  */
62330  Cleanup(p);
62331
62332  /* Save profiling information from this VDBE run.
62333  */
62334#ifdef VDBE_PROFILE
62335  {
62336    FILE *out = fopen("vdbe_profile.out", "a");
62337    if( out ){
62338      int i;
62339      fprintf(out, "---- ");
62340      for(i=0; i<p->nOp; i++){
62341        fprintf(out, "%02x", p->aOp[i].opcode);
62342      }
62343      fprintf(out, "\n");
62344      for(i=0; i<p->nOp; i++){
62345        fprintf(out, "%6d %10lld %8lld ",
62346           p->aOp[i].cnt,
62347           p->aOp[i].cycles,
62348           p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
62349        );
62350        sqlite3VdbePrintOp(out, i, &p->aOp[i]);
62351      }
62352      fclose(out);
62353    }
62354  }
62355#endif
62356  p->magic = VDBE_MAGIC_INIT;
62357  return p->rc & db->errMask;
62358}
62359
62360/*
62361** Clean up and delete a VDBE after execution.  Return an integer which is
62362** the result code.  Write any error message text into *pzErrMsg.
62363*/
62364SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
62365  int rc = SQLITE_OK;
62366  if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
62367    rc = sqlite3VdbeReset(p);
62368    assert( (rc & p->db->errMask)==rc );
62369  }
62370  sqlite3VdbeDelete(p);
62371  return rc;
62372}
62373
62374/*
62375** Call the destructor for each auxdata entry in pVdbeFunc for which
62376** the corresponding bit in mask is clear.  Auxdata entries beyond 31
62377** are always destroyed.  To destroy all auxdata entries, call this
62378** routine with mask==0.
62379*/
62380SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
62381  int i;
62382  for(i=0; i<pVdbeFunc->nAux; i++){
62383    struct AuxData *pAux = &pVdbeFunc->apAux[i];
62384    if( (i>31 || !(mask&(((u32)1)<<i))) && pAux->pAux ){
62385      if( pAux->xDelete ){
62386        pAux->xDelete(pAux->pAux);
62387      }
62388      pAux->pAux = 0;
62389    }
62390  }
62391}
62392
62393/*
62394** Free all memory associated with the Vdbe passed as the second argument,
62395** except for object itself, which is preserved.
62396**
62397** The difference between this function and sqlite3VdbeDelete() is that
62398** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
62399** the database connection and frees the object itself.
62400*/
62401SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
62402  SubProgram *pSub, *pNext;
62403  int i;
62404  assert( p->db==0 || p->db==db );
62405  releaseMemArray(p->aVar, p->nVar);
62406  releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
62407  for(pSub=p->pProgram; pSub; pSub=pNext){
62408    pNext = pSub->pNext;
62409    vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
62410    sqlite3DbFree(db, pSub);
62411  }
62412  for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);
62413  vdbeFreeOpArray(db, p->aOp, p->nOp);
62414  sqlite3DbFree(db, p->aLabel);
62415  sqlite3DbFree(db, p->aColName);
62416  sqlite3DbFree(db, p->zSql);
62417  sqlite3DbFree(db, p->pFree);
62418#if defined(SQLITE_ENABLE_TREE_EXPLAIN)
62419  sqlite3DbFree(db, p->zExplain);
62420  sqlite3DbFree(db, p->pExplain);
62421#endif
62422}
62423
62424/*
62425** Delete an entire VDBE.
62426*/
62427SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
62428  sqlite3 *db;
62429
62430  if( NEVER(p==0) ) return;
62431  db = p->db;
62432  assert( sqlite3_mutex_held(db->mutex) );
62433  sqlite3VdbeClearObject(db, p);
62434  if( p->pPrev ){
62435    p->pPrev->pNext = p->pNext;
62436  }else{
62437    assert( db->pVdbe==p );
62438    db->pVdbe = p->pNext;
62439  }
62440  if( p->pNext ){
62441    p->pNext->pPrev = p->pPrev;
62442  }
62443  p->magic = VDBE_MAGIC_DEAD;
62444  p->db = 0;
62445  sqlite3DbFree(db, p);
62446}
62447
62448/*
62449** Make sure the cursor p is ready to read or write the row to which it
62450** was last positioned.  Return an error code if an OOM fault or I/O error
62451** prevents us from positioning the cursor to its correct position.
62452**
62453** If a MoveTo operation is pending on the given cursor, then do that
62454** MoveTo now.  If no move is pending, check to see if the row has been
62455** deleted out from under the cursor and if it has, mark the row as
62456** a NULL row.
62457**
62458** If the cursor is already pointing to the correct row and that row has
62459** not been deleted out from under the cursor, then this routine is a no-op.
62460*/
62461SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
62462  if( p->deferredMoveto ){
62463    int res, rc;
62464#ifdef SQLITE_TEST
62465    extern int sqlite3_search_count;
62466#endif
62467    assert( p->isTable );
62468    rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
62469    if( rc ) return rc;
62470    p->lastRowid = p->movetoTarget;
62471    if( res!=0 ) return SQLITE_CORRUPT_BKPT;
62472    p->rowidIsValid = 1;
62473#ifdef SQLITE_TEST
62474    sqlite3_search_count++;
62475#endif
62476    p->deferredMoveto = 0;
62477    p->cacheStatus = CACHE_STALE;
62478  }else if( ALWAYS(p->pCursor) ){
62479    int hasMoved;
62480    int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
62481    if( rc ) return rc;
62482    if( hasMoved ){
62483      p->cacheStatus = CACHE_STALE;
62484      p->nullRow = 1;
62485    }
62486  }
62487  return SQLITE_OK;
62488}
62489
62490/*
62491** The following functions:
62492**
62493** sqlite3VdbeSerialType()
62494** sqlite3VdbeSerialTypeLen()
62495** sqlite3VdbeSerialLen()
62496** sqlite3VdbeSerialPut()
62497** sqlite3VdbeSerialGet()
62498**
62499** encapsulate the code that serializes values for storage in SQLite
62500** data and index records. Each serialized value consists of a
62501** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
62502** integer, stored as a varint.
62503**
62504** In an SQLite index record, the serial type is stored directly before
62505** the blob of data that it corresponds to. In a table record, all serial
62506** types are stored at the start of the record, and the blobs of data at
62507** the end. Hence these functions allow the caller to handle the
62508** serial-type and data blob separately.
62509**
62510** The following table describes the various storage classes for data:
62511**
62512**   serial type        bytes of data      type
62513**   --------------     ---------------    ---------------
62514**      0                     0            NULL
62515**      1                     1            signed integer
62516**      2                     2            signed integer
62517**      3                     3            signed integer
62518**      4                     4            signed integer
62519**      5                     6            signed integer
62520**      6                     8            signed integer
62521**      7                     8            IEEE float
62522**      8                     0            Integer constant 0
62523**      9                     0            Integer constant 1
62524**     10,11                               reserved for expansion
62525**    N>=12 and even       (N-12)/2        BLOB
62526**    N>=13 and odd        (N-13)/2        text
62527**
62528** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
62529** of SQLite will not understand those serial types.
62530*/
62531
62532/*
62533** Return the serial-type for the value stored in pMem.
62534*/
62535SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
62536  int flags = pMem->flags;
62537  int n;
62538
62539  if( flags&MEM_Null ){
62540    return 0;
62541  }
62542  if( flags&MEM_Int ){
62543    /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
62544#   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
62545    i64 i = pMem->u.i;
62546    u64 u;
62547    if( i<0 ){
62548      if( i<(-MAX_6BYTE) ) return 6;
62549      /* Previous test prevents:  u = -(-9223372036854775808) */
62550      u = -i;
62551    }else{
62552      u = i;
62553    }
62554    if( u<=127 ){
62555      return ((i&1)==i && file_format>=4) ? 8+(u32)u : 1;
62556    }
62557    if( u<=32767 ) return 2;
62558    if( u<=8388607 ) return 3;
62559    if( u<=2147483647 ) return 4;
62560    if( u<=MAX_6BYTE ) return 5;
62561    return 6;
62562  }
62563  if( flags&MEM_Real ){
62564    return 7;
62565  }
62566  assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
62567  n = pMem->n;
62568  if( flags & MEM_Zero ){
62569    n += pMem->u.nZero;
62570  }
62571  assert( n>=0 );
62572  return ((n*2) + 12 + ((flags&MEM_Str)!=0));
62573}
62574
62575/*
62576** Return the length of the data corresponding to the supplied serial-type.
62577*/
62578SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
62579  if( serial_type>=12 ){
62580    return (serial_type-12)/2;
62581  }else{
62582    static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
62583    return aSize[serial_type];
62584  }
62585}
62586
62587/*
62588** If we are on an architecture with mixed-endian floating
62589** points (ex: ARM7) then swap the lower 4 bytes with the
62590** upper 4 bytes.  Return the result.
62591**
62592** For most architectures, this is a no-op.
62593**
62594** (later):  It is reported to me that the mixed-endian problem
62595** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
62596** that early versions of GCC stored the two words of a 64-bit
62597** float in the wrong order.  And that error has been propagated
62598** ever since.  The blame is not necessarily with GCC, though.
62599** GCC might have just copying the problem from a prior compiler.
62600** I am also told that newer versions of GCC that follow a different
62601** ABI get the byte order right.
62602**
62603** Developers using SQLite on an ARM7 should compile and run their
62604** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
62605** enabled, some asserts below will ensure that the byte order of
62606** floating point values is correct.
62607**
62608** (2007-08-30)  Frank van Vugt has studied this problem closely
62609** and has send his findings to the SQLite developers.  Frank
62610** writes that some Linux kernels offer floating point hardware
62611** emulation that uses only 32-bit mantissas instead of a full
62612** 48-bits as required by the IEEE standard.  (This is the
62613** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
62614** byte swapping becomes very complicated.  To avoid problems,
62615** the necessary byte swapping is carried out using a 64-bit integer
62616** rather than a 64-bit float.  Frank assures us that the code here
62617** works for him.  We, the developers, have no way to independently
62618** verify this, but Frank seems to know what he is talking about
62619** so we trust him.
62620*/
62621#ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
62622static u64 floatSwap(u64 in){
62623  union {
62624    u64 r;
62625    u32 i[2];
62626  } u;
62627  u32 t;
62628
62629  u.r = in;
62630  t = u.i[0];
62631  u.i[0] = u.i[1];
62632  u.i[1] = t;
62633  return u.r;
62634}
62635# define swapMixedEndianFloat(X)  X = floatSwap(X)
62636#else
62637# define swapMixedEndianFloat(X)
62638#endif
62639
62640/*
62641** Write the serialized data blob for the value stored in pMem into
62642** buf. It is assumed that the caller has allocated sufficient space.
62643** Return the number of bytes written.
62644**
62645** nBuf is the amount of space left in buf[].  nBuf must always be
62646** large enough to hold the entire field.  Except, if the field is
62647** a blob with a zero-filled tail, then buf[] might be just the right
62648** size to hold everything except for the zero-filled tail.  If buf[]
62649** is only big enough to hold the non-zero prefix, then only write that
62650** prefix into buf[].  But if buf[] is large enough to hold both the
62651** prefix and the tail then write the prefix and set the tail to all
62652** zeros.
62653**
62654** Return the number of bytes actually written into buf[].  The number
62655** of bytes in the zero-filled tail is included in the return value only
62656** if those bytes were zeroed in buf[].
62657*/
62658SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
62659  u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
62660  u32 len;
62661
62662  /* Integer and Real */
62663  if( serial_type<=7 && serial_type>0 ){
62664    u64 v;
62665    u32 i;
62666    if( serial_type==7 ){
62667      assert( sizeof(v)==sizeof(pMem->r) );
62668      memcpy(&v, &pMem->r, sizeof(v));
62669      swapMixedEndianFloat(v);
62670    }else{
62671      v = pMem->u.i;
62672    }
62673    len = i = sqlite3VdbeSerialTypeLen(serial_type);
62674    assert( len<=(u32)nBuf );
62675    while( i-- ){
62676      buf[i] = (u8)(v&0xFF);
62677      v >>= 8;
62678    }
62679    return len;
62680  }
62681
62682  /* String or blob */
62683  if( serial_type>=12 ){
62684    assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
62685             == (int)sqlite3VdbeSerialTypeLen(serial_type) );
62686    assert( pMem->n<=nBuf );
62687    len = pMem->n;
62688    memcpy(buf, pMem->z, len);
62689    if( pMem->flags & MEM_Zero ){
62690      len += pMem->u.nZero;
62691      assert( nBuf>=0 );
62692      if( len > (u32)nBuf ){
62693        len = (u32)nBuf;
62694      }
62695      memset(&buf[pMem->n], 0, len-pMem->n);
62696    }
62697    return len;
62698  }
62699
62700  /* NULL or constants 0 or 1 */
62701  return 0;
62702}
62703
62704/*
62705** Deserialize the data blob pointed to by buf as serial type serial_type
62706** and store the result in pMem.  Return the number of bytes read.
62707*/
62708SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
62709  const unsigned char *buf,     /* Buffer to deserialize from */
62710  u32 serial_type,              /* Serial type to deserialize */
62711  Mem *pMem                     /* Memory cell to write value into */
62712){
62713  switch( serial_type ){
62714    case 10:   /* Reserved for future use */
62715    case 11:   /* Reserved for future use */
62716    case 0: {  /* NULL */
62717      pMem->flags = MEM_Null;
62718      break;
62719    }
62720    case 1: { /* 1-byte signed integer */
62721      pMem->u.i = (signed char)buf[0];
62722      pMem->flags = MEM_Int;
62723      return 1;
62724    }
62725    case 2: { /* 2-byte signed integer */
62726      pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
62727      pMem->flags = MEM_Int;
62728      return 2;
62729    }
62730    case 3: { /* 3-byte signed integer */
62731      pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
62732      pMem->flags = MEM_Int;
62733      return 3;
62734    }
62735    case 4: { /* 4-byte signed integer */
62736      pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
62737      pMem->flags = MEM_Int;
62738      return 4;
62739    }
62740    case 5: { /* 6-byte signed integer */
62741      u64 x = (((signed char)buf[0])<<8) | buf[1];
62742      u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
62743      x = (x<<32) | y;
62744      pMem->u.i = *(i64*)&x;
62745      pMem->flags = MEM_Int;
62746      return 6;
62747    }
62748    case 6:   /* 8-byte signed integer */
62749    case 7: { /* IEEE floating point */
62750      u64 x;
62751      u32 y;
62752#if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
62753      /* Verify that integers and floating point values use the same
62754      ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
62755      ** defined that 64-bit floating point values really are mixed
62756      ** endian.
62757      */
62758      static const u64 t1 = ((u64)0x3ff00000)<<32;
62759      static const double r1 = 1.0;
62760      u64 t2 = t1;
62761      swapMixedEndianFloat(t2);
62762      assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
62763#endif
62764
62765      x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
62766      y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
62767      x = (x<<32) | y;
62768      if( serial_type==6 ){
62769        pMem->u.i = *(i64*)&x;
62770        pMem->flags = MEM_Int;
62771      }else{
62772        assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
62773        swapMixedEndianFloat(x);
62774        memcpy(&pMem->r, &x, sizeof(x));
62775        pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
62776      }
62777      return 8;
62778    }
62779    case 8:    /* Integer 0 */
62780    case 9: {  /* Integer 1 */
62781      pMem->u.i = serial_type-8;
62782      pMem->flags = MEM_Int;
62783      return 0;
62784    }
62785    default: {
62786      u32 len = (serial_type-12)/2;
62787      pMem->z = (char *)buf;
62788      pMem->n = len;
62789      pMem->xDel = 0;
62790      if( serial_type&0x01 ){
62791        pMem->flags = MEM_Str | MEM_Ephem;
62792      }else{
62793        pMem->flags = MEM_Blob | MEM_Ephem;
62794      }
62795      return len;
62796    }
62797  }
62798  return 0;
62799}
62800
62801/*
62802** This routine is used to allocate sufficient space for an UnpackedRecord
62803** structure large enough to be used with sqlite3VdbeRecordUnpack() if
62804** the first argument is a pointer to KeyInfo structure pKeyInfo.
62805**
62806** The space is either allocated using sqlite3DbMallocRaw() or from within
62807** the unaligned buffer passed via the second and third arguments (presumably
62808** stack space). If the former, then *ppFree is set to a pointer that should
62809** be eventually freed by the caller using sqlite3DbFree(). Or, if the
62810** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
62811** before returning.
62812**
62813** If an OOM error occurs, NULL is returned.
62814*/
62815SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
62816  KeyInfo *pKeyInfo,              /* Description of the record */
62817  char *pSpace,                   /* Unaligned space available */
62818  int szSpace,                    /* Size of pSpace[] in bytes */
62819  char **ppFree                   /* OUT: Caller should free this pointer */
62820){
62821  UnpackedRecord *p;              /* Unpacked record to return */
62822  int nOff;                       /* Increment pSpace by nOff to align it */
62823  int nByte;                      /* Number of bytes required for *p */
62824
62825  /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
62826  ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
62827  ** it by.  If pSpace is already 8-byte aligned, nOff should be zero.
62828  */
62829  nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
62830  nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
62831  if( nByte>szSpace+nOff ){
62832    p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
62833    *ppFree = (char *)p;
62834    if( !p ) return 0;
62835  }else{
62836    p = (UnpackedRecord*)&pSpace[nOff];
62837    *ppFree = 0;
62838  }
62839
62840  p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
62841  assert( pKeyInfo->aSortOrder!=0 );
62842  p->pKeyInfo = pKeyInfo;
62843  p->nField = pKeyInfo->nField + 1;
62844  return p;
62845}
62846
62847/*
62848** Given the nKey-byte encoding of a record in pKey[], populate the
62849** UnpackedRecord structure indicated by the fourth argument with the
62850** contents of the decoded record.
62851*/
62852SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
62853  KeyInfo *pKeyInfo,     /* Information about the record format */
62854  int nKey,              /* Size of the binary record */
62855  const void *pKey,      /* The binary record */
62856  UnpackedRecord *p      /* Populate this structure before returning. */
62857){
62858  const unsigned char *aKey = (const unsigned char *)pKey;
62859  int d;
62860  u32 idx;                        /* Offset in aKey[] to read from */
62861  u16 u;                          /* Unsigned loop counter */
62862  u32 szHdr;
62863  Mem *pMem = p->aMem;
62864
62865  p->flags = 0;
62866  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
62867  idx = getVarint32(aKey, szHdr);
62868  d = szHdr;
62869  u = 0;
62870  while( idx<szHdr && u<p->nField && d<=nKey ){
62871    u32 serial_type;
62872
62873    idx += getVarint32(&aKey[idx], serial_type);
62874    pMem->enc = pKeyInfo->enc;
62875    pMem->db = pKeyInfo->db;
62876    /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
62877    pMem->zMalloc = 0;
62878    d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
62879    pMem++;
62880    u++;
62881  }
62882  assert( u<=pKeyInfo->nField + 1 );
62883  p->nField = u;
62884}
62885
62886/*
62887** This function compares the two table rows or index records
62888** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
62889** or positive integer if key1 is less than, equal to or
62890** greater than key2.  The {nKey1, pKey1} key must be a blob
62891** created by th OP_MakeRecord opcode of the VDBE.  The pPKey2
62892** key must be a parsed key such as obtained from
62893** sqlite3VdbeParseRecord.
62894**
62895** Key1 and Key2 do not have to contain the same number of fields.
62896** The key with fewer fields is usually compares less than the
62897** longer key.  However if the UNPACKED_INCRKEY flags in pPKey2 is set
62898** and the common prefixes are equal, then key1 is less than key2.
62899** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
62900** equal, then the keys are considered to be equal and
62901** the parts beyond the common prefix are ignored.
62902*/
62903SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
62904  int nKey1, const void *pKey1, /* Left key */
62905  UnpackedRecord *pPKey2        /* Right key */
62906){
62907  int d1;            /* Offset into aKey[] of next data element */
62908  u32 idx1;          /* Offset into aKey[] of next header element */
62909  u32 szHdr1;        /* Number of bytes in header */
62910  int i = 0;
62911  int nField;
62912  int rc = 0;
62913  const unsigned char *aKey1 = (const unsigned char *)pKey1;
62914  KeyInfo *pKeyInfo;
62915  Mem mem1;
62916
62917  pKeyInfo = pPKey2->pKeyInfo;
62918  mem1.enc = pKeyInfo->enc;
62919  mem1.db = pKeyInfo->db;
62920  /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
62921  VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
62922
62923  /* Compilers may complain that mem1.u.i is potentially uninitialized.
62924  ** We could initialize it, as shown here, to silence those complaints.
62925  ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
62926  ** the unnecessary initialization has a measurable negative performance
62927  ** impact, since this routine is a very high runner.  And so, we choose
62928  ** to ignore the compiler warnings and leave this variable uninitialized.
62929  */
62930  /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
62931
62932  idx1 = getVarint32(aKey1, szHdr1);
62933  d1 = szHdr1;
62934  nField = pKeyInfo->nField;
62935  assert( pKeyInfo->aSortOrder!=0 );
62936  while( idx1<szHdr1 && i<pPKey2->nField ){
62937    u32 serial_type1;
62938
62939    /* Read the serial types for the next element in each key. */
62940    idx1 += getVarint32( aKey1+idx1, serial_type1 );
62941    if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
62942
62943    /* Extract the values to be compared.
62944    */
62945    d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
62946
62947    /* Do the comparison
62948    */
62949    rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
62950                           i<nField ? pKeyInfo->aColl[i] : 0);
62951    if( rc!=0 ){
62952      assert( mem1.zMalloc==0 );  /* See comment below */
62953
62954      /* Invert the result if we are using DESC sort order. */
62955      if( i<nField && pKeyInfo->aSortOrder[i] ){
62956        rc = -rc;
62957      }
62958
62959      /* If the PREFIX_SEARCH flag is set and all fields except the final
62960      ** rowid field were equal, then clear the PREFIX_SEARCH flag and set
62961      ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
62962      ** This is used by the OP_IsUnique opcode.
62963      */
62964      if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){
62965        assert( idx1==szHdr1 && rc );
62966        assert( mem1.flags & MEM_Int );
62967        pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH;
62968        pPKey2->rowid = mem1.u.i;
62969      }
62970
62971      return rc;
62972    }
62973    i++;
62974  }
62975
62976  /* No memory allocation is ever used on mem1.  Prove this using
62977  ** the following assert().  If the assert() fails, it indicates a
62978  ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
62979  */
62980  assert( mem1.zMalloc==0 );
62981
62982  /* rc==0 here means that one of the keys ran out of fields and
62983  ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
62984  ** flag is set, then break the tie by treating key2 as larger.
62985  ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
62986  ** are considered to be equal.  Otherwise, the longer key is the
62987  ** larger.  As it happens, the pPKey2 will always be the longer
62988  ** if there is a difference.
62989  */
62990  assert( rc==0 );
62991  if( pPKey2->flags & UNPACKED_INCRKEY ){
62992    rc = -1;
62993  }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
62994    /* Leave rc==0 */
62995  }else if( idx1<szHdr1 ){
62996    rc = 1;
62997  }
62998  return rc;
62999}
63000
63001
63002/*
63003** pCur points at an index entry created using the OP_MakeRecord opcode.
63004** Read the rowid (the last field in the record) and store it in *rowid.
63005** Return SQLITE_OK if everything works, or an error code otherwise.
63006**
63007** pCur might be pointing to text obtained from a corrupt database file.
63008** So the content cannot be trusted.  Do appropriate checks on the content.
63009*/
63010SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
63011  i64 nCellKey = 0;
63012  int rc;
63013  u32 szHdr;        /* Size of the header */
63014  u32 typeRowid;    /* Serial type of the rowid */
63015  u32 lenRowid;     /* Size of the rowid */
63016  Mem m, v;
63017
63018  UNUSED_PARAMETER(db);
63019
63020  /* Get the size of the index entry.  Only indices entries of less
63021  ** than 2GiB are support - anything large must be database corruption.
63022  ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
63023  ** this code can safely assume that nCellKey is 32-bits
63024  */
63025  assert( sqlite3BtreeCursorIsValid(pCur) );
63026  VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
63027  assert( rc==SQLITE_OK );     /* pCur is always valid so KeySize cannot fail */
63028  assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
63029
63030  /* Read in the complete content of the index entry */
63031  memset(&m, 0, sizeof(m));
63032  rc = sqlite3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);
63033  if( rc ){
63034    return rc;
63035  }
63036
63037  /* The index entry must begin with a header size */
63038  (void)getVarint32((u8*)m.z, szHdr);
63039  testcase( szHdr==3 );
63040  testcase( szHdr==m.n );
63041  if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
63042    goto idx_rowid_corruption;
63043  }
63044
63045  /* The last field of the index should be an integer - the ROWID.
63046  ** Verify that the last entry really is an integer. */
63047  (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
63048  testcase( typeRowid==1 );
63049  testcase( typeRowid==2 );
63050  testcase( typeRowid==3 );
63051  testcase( typeRowid==4 );
63052  testcase( typeRowid==5 );
63053  testcase( typeRowid==6 );
63054  testcase( typeRowid==8 );
63055  testcase( typeRowid==9 );
63056  if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
63057    goto idx_rowid_corruption;
63058  }
63059  lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
63060  testcase( (u32)m.n==szHdr+lenRowid );
63061  if( unlikely((u32)m.n<szHdr+lenRowid) ){
63062    goto idx_rowid_corruption;
63063  }
63064
63065  /* Fetch the integer off the end of the index record */
63066  sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
63067  *rowid = v.u.i;
63068  sqlite3VdbeMemRelease(&m);
63069  return SQLITE_OK;
63070
63071  /* Jump here if database corruption is detected after m has been
63072  ** allocated.  Free the m object and return SQLITE_CORRUPT. */
63073idx_rowid_corruption:
63074  testcase( m.zMalloc!=0 );
63075  sqlite3VdbeMemRelease(&m);
63076  return SQLITE_CORRUPT_BKPT;
63077}
63078
63079/*
63080** Compare the key of the index entry that cursor pC is pointing to against
63081** the key string in pUnpacked.  Write into *pRes a number
63082** that is negative, zero, or positive if pC is less than, equal to,
63083** or greater than pUnpacked.  Return SQLITE_OK on success.
63084**
63085** pUnpacked is either created without a rowid or is truncated so that it
63086** omits the rowid at the end.  The rowid at the end of the index entry
63087** is ignored as well.  Hence, this routine only compares the prefixes
63088** of the keys prior to the final rowid, not the entire key.
63089*/
63090SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
63091  VdbeCursor *pC,             /* The cursor to compare against */
63092  UnpackedRecord *pUnpacked,  /* Unpacked version of key to compare against */
63093  int *res                    /* Write the comparison result here */
63094){
63095  i64 nCellKey = 0;
63096  int rc;
63097  BtCursor *pCur = pC->pCursor;
63098  Mem m;
63099
63100  assert( sqlite3BtreeCursorIsValid(pCur) );
63101  VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
63102  assert( rc==SQLITE_OK );    /* pCur is always valid so KeySize cannot fail */
63103  /* nCellKey will always be between 0 and 0xffffffff because of the say
63104  ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
63105  if( nCellKey<=0 || nCellKey>0x7fffffff ){
63106    *res = 0;
63107    return SQLITE_CORRUPT_BKPT;
63108  }
63109  memset(&m, 0, sizeof(m));
63110  rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);
63111  if( rc ){
63112    return rc;
63113  }
63114  assert( pUnpacked->flags & UNPACKED_PREFIX_MATCH );
63115  *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
63116  sqlite3VdbeMemRelease(&m);
63117  return SQLITE_OK;
63118}
63119
63120/*
63121** This routine sets the value to be returned by subsequent calls to
63122** sqlite3_changes() on the database handle 'db'.
63123*/
63124SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
63125  assert( sqlite3_mutex_held(db->mutex) );
63126  db->nChange = nChange;
63127  db->nTotalChange += nChange;
63128}
63129
63130/*
63131** Set a flag in the vdbe to update the change counter when it is finalised
63132** or reset.
63133*/
63134SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
63135  v->changeCntOn = 1;
63136}
63137
63138/*
63139** Mark every prepared statement associated with a database connection
63140** as expired.
63141**
63142** An expired statement means that recompilation of the statement is
63143** recommend.  Statements expire when things happen that make their
63144** programs obsolete.  Removing user-defined functions or collating
63145** sequences, or changing an authorization function are the types of
63146** things that make prepared statements obsolete.
63147*/
63148SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
63149  Vdbe *p;
63150  for(p = db->pVdbe; p; p=p->pNext){
63151    p->expired = 1;
63152  }
63153}
63154
63155/*
63156** Return the database associated with the Vdbe.
63157*/
63158SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
63159  return v->db;
63160}
63161
63162/*
63163** Return a pointer to an sqlite3_value structure containing the value bound
63164** parameter iVar of VM v. Except, if the value is an SQL NULL, return
63165** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
63166** constants) to the value before returning it.
63167**
63168** The returned value must be freed by the caller using sqlite3ValueFree().
63169*/
63170SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe *v, int iVar, u8 aff){
63171  assert( iVar>0 );
63172  if( v ){
63173    Mem *pMem = &v->aVar[iVar-1];
63174    if( 0==(pMem->flags & MEM_Null) ){
63175      sqlite3_value *pRet = sqlite3ValueNew(v->db);
63176      if( pRet ){
63177        sqlite3VdbeMemCopy((Mem *)pRet, pMem);
63178        sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
63179        sqlite3VdbeMemStoreType((Mem *)pRet);
63180      }
63181      return pRet;
63182    }
63183  }
63184  return 0;
63185}
63186
63187/*
63188** Configure SQL variable iVar so that binding a new value to it signals
63189** to sqlite3_reoptimize() that re-preparing the statement may result
63190** in a better query plan.
63191*/
63192SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
63193  assert( iVar>0 );
63194  if( iVar>32 ){
63195    v->expmask = 0xffffffff;
63196  }else{
63197    v->expmask |= ((u32)1 << (iVar-1));
63198  }
63199}
63200
63201/************** End of vdbeaux.c *********************************************/
63202/************** Begin file vdbeapi.c *****************************************/
63203/*
63204** 2004 May 26
63205**
63206** The author disclaims copyright to this source code.  In place of
63207** a legal notice, here is a blessing:
63208**
63209**    May you do good and not evil.
63210**    May you find forgiveness for yourself and forgive others.
63211**    May you share freely, never taking more than you give.
63212**
63213*************************************************************************
63214**
63215** This file contains code use to implement APIs that are part of the
63216** VDBE.
63217*/
63218
63219#ifndef SQLITE_OMIT_DEPRECATED
63220/*
63221** Return TRUE (non-zero) of the statement supplied as an argument needs
63222** to be recompiled.  A statement needs to be recompiled whenever the
63223** execution environment changes in a way that would alter the program
63224** that sqlite3_prepare() generates.  For example, if new functions or
63225** collating sequences are registered or if an authorizer function is
63226** added or changed.
63227*/
63228SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
63229  Vdbe *p = (Vdbe*)pStmt;
63230  return p==0 || p->expired;
63231}
63232#endif
63233
63234/*
63235** Check on a Vdbe to make sure it has not been finalized.  Log
63236** an error and return true if it has been finalized (or is otherwise
63237** invalid).  Return false if it is ok.
63238*/
63239static int vdbeSafety(Vdbe *p){
63240  if( p->db==0 ){
63241    sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
63242    return 1;
63243  }else{
63244    return 0;
63245  }
63246}
63247static int vdbeSafetyNotNull(Vdbe *p){
63248  if( p==0 ){
63249    sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
63250    return 1;
63251  }else{
63252    return vdbeSafety(p);
63253  }
63254}
63255
63256/*
63257** The following routine destroys a virtual machine that is created by
63258** the sqlite3_compile() routine. The integer returned is an SQLITE_
63259** success/failure code that describes the result of executing the virtual
63260** machine.
63261**
63262** This routine sets the error code and string returned by
63263** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
63264*/
63265SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
63266  int rc;
63267  if( pStmt==0 ){
63268    /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
63269    ** pointer is a harmless no-op. */
63270    rc = SQLITE_OK;
63271  }else{
63272    Vdbe *v = (Vdbe*)pStmt;
63273    sqlite3 *db = v->db;
63274    if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
63275    sqlite3_mutex_enter(db->mutex);
63276    rc = sqlite3VdbeFinalize(v);
63277    rc = sqlite3ApiExit(db, rc);
63278    sqlite3LeaveMutexAndCloseZombie(db);
63279  }
63280  return rc;
63281}
63282
63283/*
63284** Terminate the current execution of an SQL statement and reset it
63285** back to its starting state so that it can be reused. A success code from
63286** the prior execution is returned.
63287**
63288** This routine sets the error code and string returned by
63289** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
63290*/
63291SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
63292  int rc;
63293  if( pStmt==0 ){
63294    rc = SQLITE_OK;
63295  }else{
63296    Vdbe *v = (Vdbe*)pStmt;
63297    sqlite3_mutex_enter(v->db->mutex);
63298    rc = sqlite3VdbeReset(v);
63299    sqlite3VdbeRewind(v);
63300    assert( (rc & (v->db->errMask))==rc );
63301    rc = sqlite3ApiExit(v->db, rc);
63302    sqlite3_mutex_leave(v->db->mutex);
63303  }
63304  return rc;
63305}
63306
63307/*
63308** Set all the parameters in the compiled SQL statement to NULL.
63309*/
63310SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
63311  int i;
63312  int rc = SQLITE_OK;
63313  Vdbe *p = (Vdbe*)pStmt;
63314#if SQLITE_THREADSAFE
63315  sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
63316#endif
63317  sqlite3_mutex_enter(mutex);
63318  for(i=0; i<p->nVar; i++){
63319    sqlite3VdbeMemRelease(&p->aVar[i]);
63320    p->aVar[i].flags = MEM_Null;
63321  }
63322  if( p->isPrepareV2 && p->expmask ){
63323    p->expired = 1;
63324  }
63325  sqlite3_mutex_leave(mutex);
63326  return rc;
63327}
63328
63329
63330/**************************** sqlite3_value_  *******************************
63331** The following routines extract information from a Mem or sqlite3_value
63332** structure.
63333*/
63334SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
63335  Mem *p = (Mem*)pVal;
63336  if( p->flags & (MEM_Blob|MEM_Str) ){
63337    sqlite3VdbeMemExpandBlob(p);
63338    p->flags &= ~MEM_Str;
63339    p->flags |= MEM_Blob;
63340    return p->n ? p->z : 0;
63341  }else{
63342    return sqlite3_value_text(pVal);
63343  }
63344}
63345SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
63346  return sqlite3ValueBytes(pVal, SQLITE_UTF8);
63347}
63348SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
63349  return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
63350}
63351SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
63352  return sqlite3VdbeRealValue((Mem*)pVal);
63353}
63354SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
63355  return (int)sqlite3VdbeIntValue((Mem*)pVal);
63356}
63357SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
63358  return sqlite3VdbeIntValue((Mem*)pVal);
63359}
63360SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
63361  return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
63362}
63363#ifndef SQLITE_OMIT_UTF16
63364SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
63365  return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
63366}
63367SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
63368  return sqlite3ValueText(pVal, SQLITE_UTF16BE);
63369}
63370SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
63371  return sqlite3ValueText(pVal, SQLITE_UTF16LE);
63372}
63373#endif /* SQLITE_OMIT_UTF16 */
63374SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
63375  return pVal->type;
63376}
63377
63378/**************************** sqlite3_result_  *******************************
63379** The following routines are used by user-defined functions to specify
63380** the function result.
63381**
63382** The setStrOrError() funtion calls sqlite3VdbeMemSetStr() to store the
63383** result as a string or blob but if the string or blob is too large, it
63384** then sets the error code to SQLITE_TOOBIG
63385*/
63386static void setResultStrOrError(
63387  sqlite3_context *pCtx,  /* Function context */
63388  const char *z,          /* String pointer */
63389  int n,                  /* Bytes in string, or negative */
63390  u8 enc,                 /* Encoding of z.  0 for BLOBs */
63391  void (*xDel)(void*)     /* Destructor function */
63392){
63393  if( sqlite3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){
63394    sqlite3_result_error_toobig(pCtx);
63395  }
63396}
63397SQLITE_API void sqlite3_result_blob(
63398  sqlite3_context *pCtx,
63399  const void *z,
63400  int n,
63401  void (*xDel)(void *)
63402){
63403  assert( n>=0 );
63404  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63405  setResultStrOrError(pCtx, z, n, 0, xDel);
63406}
63407SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
63408  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63409  sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
63410}
63411SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
63412  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63413  pCtx->isError = SQLITE_ERROR;
63414  sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
63415}
63416#ifndef SQLITE_OMIT_UTF16
63417SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
63418  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63419  pCtx->isError = SQLITE_ERROR;
63420  sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
63421}
63422#endif
63423SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
63424  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63425  sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
63426}
63427SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
63428  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63429  sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
63430}
63431SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
63432  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63433  sqlite3VdbeMemSetNull(&pCtx->s);
63434}
63435SQLITE_API void sqlite3_result_text(
63436  sqlite3_context *pCtx,
63437  const char *z,
63438  int n,
63439  void (*xDel)(void *)
63440){
63441  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63442  setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
63443}
63444#ifndef SQLITE_OMIT_UTF16
63445SQLITE_API void sqlite3_result_text16(
63446  sqlite3_context *pCtx,
63447  const void *z,
63448  int n,
63449  void (*xDel)(void *)
63450){
63451  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63452  setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
63453}
63454SQLITE_API void sqlite3_result_text16be(
63455  sqlite3_context *pCtx,
63456  const void *z,
63457  int n,
63458  void (*xDel)(void *)
63459){
63460  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63461  setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
63462}
63463SQLITE_API void sqlite3_result_text16le(
63464  sqlite3_context *pCtx,
63465  const void *z,
63466  int n,
63467  void (*xDel)(void *)
63468){
63469  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63470  setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
63471}
63472#endif /* SQLITE_OMIT_UTF16 */
63473SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
63474  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63475  sqlite3VdbeMemCopy(&pCtx->s, pValue);
63476}
63477SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
63478  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63479  sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
63480}
63481SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
63482  pCtx->isError = errCode;
63483  if( pCtx->s.flags & MEM_Null ){
63484    sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1,
63485                         SQLITE_UTF8, SQLITE_STATIC);
63486  }
63487}
63488
63489/* Force an SQLITE_TOOBIG error. */
63490SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
63491  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63492  pCtx->isError = SQLITE_TOOBIG;
63493  sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1,
63494                       SQLITE_UTF8, SQLITE_STATIC);
63495}
63496
63497/* An SQLITE_NOMEM error. */
63498SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
63499  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63500  sqlite3VdbeMemSetNull(&pCtx->s);
63501  pCtx->isError = SQLITE_NOMEM;
63502  pCtx->s.db->mallocFailed = 1;
63503}
63504
63505/*
63506** This function is called after a transaction has been committed. It
63507** invokes callbacks registered with sqlite3_wal_hook() as required.
63508*/
63509static int doWalCallbacks(sqlite3 *db){
63510  int rc = SQLITE_OK;
63511#ifndef SQLITE_OMIT_WAL
63512  int i;
63513  for(i=0; i<db->nDb; i++){
63514    Btree *pBt = db->aDb[i].pBt;
63515    if( pBt ){
63516      int nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
63517      if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
63518        rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
63519      }
63520    }
63521  }
63522#endif
63523  return rc;
63524}
63525
63526/*
63527** Execute the statement pStmt, either until a row of data is ready, the
63528** statement is completely executed or an error occurs.
63529**
63530** This routine implements the bulk of the logic behind the sqlite_step()
63531** API.  The only thing omitted is the automatic recompile if a
63532** schema change has occurred.  That detail is handled by the
63533** outer sqlite3_step() wrapper procedure.
63534*/
63535static int sqlite3Step(Vdbe *p){
63536  sqlite3 *db;
63537  int rc;
63538
63539  assert(p);
63540  if( p->magic!=VDBE_MAGIC_RUN ){
63541    /* We used to require that sqlite3_reset() be called before retrying
63542    ** sqlite3_step() after any error or after SQLITE_DONE.  But beginning
63543    ** with version 3.7.0, we changed this so that sqlite3_reset() would
63544    ** be called automatically instead of throwing the SQLITE_MISUSE error.
63545    ** This "automatic-reset" change is not technically an incompatibility,
63546    ** since any application that receives an SQLITE_MISUSE is broken by
63547    ** definition.
63548    **
63549    ** Nevertheless, some published applications that were originally written
63550    ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
63551    ** returns, and those were broken by the automatic-reset change.  As a
63552    ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
63553    ** legacy behavior of returning SQLITE_MISUSE for cases where the
63554    ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
63555    ** or SQLITE_BUSY error.
63556    */
63557#ifdef SQLITE_OMIT_AUTORESET
63558    if( p->rc==SQLITE_BUSY || p->rc==SQLITE_LOCKED ){
63559      sqlite3_reset((sqlite3_stmt*)p);
63560    }else{
63561      return SQLITE_MISUSE_BKPT;
63562    }
63563#else
63564    sqlite3_reset((sqlite3_stmt*)p);
63565#endif
63566  }
63567
63568  /* Check that malloc() has not failed. If it has, return early. */
63569  db = p->db;
63570  if( db->mallocFailed ){
63571    p->rc = SQLITE_NOMEM;
63572    return SQLITE_NOMEM;
63573  }
63574
63575  if( p->pc<=0 && p->expired ){
63576    p->rc = SQLITE_SCHEMA;
63577    rc = SQLITE_ERROR;
63578    goto end_of_step;
63579  }
63580  if( p->pc<0 ){
63581    /* If there are no other statements currently running, then
63582    ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
63583    ** from interrupting a statement that has not yet started.
63584    */
63585    if( db->activeVdbeCnt==0 ){
63586      db->u1.isInterrupted = 0;
63587    }
63588
63589    assert( db->writeVdbeCnt>0 || db->autoCommit==0 || db->nDeferredCons==0 );
63590
63591#ifndef SQLITE_OMIT_TRACE
63592    if( db->xProfile && !db->init.busy ){
63593      sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
63594    }
63595#endif
63596
63597    db->activeVdbeCnt++;
63598    if( p->readOnly==0 ) db->writeVdbeCnt++;
63599    p->pc = 0;
63600  }
63601#ifndef SQLITE_OMIT_EXPLAIN
63602  if( p->explain ){
63603    rc = sqlite3VdbeList(p);
63604  }else
63605#endif /* SQLITE_OMIT_EXPLAIN */
63606  {
63607    db->vdbeExecCnt++;
63608    rc = sqlite3VdbeExec(p);
63609    db->vdbeExecCnt--;
63610  }
63611
63612#ifndef SQLITE_OMIT_TRACE
63613  /* Invoke the profile callback if there is one
63614  */
63615  if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
63616    sqlite3_int64 iNow;
63617    sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
63618    db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
63619  }
63620#endif
63621
63622  if( rc==SQLITE_DONE ){
63623    assert( p->rc==SQLITE_OK );
63624    p->rc = doWalCallbacks(db);
63625    if( p->rc!=SQLITE_OK ){
63626      rc = SQLITE_ERROR;
63627    }
63628  }
63629
63630  db->errCode = rc;
63631  if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
63632    p->rc = SQLITE_NOMEM;
63633  }
63634end_of_step:
63635  /* At this point local variable rc holds the value that should be
63636  ** returned if this statement was compiled using the legacy
63637  ** sqlite3_prepare() interface. According to the docs, this can only
63638  ** be one of the values in the first assert() below. Variable p->rc
63639  ** contains the value that would be returned if sqlite3_finalize()
63640  ** were called on statement p.
63641  */
63642  assert( rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR
63643       || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
63644  );
63645  assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
63646  if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
63647    /* If this statement was prepared using sqlite3_prepare_v2(), and an
63648    ** error has occurred, then return the error code in p->rc to the
63649    ** caller. Set the error code in the database handle to the same value.
63650    */
63651    rc = sqlite3VdbeTransferError(p);
63652  }
63653  return (rc&db->errMask);
63654}
63655
63656/*
63657** This is the top-level implementation of sqlite3_step().  Call
63658** sqlite3Step() to do most of the work.  If a schema error occurs,
63659** call sqlite3Reprepare() and try again.
63660*/
63661SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
63662  int rc = SQLITE_OK;      /* Result from sqlite3Step() */
63663  int rc2 = SQLITE_OK;     /* Result from sqlite3Reprepare() */
63664  Vdbe *v = (Vdbe*)pStmt;  /* the prepared statement */
63665  int cnt = 0;             /* Counter to prevent infinite loop of reprepares */
63666  sqlite3 *db;             /* The database connection */
63667
63668  if( vdbeSafetyNotNull(v) ){
63669    return SQLITE_MISUSE_BKPT;
63670  }
63671  db = v->db;
63672  sqlite3_mutex_enter(db->mutex);
63673  v->doingRerun = 0;
63674  while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
63675         && cnt++ < SQLITE_MAX_SCHEMA_RETRY
63676         && (rc2 = rc = sqlite3Reprepare(v))==SQLITE_OK ){
63677    sqlite3_reset(pStmt);
63678    v->doingRerun = 1;
63679    assert( v->expired==0 );
63680  }
63681  if( rc2!=SQLITE_OK && ALWAYS(v->isPrepareV2) && ALWAYS(db->pErr) ){
63682    /* This case occurs after failing to recompile an sql statement.
63683    ** The error message from the SQL compiler has already been loaded
63684    ** into the database handle. This block copies the error message
63685    ** from the database handle into the statement and sets the statement
63686    ** program counter to 0 to ensure that when the statement is
63687    ** finalized or reset the parser error message is available via
63688    ** sqlite3_errmsg() and sqlite3_errcode().
63689    */
63690    const char *zErr = (const char *)sqlite3_value_text(db->pErr);
63691    sqlite3DbFree(db, v->zErrMsg);
63692    if( !db->mallocFailed ){
63693      v->zErrMsg = sqlite3DbStrDup(db, zErr);
63694      v->rc = rc2;
63695    } else {
63696      v->zErrMsg = 0;
63697      v->rc = rc = SQLITE_NOMEM;
63698    }
63699  }
63700  rc = sqlite3ApiExit(db, rc);
63701  sqlite3_mutex_leave(db->mutex);
63702  return rc;
63703}
63704
63705/*
63706** Extract the user data from a sqlite3_context structure and return a
63707** pointer to it.
63708*/
63709SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
63710  assert( p && p->pFunc );
63711  return p->pFunc->pUserData;
63712}
63713
63714/*
63715** Extract the user data from a sqlite3_context structure and return a
63716** pointer to it.
63717**
63718** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
63719** returns a copy of the pointer to the database connection (the 1st
63720** parameter) of the sqlite3_create_function() and
63721** sqlite3_create_function16() routines that originally registered the
63722** application defined function.
63723*/
63724SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
63725  assert( p && p->pFunc );
63726  return p->s.db;
63727}
63728
63729/*
63730** The following is the implementation of an SQL function that always
63731** fails with an error message stating that the function is used in the
63732** wrong context.  The sqlite3_overload_function() API might construct
63733** SQL function that use this routine so that the functions will exist
63734** for name resolution but are actually overloaded by the xFindFunction
63735** method of virtual tables.
63736*/
63737SQLITE_PRIVATE void sqlite3InvalidFunction(
63738  sqlite3_context *context,  /* The function calling context */
63739  int NotUsed,               /* Number of arguments to the function */
63740  sqlite3_value **NotUsed2   /* Value of each argument */
63741){
63742  const char *zName = context->pFunc->zName;
63743  char *zErr;
63744  UNUSED_PARAMETER2(NotUsed, NotUsed2);
63745  zErr = sqlite3_mprintf(
63746      "unable to use function %s in the requested context", zName);
63747  sqlite3_result_error(context, zErr, -1);
63748  sqlite3_free(zErr);
63749}
63750
63751/*
63752** Allocate or return the aggregate context for a user function.  A new
63753** context is allocated on the first call.  Subsequent calls return the
63754** same context that was returned on prior calls.
63755*/
63756SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
63757  Mem *pMem;
63758  assert( p && p->pFunc && p->pFunc->xStep );
63759  assert( sqlite3_mutex_held(p->s.db->mutex) );
63760  pMem = p->pMem;
63761  testcase( nByte<0 );
63762  if( (pMem->flags & MEM_Agg)==0 ){
63763    if( nByte<=0 ){
63764      sqlite3VdbeMemReleaseExternal(pMem);
63765      pMem->flags = MEM_Null;
63766      pMem->z = 0;
63767    }else{
63768      sqlite3VdbeMemGrow(pMem, nByte, 0);
63769      pMem->flags = MEM_Agg;
63770      pMem->u.pDef = p->pFunc;
63771      if( pMem->z ){
63772        memset(pMem->z, 0, nByte);
63773      }
63774    }
63775  }
63776  return (void*)pMem->z;
63777}
63778
63779/*
63780** Return the auxilary data pointer, if any, for the iArg'th argument to
63781** the user-function defined by pCtx.
63782*/
63783SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
63784  VdbeFunc *pVdbeFunc;
63785
63786  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63787  pVdbeFunc = pCtx->pVdbeFunc;
63788  if( !pVdbeFunc || iArg>=pVdbeFunc->nAux || iArg<0 ){
63789    return 0;
63790  }
63791  return pVdbeFunc->apAux[iArg].pAux;
63792}
63793
63794/*
63795** Set the auxilary data pointer and delete function, for the iArg'th
63796** argument to the user-function defined by pCtx. Any previous value is
63797** deleted by calling the delete function specified when it was set.
63798*/
63799SQLITE_API void sqlite3_set_auxdata(
63800  sqlite3_context *pCtx,
63801  int iArg,
63802  void *pAux,
63803  void (*xDelete)(void*)
63804){
63805  struct AuxData *pAuxData;
63806  VdbeFunc *pVdbeFunc;
63807  if( iArg<0 ) goto failed;
63808
63809  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63810  pVdbeFunc = pCtx->pVdbeFunc;
63811  if( !pVdbeFunc || pVdbeFunc->nAux<=iArg ){
63812    int nAux = (pVdbeFunc ? pVdbeFunc->nAux : 0);
63813    int nMalloc = sizeof(VdbeFunc) + sizeof(struct AuxData)*iArg;
63814    pVdbeFunc = sqlite3DbRealloc(pCtx->s.db, pVdbeFunc, nMalloc);
63815    if( !pVdbeFunc ){
63816      goto failed;
63817    }
63818    pCtx->pVdbeFunc = pVdbeFunc;
63819    memset(&pVdbeFunc->apAux[nAux], 0, sizeof(struct AuxData)*(iArg+1-nAux));
63820    pVdbeFunc->nAux = iArg+1;
63821    pVdbeFunc->pFunc = pCtx->pFunc;
63822  }
63823
63824  pAuxData = &pVdbeFunc->apAux[iArg];
63825  if( pAuxData->pAux && pAuxData->xDelete ){
63826    pAuxData->xDelete(pAuxData->pAux);
63827  }
63828  pAuxData->pAux = pAux;
63829  pAuxData->xDelete = xDelete;
63830  return;
63831
63832failed:
63833  if( xDelete ){
63834    xDelete(pAux);
63835  }
63836}
63837
63838#ifndef SQLITE_OMIT_DEPRECATED
63839/*
63840** Return the number of times the Step function of a aggregate has been
63841** called.
63842**
63843** This function is deprecated.  Do not use it for new code.  It is
63844** provide only to avoid breaking legacy code.  New aggregate function
63845** implementations should keep their own counts within their aggregate
63846** context.
63847*/
63848SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
63849  assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
63850  return p->pMem->n;
63851}
63852#endif
63853
63854/*
63855** Return the number of columns in the result set for the statement pStmt.
63856*/
63857SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
63858  Vdbe *pVm = (Vdbe *)pStmt;
63859  return pVm ? pVm->nResColumn : 0;
63860}
63861
63862/*
63863** Return the number of values available from the current row of the
63864** currently executing statement pStmt.
63865*/
63866SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
63867  Vdbe *pVm = (Vdbe *)pStmt;
63868  if( pVm==0 || pVm->pResultSet==0 ) return 0;
63869  return pVm->nResColumn;
63870}
63871
63872
63873/*
63874** Check to see if column iCol of the given statement is valid.  If
63875** it is, return a pointer to the Mem for the value of that column.
63876** If iCol is not valid, return a pointer to a Mem which has a value
63877** of NULL.
63878*/
63879static Mem *columnMem(sqlite3_stmt *pStmt, int i){
63880  Vdbe *pVm;
63881  Mem *pOut;
63882
63883  pVm = (Vdbe *)pStmt;
63884  if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
63885    sqlite3_mutex_enter(pVm->db->mutex);
63886    pOut = &pVm->pResultSet[i];
63887  }else{
63888    /* If the value passed as the second argument is out of range, return
63889    ** a pointer to the following static Mem object which contains the
63890    ** value SQL NULL. Even though the Mem structure contains an element
63891    ** of type i64, on certain architectures (x86) with certain compiler
63892    ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
63893    ** instead of an 8-byte one. This all works fine, except that when
63894    ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
63895    ** that a Mem structure is located on an 8-byte boundary. To prevent
63896    ** these assert()s from failing, when building with SQLITE_DEBUG defined
63897    ** using gcc, we force nullMem to be 8-byte aligned using the magical
63898    ** __attribute__((aligned(8))) macro.  */
63899    static const Mem nullMem
63900#if defined(SQLITE_DEBUG) && defined(__GNUC__)
63901      __attribute__((aligned(8)))
63902#endif
63903      = {0, "", (double)0, {0}, 0, MEM_Null, SQLITE_NULL, 0,
63904#ifdef SQLITE_DEBUG
63905         0, 0,  /* pScopyFrom, pFiller */
63906#endif
63907         0, 0 };
63908
63909    if( pVm && ALWAYS(pVm->db) ){
63910      sqlite3_mutex_enter(pVm->db->mutex);
63911      sqlite3Error(pVm->db, SQLITE_RANGE, 0);
63912    }
63913    pOut = (Mem*)&nullMem;
63914  }
63915  return pOut;
63916}
63917
63918/*
63919** This function is called after invoking an sqlite3_value_XXX function on a
63920** column value (i.e. a value returned by evaluating an SQL expression in the
63921** select list of a SELECT statement) that may cause a malloc() failure. If
63922** malloc() has failed, the threads mallocFailed flag is cleared and the result
63923** code of statement pStmt set to SQLITE_NOMEM.
63924**
63925** Specifically, this is called from within:
63926**
63927**     sqlite3_column_int()
63928**     sqlite3_column_int64()
63929**     sqlite3_column_text()
63930**     sqlite3_column_text16()
63931**     sqlite3_column_real()
63932**     sqlite3_column_bytes()
63933**     sqlite3_column_bytes16()
63934**     sqiite3_column_blob()
63935*/
63936static void columnMallocFailure(sqlite3_stmt *pStmt)
63937{
63938  /* If malloc() failed during an encoding conversion within an
63939  ** sqlite3_column_XXX API, then set the return code of the statement to
63940  ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
63941  ** and _finalize() will return NOMEM.
63942  */
63943  Vdbe *p = (Vdbe *)pStmt;
63944  if( p ){
63945    p->rc = sqlite3ApiExit(p->db, p->rc);
63946    sqlite3_mutex_leave(p->db->mutex);
63947  }
63948}
63949
63950/**************************** sqlite3_column_  *******************************
63951** The following routines are used to access elements of the current row
63952** in the result set.
63953*/
63954SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
63955  const void *val;
63956  val = sqlite3_value_blob( columnMem(pStmt,i) );
63957  /* Even though there is no encoding conversion, value_blob() might
63958  ** need to call malloc() to expand the result of a zeroblob()
63959  ** expression.
63960  */
63961  columnMallocFailure(pStmt);
63962  return val;
63963}
63964SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
63965  int val = sqlite3_value_bytes( columnMem(pStmt,i) );
63966  columnMallocFailure(pStmt);
63967  return val;
63968}
63969SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
63970  int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
63971  columnMallocFailure(pStmt);
63972  return val;
63973}
63974SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
63975  double val = sqlite3_value_double( columnMem(pStmt,i) );
63976  columnMallocFailure(pStmt);
63977  return val;
63978}
63979SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
63980  int val = sqlite3_value_int( columnMem(pStmt,i) );
63981  columnMallocFailure(pStmt);
63982  return val;
63983}
63984SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
63985  sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
63986  columnMallocFailure(pStmt);
63987  return val;
63988}
63989SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
63990  const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
63991  columnMallocFailure(pStmt);
63992  return val;
63993}
63994SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
63995  Mem *pOut = columnMem(pStmt, i);
63996  if( pOut->flags&MEM_Static ){
63997    pOut->flags &= ~MEM_Static;
63998    pOut->flags |= MEM_Ephem;
63999  }
64000  columnMallocFailure(pStmt);
64001  return (sqlite3_value *)pOut;
64002}
64003#ifndef SQLITE_OMIT_UTF16
64004SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
64005  const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
64006  columnMallocFailure(pStmt);
64007  return val;
64008}
64009#endif /* SQLITE_OMIT_UTF16 */
64010SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
64011  int iType = sqlite3_value_type( columnMem(pStmt,i) );
64012  columnMallocFailure(pStmt);
64013  return iType;
64014}
64015
64016/* The following function is experimental and subject to change or
64017** removal */
64018/*int sqlite3_column_numeric_type(sqlite3_stmt *pStmt, int i){
64019**  return sqlite3_value_numeric_type( columnMem(pStmt,i) );
64020**}
64021*/
64022
64023/*
64024** Convert the N-th element of pStmt->pColName[] into a string using
64025** xFunc() then return that string.  If N is out of range, return 0.
64026**
64027** There are up to 5 names for each column.  useType determines which
64028** name is returned.  Here are the names:
64029**
64030**    0      The column name as it should be displayed for output
64031**    1      The datatype name for the column
64032**    2      The name of the database that the column derives from
64033**    3      The name of the table that the column derives from
64034**    4      The name of the table column that the result column derives from
64035**
64036** If the result is not a simple column reference (if it is an expression
64037** or a constant) then useTypes 2, 3, and 4 return NULL.
64038*/
64039static const void *columnName(
64040  sqlite3_stmt *pStmt,
64041  int N,
64042  const void *(*xFunc)(Mem*),
64043  int useType
64044){
64045  const void *ret = 0;
64046  Vdbe *p = (Vdbe *)pStmt;
64047  int n;
64048  sqlite3 *db = p->db;
64049
64050  assert( db!=0 );
64051  n = sqlite3_column_count(pStmt);
64052  if( N<n && N>=0 ){
64053    N += useType*n;
64054    sqlite3_mutex_enter(db->mutex);
64055    assert( db->mallocFailed==0 );
64056    ret = xFunc(&p->aColName[N]);
64057     /* A malloc may have failed inside of the xFunc() call. If this
64058    ** is the case, clear the mallocFailed flag and return NULL.
64059    */
64060    if( db->mallocFailed ){
64061      db->mallocFailed = 0;
64062      ret = 0;
64063    }
64064    sqlite3_mutex_leave(db->mutex);
64065  }
64066  return ret;
64067}
64068
64069/*
64070** Return the name of the Nth column of the result set returned by SQL
64071** statement pStmt.
64072*/
64073SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
64074  return columnName(
64075      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
64076}
64077#ifndef SQLITE_OMIT_UTF16
64078SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
64079  return columnName(
64080      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
64081}
64082#endif
64083
64084/*
64085** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
64086** not define OMIT_DECLTYPE.
64087*/
64088#if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
64089# error "Must not define both SQLITE_OMIT_DECLTYPE \
64090         and SQLITE_ENABLE_COLUMN_METADATA"
64091#endif
64092
64093#ifndef SQLITE_OMIT_DECLTYPE
64094/*
64095** Return the column declaration type (if applicable) of the 'i'th column
64096** of the result set of SQL statement pStmt.
64097*/
64098SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
64099  return columnName(
64100      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
64101}
64102#ifndef SQLITE_OMIT_UTF16
64103SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
64104  return columnName(
64105      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
64106}
64107#endif /* SQLITE_OMIT_UTF16 */
64108#endif /* SQLITE_OMIT_DECLTYPE */
64109
64110#ifdef SQLITE_ENABLE_COLUMN_METADATA
64111/*
64112** Return the name of the database from which a result column derives.
64113** NULL is returned if the result column is an expression or constant or
64114** anything else which is not an unabiguous reference to a database column.
64115*/
64116SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
64117  return columnName(
64118      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
64119}
64120#ifndef SQLITE_OMIT_UTF16
64121SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
64122  return columnName(
64123      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
64124}
64125#endif /* SQLITE_OMIT_UTF16 */
64126
64127/*
64128** Return the name of the table from which a result column derives.
64129** NULL is returned if the result column is an expression or constant or
64130** anything else which is not an unabiguous reference to a database column.
64131*/
64132SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
64133  return columnName(
64134      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
64135}
64136#ifndef SQLITE_OMIT_UTF16
64137SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
64138  return columnName(
64139      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
64140}
64141#endif /* SQLITE_OMIT_UTF16 */
64142
64143/*
64144** Return the name of the table column from which a result column derives.
64145** NULL is returned if the result column is an expression or constant or
64146** anything else which is not an unabiguous reference to a database column.
64147*/
64148SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
64149  return columnName(
64150      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
64151}
64152#ifndef SQLITE_OMIT_UTF16
64153SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
64154  return columnName(
64155      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
64156}
64157#endif /* SQLITE_OMIT_UTF16 */
64158#endif /* SQLITE_ENABLE_COLUMN_METADATA */
64159
64160
64161/******************************* sqlite3_bind_  ***************************
64162**
64163** Routines used to attach values to wildcards in a compiled SQL statement.
64164*/
64165/*
64166** Unbind the value bound to variable i in virtual machine p. This is the
64167** the same as binding a NULL value to the column. If the "i" parameter is
64168** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
64169**
64170** A successful evaluation of this routine acquires the mutex on p.
64171** the mutex is released if any kind of error occurs.
64172**
64173** The error code stored in database p->db is overwritten with the return
64174** value in any case.
64175*/
64176static int vdbeUnbind(Vdbe *p, int i){
64177  Mem *pVar;
64178  if( vdbeSafetyNotNull(p) ){
64179    return SQLITE_MISUSE_BKPT;
64180  }
64181  sqlite3_mutex_enter(p->db->mutex);
64182  if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
64183    sqlite3Error(p->db, SQLITE_MISUSE, 0);
64184    sqlite3_mutex_leave(p->db->mutex);
64185    sqlite3_log(SQLITE_MISUSE,
64186        "bind on a busy prepared statement: [%s]", p->zSql);
64187    return SQLITE_MISUSE_BKPT;
64188  }
64189  if( i<1 || i>p->nVar ){
64190    sqlite3Error(p->db, SQLITE_RANGE, 0);
64191    sqlite3_mutex_leave(p->db->mutex);
64192    return SQLITE_RANGE;
64193  }
64194  i--;
64195  pVar = &p->aVar[i];
64196  sqlite3VdbeMemRelease(pVar);
64197  pVar->flags = MEM_Null;
64198  sqlite3Error(p->db, SQLITE_OK, 0);
64199
64200  /* If the bit corresponding to this variable in Vdbe.expmask is set, then
64201  ** binding a new value to this variable invalidates the current query plan.
64202  **
64203  ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
64204  ** parameter in the WHERE clause might influence the choice of query plan
64205  ** for a statement, then the statement will be automatically recompiled,
64206  ** as if there had been a schema change, on the first sqlite3_step() call
64207  ** following any change to the bindings of that parameter.
64208  */
64209  if( p->isPrepareV2 &&
64210     ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
64211  ){
64212    p->expired = 1;
64213  }
64214  return SQLITE_OK;
64215}
64216
64217/*
64218** Bind a text or BLOB value.
64219*/
64220static int bindText(
64221  sqlite3_stmt *pStmt,   /* The statement to bind against */
64222  int i,                 /* Index of the parameter to bind */
64223  const void *zData,     /* Pointer to the data to be bound */
64224  int nData,             /* Number of bytes of data to be bound */
64225  void (*xDel)(void*),   /* Destructor for the data */
64226  u8 encoding            /* Encoding for the data */
64227){
64228  Vdbe *p = (Vdbe *)pStmt;
64229  Mem *pVar;
64230  int rc;
64231
64232  rc = vdbeUnbind(p, i);
64233  if( rc==SQLITE_OK ){
64234    if( zData!=0 ){
64235      pVar = &p->aVar[i-1];
64236      rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
64237      if( rc==SQLITE_OK && encoding!=0 ){
64238        rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
64239      }
64240      sqlite3Error(p->db, rc, 0);
64241      rc = sqlite3ApiExit(p->db, rc);
64242    }
64243    sqlite3_mutex_leave(p->db->mutex);
64244  }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
64245    xDel((void*)zData);
64246  }
64247  return rc;
64248}
64249
64250
64251/*
64252** Bind a blob value to an SQL statement variable.
64253*/
64254SQLITE_API int sqlite3_bind_blob(
64255  sqlite3_stmt *pStmt,
64256  int i,
64257  const void *zData,
64258  int nData,
64259  void (*xDel)(void*)
64260){
64261  return bindText(pStmt, i, zData, nData, xDel, 0);
64262}
64263SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
64264  int rc;
64265  Vdbe *p = (Vdbe *)pStmt;
64266  rc = vdbeUnbind(p, i);
64267  if( rc==SQLITE_OK ){
64268    sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
64269    sqlite3_mutex_leave(p->db->mutex);
64270  }
64271  return rc;
64272}
64273SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
64274  return sqlite3_bind_int64(p, i, (i64)iValue);
64275}
64276SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
64277  int rc;
64278  Vdbe *p = (Vdbe *)pStmt;
64279  rc = vdbeUnbind(p, i);
64280  if( rc==SQLITE_OK ){
64281    sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
64282    sqlite3_mutex_leave(p->db->mutex);
64283  }
64284  return rc;
64285}
64286SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
64287  int rc;
64288  Vdbe *p = (Vdbe*)pStmt;
64289  rc = vdbeUnbind(p, i);
64290  if( rc==SQLITE_OK ){
64291    sqlite3_mutex_leave(p->db->mutex);
64292  }
64293  return rc;
64294}
64295SQLITE_API int sqlite3_bind_text(
64296  sqlite3_stmt *pStmt,
64297  int i,
64298  const char *zData,
64299  int nData,
64300  void (*xDel)(void*)
64301){
64302  return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
64303}
64304#ifndef SQLITE_OMIT_UTF16
64305SQLITE_API int sqlite3_bind_text16(
64306  sqlite3_stmt *pStmt,
64307  int i,
64308  const void *zData,
64309  int nData,
64310  void (*xDel)(void*)
64311){
64312  return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
64313}
64314#endif /* SQLITE_OMIT_UTF16 */
64315SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
64316  int rc;
64317  switch( pValue->type ){
64318    case SQLITE_INTEGER: {
64319      rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
64320      break;
64321    }
64322    case SQLITE_FLOAT: {
64323      rc = sqlite3_bind_double(pStmt, i, pValue->r);
64324      break;
64325    }
64326    case SQLITE_BLOB: {
64327      if( pValue->flags & MEM_Zero ){
64328        rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
64329      }else{
64330        rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
64331      }
64332      break;
64333    }
64334    case SQLITE_TEXT: {
64335      rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,
64336                              pValue->enc);
64337      break;
64338    }
64339    default: {
64340      rc = sqlite3_bind_null(pStmt, i);
64341      break;
64342    }
64343  }
64344  return rc;
64345}
64346SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
64347  int rc;
64348  Vdbe *p = (Vdbe *)pStmt;
64349  rc = vdbeUnbind(p, i);
64350  if( rc==SQLITE_OK ){
64351    sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
64352    sqlite3_mutex_leave(p->db->mutex);
64353  }
64354  return rc;
64355}
64356
64357/*
64358** Return the number of wildcards that can be potentially bound to.
64359** This routine is added to support DBD::SQLite.
64360*/
64361SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
64362  Vdbe *p = (Vdbe*)pStmt;
64363  return p ? p->nVar : 0;
64364}
64365
64366/*
64367** Return the name of a wildcard parameter.  Return NULL if the index
64368** is out of range or if the wildcard is unnamed.
64369**
64370** The result is always UTF-8.
64371*/
64372SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
64373  Vdbe *p = (Vdbe*)pStmt;
64374  if( p==0 || i<1 || i>p->nzVar ){
64375    return 0;
64376  }
64377  return p->azVar[i-1];
64378}
64379
64380/*
64381** Given a wildcard parameter name, return the index of the variable
64382** with that name.  If there is no variable with the given name,
64383** return 0.
64384*/
64385SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
64386  int i;
64387  if( p==0 ){
64388    return 0;
64389  }
64390  if( zName ){
64391    for(i=0; i<p->nzVar; i++){
64392      const char *z = p->azVar[i];
64393      if( z && strncmp(z,zName,nName)==0 && z[nName]==0 ){
64394        return i+1;
64395      }
64396    }
64397  }
64398  return 0;
64399}
64400SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
64401  return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
64402}
64403
64404/*
64405** Transfer all bindings from the first statement over to the second.
64406*/
64407SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
64408  Vdbe *pFrom = (Vdbe*)pFromStmt;
64409  Vdbe *pTo = (Vdbe*)pToStmt;
64410  int i;
64411  assert( pTo->db==pFrom->db );
64412  assert( pTo->nVar==pFrom->nVar );
64413  sqlite3_mutex_enter(pTo->db->mutex);
64414  for(i=0; i<pFrom->nVar; i++){
64415    sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
64416  }
64417  sqlite3_mutex_leave(pTo->db->mutex);
64418  return SQLITE_OK;
64419}
64420
64421#ifndef SQLITE_OMIT_DEPRECATED
64422/*
64423** Deprecated external interface.  Internal/core SQLite code
64424** should call sqlite3TransferBindings.
64425**
64426** Is is misuse to call this routine with statements from different
64427** database connections.  But as this is a deprecated interface, we
64428** will not bother to check for that condition.
64429**
64430** If the two statements contain a different number of bindings, then
64431** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise
64432** SQLITE_OK is returned.
64433*/
64434SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
64435  Vdbe *pFrom = (Vdbe*)pFromStmt;
64436  Vdbe *pTo = (Vdbe*)pToStmt;
64437  if( pFrom->nVar!=pTo->nVar ){
64438    return SQLITE_ERROR;
64439  }
64440  if( pTo->isPrepareV2 && pTo->expmask ){
64441    pTo->expired = 1;
64442  }
64443  if( pFrom->isPrepareV2 && pFrom->expmask ){
64444    pFrom->expired = 1;
64445  }
64446  return sqlite3TransferBindings(pFromStmt, pToStmt);
64447}
64448#endif
64449
64450/*
64451** Return the sqlite3* database handle to which the prepared statement given
64452** in the argument belongs.  This is the same database handle that was
64453** the first argument to the sqlite3_prepare() that was used to create
64454** the statement in the first place.
64455*/
64456SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
64457  return pStmt ? ((Vdbe*)pStmt)->db : 0;
64458}
64459
64460/*
64461** Return true if the prepared statement is guaranteed to not modify the
64462** database.
64463*/
64464SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
64465  return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
64466}
64467
64468/*
64469** Return true if the prepared statement is in need of being reset.
64470*/
64471SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
64472  Vdbe *v = (Vdbe*)pStmt;
64473  return v!=0 && v->pc>0 && v->magic==VDBE_MAGIC_RUN;
64474}
64475
64476/*
64477** Return a pointer to the next prepared statement after pStmt associated
64478** with database connection pDb.  If pStmt is NULL, return the first
64479** prepared statement for the database connection.  Return NULL if there
64480** are no more.
64481*/
64482SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
64483  sqlite3_stmt *pNext;
64484  sqlite3_mutex_enter(pDb->mutex);
64485  if( pStmt==0 ){
64486    pNext = (sqlite3_stmt*)pDb->pVdbe;
64487  }else{
64488    pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
64489  }
64490  sqlite3_mutex_leave(pDb->mutex);
64491  return pNext;
64492}
64493
64494/*
64495** Return the value of a status counter for a prepared statement
64496*/
64497SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
64498  Vdbe *pVdbe = (Vdbe*)pStmt;
64499  int v = pVdbe->aCounter[op-1];
64500  if( resetFlag ) pVdbe->aCounter[op-1] = 0;
64501  return v;
64502}
64503
64504/************** End of vdbeapi.c *********************************************/
64505/************** Begin file vdbetrace.c ***************************************/
64506/*
64507** 2009 November 25
64508**
64509** The author disclaims copyright to this source code.  In place of
64510** a legal notice, here is a blessing:
64511**
64512**    May you do good and not evil.
64513**    May you find forgiveness for yourself and forgive others.
64514**    May you share freely, never taking more than you give.
64515**
64516*************************************************************************
64517**
64518** This file contains code used to insert the values of host parameters
64519** (aka "wildcards") into the SQL text output by sqlite3_trace().
64520**
64521** The Vdbe parse-tree explainer is also found here.
64522*/
64523
64524#ifndef SQLITE_OMIT_TRACE
64525
64526/*
64527** zSql is a zero-terminated string of UTF-8 SQL text.  Return the number of
64528** bytes in this text up to but excluding the first character in
64529** a host parameter.  If the text contains no host parameters, return
64530** the total number of bytes in the text.
64531*/
64532static int findNextHostParameter(const char *zSql, int *pnToken){
64533  int tokenType;
64534  int nTotal = 0;
64535  int n;
64536
64537  *pnToken = 0;
64538  while( zSql[0] ){
64539    n = sqlite3GetToken((u8*)zSql, &tokenType);
64540    assert( n>0 && tokenType!=TK_ILLEGAL );
64541    if( tokenType==TK_VARIABLE ){
64542      *pnToken = n;
64543      break;
64544    }
64545    nTotal += n;
64546    zSql += n;
64547  }
64548  return nTotal;
64549}
64550
64551/*
64552** This function returns a pointer to a nul-terminated string in memory
64553** obtained from sqlite3DbMalloc(). If sqlite3.vdbeExecCnt is 1, then the
64554** string contains a copy of zRawSql but with host parameters expanded to
64555** their current bindings. Or, if sqlite3.vdbeExecCnt is greater than 1,
64556** then the returned string holds a copy of zRawSql with "-- " prepended
64557** to each line of text.
64558**
64559** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then
64560** then long strings and blobs are truncated to that many bytes.  This
64561** can be used to prevent unreasonably large trace strings when dealing
64562** with large (multi-megabyte) strings and blobs.
64563**
64564** The calling function is responsible for making sure the memory returned
64565** is eventually freed.
64566**
64567** ALGORITHM:  Scan the input string looking for host parameters in any of
64568** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within
64569** string literals, quoted identifier names, and comments.  For text forms,
64570** the host parameter index is found by scanning the perpared
64571** statement for the corresponding OP_Variable opcode.  Once the host
64572** parameter index is known, locate the value in p->aVar[].  Then render
64573** the value as a literal in place of the host parameter name.
64574*/
64575SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
64576  Vdbe *p,                 /* The prepared statement being evaluated */
64577  const char *zRawSql      /* Raw text of the SQL statement */
64578){
64579  sqlite3 *db;             /* The database connection */
64580  int idx = 0;             /* Index of a host parameter */
64581  int nextIndex = 1;       /* Index of next ? host parameter */
64582  int n;                   /* Length of a token prefix */
64583  int nToken;              /* Length of the parameter token */
64584  int i;                   /* Loop counter */
64585  Mem *pVar;               /* Value of a host parameter */
64586  StrAccum out;            /* Accumulate the output here */
64587  char zBase[100];         /* Initial working space */
64588
64589  db = p->db;
64590  sqlite3StrAccumInit(&out, zBase, sizeof(zBase),
64591                      db->aLimit[SQLITE_LIMIT_LENGTH]);
64592  out.db = db;
64593  if( db->vdbeExecCnt>1 ){
64594    while( *zRawSql ){
64595      const char *zStart = zRawSql;
64596      while( *(zRawSql++)!='\n' && *zRawSql );
64597      sqlite3StrAccumAppend(&out, "-- ", 3);
64598      sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
64599    }
64600  }else{
64601    while( zRawSql[0] ){
64602      n = findNextHostParameter(zRawSql, &nToken);
64603      assert( n>0 );
64604      sqlite3StrAccumAppend(&out, zRawSql, n);
64605      zRawSql += n;
64606      assert( zRawSql[0] || nToken==0 );
64607      if( nToken==0 ) break;
64608      if( zRawSql[0]=='?' ){
64609        if( nToken>1 ){
64610          assert( sqlite3Isdigit(zRawSql[1]) );
64611          sqlite3GetInt32(&zRawSql[1], &idx);
64612        }else{
64613          idx = nextIndex;
64614        }
64615      }else{
64616        assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
64617        testcase( zRawSql[0]==':' );
64618        testcase( zRawSql[0]=='$' );
64619        testcase( zRawSql[0]=='@' );
64620        idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
64621        assert( idx>0 );
64622      }
64623      zRawSql += nToken;
64624      nextIndex = idx + 1;
64625      assert( idx>0 && idx<=p->nVar );
64626      pVar = &p->aVar[idx-1];
64627      if( pVar->flags & MEM_Null ){
64628        sqlite3StrAccumAppend(&out, "NULL", 4);
64629      }else if( pVar->flags & MEM_Int ){
64630        sqlite3XPrintf(&out, "%lld", pVar->u.i);
64631      }else if( pVar->flags & MEM_Real ){
64632        sqlite3XPrintf(&out, "%!.15g", pVar->r);
64633      }else if( pVar->flags & MEM_Str ){
64634        int nOut;  /* Number of bytes of the string text to include in output */
64635#ifndef SQLITE_OMIT_UTF16
64636        u8 enc = ENC(db);
64637        Mem utf8;
64638        if( enc!=SQLITE_UTF8 ){
64639          memset(&utf8, 0, sizeof(utf8));
64640          utf8.db = db;
64641          sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
64642          sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
64643          pVar = &utf8;
64644        }
64645#endif
64646        nOut = pVar->n;
64647#ifdef SQLITE_TRACE_SIZE_LIMIT
64648        if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
64649          nOut = SQLITE_TRACE_SIZE_LIMIT;
64650          while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
64651        }
64652#endif
64653        sqlite3XPrintf(&out, "'%.*q'", nOut, pVar->z);
64654#ifdef SQLITE_TRACE_SIZE_LIMIT
64655        if( nOut<pVar->n ) sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
64656#endif
64657#ifndef SQLITE_OMIT_UTF16
64658        if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
64659#endif
64660      }else if( pVar->flags & MEM_Zero ){
64661        sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
64662      }else{
64663        int nOut;  /* Number of bytes of the blob to include in output */
64664        assert( pVar->flags & MEM_Blob );
64665        sqlite3StrAccumAppend(&out, "x'", 2);
64666        nOut = pVar->n;
64667#ifdef SQLITE_TRACE_SIZE_LIMIT
64668        if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT;
64669#endif
64670        for(i=0; i<nOut; i++){
64671          sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
64672        }
64673        sqlite3StrAccumAppend(&out, "'", 1);
64674#ifdef SQLITE_TRACE_SIZE_LIMIT
64675        if( nOut<pVar->n ) sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
64676#endif
64677      }
64678    }
64679  }
64680  return sqlite3StrAccumFinish(&out);
64681}
64682
64683#endif /* #ifndef SQLITE_OMIT_TRACE */
64684
64685/*****************************************************************************
64686** The following code implements the data-structure explaining logic
64687** for the Vdbe.
64688*/
64689
64690#if defined(SQLITE_ENABLE_TREE_EXPLAIN)
64691
64692/*
64693** Allocate a new Explain object
64694*/
64695SQLITE_PRIVATE void sqlite3ExplainBegin(Vdbe *pVdbe){
64696  if( pVdbe ){
64697    Explain *p;
64698    sqlite3BeginBenignMalloc();
64699    p = (Explain *)sqlite3MallocZero( sizeof(Explain) );
64700    if( p ){
64701      p->pVdbe = pVdbe;
64702      sqlite3_free(pVdbe->pExplain);
64703      pVdbe->pExplain = p;
64704      sqlite3StrAccumInit(&p->str, p->zBase, sizeof(p->zBase),
64705                          SQLITE_MAX_LENGTH);
64706      p->str.useMalloc = 2;
64707    }else{
64708      sqlite3EndBenignMalloc();
64709    }
64710  }
64711}
64712
64713/*
64714** Return true if the Explain ends with a new-line.
64715*/
64716static int endsWithNL(Explain *p){
64717  return p && p->str.zText && p->str.nChar
64718           && p->str.zText[p->str.nChar-1]=='\n';
64719}
64720
64721/*
64722** Append text to the indentation
64723*/
64724SQLITE_PRIVATE void sqlite3ExplainPrintf(Vdbe *pVdbe, const char *zFormat, ...){
64725  Explain *p;
64726  if( pVdbe && (p = pVdbe->pExplain)!=0 ){
64727    va_list ap;
64728    if( p->nIndent && endsWithNL(p) ){
64729      int n = p->nIndent;
64730      if( n>ArraySize(p->aIndent) ) n = ArraySize(p->aIndent);
64731      sqlite3AppendSpace(&p->str, p->aIndent[n-1]);
64732    }
64733    va_start(ap, zFormat);
64734    sqlite3VXPrintf(&p->str, 1, zFormat, ap);
64735    va_end(ap);
64736  }
64737}
64738
64739/*
64740** Append a '\n' if there is not already one.
64741*/
64742SQLITE_PRIVATE void sqlite3ExplainNL(Vdbe *pVdbe){
64743  Explain *p;
64744  if( pVdbe && (p = pVdbe->pExplain)!=0 && !endsWithNL(p) ){
64745    sqlite3StrAccumAppend(&p->str, "\n", 1);
64746  }
64747}
64748
64749/*
64750** Push a new indentation level.  Subsequent lines will be indented
64751** so that they begin at the current cursor position.
64752*/
64753SQLITE_PRIVATE void sqlite3ExplainPush(Vdbe *pVdbe){
64754  Explain *p;
64755  if( pVdbe && (p = pVdbe->pExplain)!=0 ){
64756    if( p->str.zText && p->nIndent<ArraySize(p->aIndent) ){
64757      const char *z = p->str.zText;
64758      int i = p->str.nChar-1;
64759      int x;
64760      while( i>=0 && z[i]!='\n' ){ i--; }
64761      x = (p->str.nChar - 1) - i;
64762      if( p->nIndent && x<p->aIndent[p->nIndent-1] ){
64763        x = p->aIndent[p->nIndent-1];
64764      }
64765      p->aIndent[p->nIndent] = x;
64766    }
64767    p->nIndent++;
64768  }
64769}
64770
64771/*
64772** Pop the indentation stack by one level.
64773*/
64774SQLITE_PRIVATE void sqlite3ExplainPop(Vdbe *p){
64775  if( p && p->pExplain ) p->pExplain->nIndent--;
64776}
64777
64778/*
64779** Free the indentation structure
64780*/
64781SQLITE_PRIVATE void sqlite3ExplainFinish(Vdbe *pVdbe){
64782  if( pVdbe && pVdbe->pExplain ){
64783    sqlite3_free(pVdbe->zExplain);
64784    sqlite3ExplainNL(pVdbe);
64785    pVdbe->zExplain = sqlite3StrAccumFinish(&pVdbe->pExplain->str);
64786    sqlite3_free(pVdbe->pExplain);
64787    pVdbe->pExplain = 0;
64788    sqlite3EndBenignMalloc();
64789  }
64790}
64791
64792/*
64793** Return the explanation of a virtual machine.
64794*/
64795SQLITE_PRIVATE const char *sqlite3VdbeExplanation(Vdbe *pVdbe){
64796  return (pVdbe && pVdbe->zExplain) ? pVdbe->zExplain : 0;
64797}
64798#endif /* defined(SQLITE_DEBUG) */
64799
64800/************** End of vdbetrace.c *******************************************/
64801/************** Begin file vdbe.c ********************************************/
64802/*
64803** 2001 September 15
64804**
64805** The author disclaims copyright to this source code.  In place of
64806** a legal notice, here is a blessing:
64807**
64808**    May you do good and not evil.
64809**    May you find forgiveness for yourself and forgive others.
64810**    May you share freely, never taking more than you give.
64811**
64812*************************************************************************
64813** The code in this file implements execution method of the
64814** Virtual Database Engine (VDBE).  A separate file ("vdbeaux.c")
64815** handles housekeeping details such as creating and deleting
64816** VDBE instances.  This file is solely interested in executing
64817** the VDBE program.
64818**
64819** In the external interface, an "sqlite3_stmt*" is an opaque pointer
64820** to a VDBE.
64821**
64822** The SQL parser generates a program which is then executed by
64823** the VDBE to do the work of the SQL statement.  VDBE programs are
64824** similar in form to assembly language.  The program consists of
64825** a linear sequence of operations.  Each operation has an opcode
64826** and 5 operands.  Operands P1, P2, and P3 are integers.  Operand P4
64827** is a null-terminated string.  Operand P5 is an unsigned character.
64828** Few opcodes use all 5 operands.
64829**
64830** Computation results are stored on a set of registers numbered beginning
64831** with 1 and going up to Vdbe.nMem.  Each register can store
64832** either an integer, a null-terminated string, a floating point
64833** number, or the SQL "NULL" value.  An implicit conversion from one
64834** type to the other occurs as necessary.
64835**
64836** Most of the code in this file is taken up by the sqlite3VdbeExec()
64837** function which does the work of interpreting a VDBE program.
64838** But other routines are also provided to help in building up
64839** a program instruction by instruction.
64840**
64841** Various scripts scan this source file in order to generate HTML
64842** documentation, headers files, or other derived files.  The formatting
64843** of the code in this file is, therefore, important.  See other comments
64844** in this file for details.  If in doubt, do not deviate from existing
64845** commenting and indentation practices when changing or adding code.
64846*/
64847
64848/*
64849** Invoke this macro on memory cells just prior to changing the
64850** value of the cell.  This macro verifies that shallow copies are
64851** not misused.
64852*/
64853#ifdef SQLITE_DEBUG
64854# define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
64855#else
64856# define memAboutToChange(P,M)
64857#endif
64858
64859/*
64860** The following global variable is incremented every time a cursor
64861** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
64862** procedures use this information to make sure that indices are
64863** working correctly.  This variable has no function other than to
64864** help verify the correct operation of the library.
64865*/
64866#ifdef SQLITE_TEST
64867SQLITE_API int sqlite3_search_count = 0;
64868#endif
64869
64870/*
64871** When this global variable is positive, it gets decremented once before
64872** each instruction in the VDBE.  When it reaches zero, the u1.isInterrupted
64873** field of the sqlite3 structure is set in order to simulate an interrupt.
64874**
64875** This facility is used for testing purposes only.  It does not function
64876** in an ordinary build.
64877*/
64878#ifdef SQLITE_TEST
64879SQLITE_API int sqlite3_interrupt_count = 0;
64880#endif
64881
64882/*
64883** The next global variable is incremented each type the OP_Sort opcode
64884** is executed.  The test procedures use this information to make sure that
64885** sorting is occurring or not occurring at appropriate times.   This variable
64886** has no function other than to help verify the correct operation of the
64887** library.
64888*/
64889#ifdef SQLITE_TEST
64890SQLITE_API int sqlite3_sort_count = 0;
64891#endif
64892
64893/*
64894** The next global variable records the size of the largest MEM_Blob
64895** or MEM_Str that has been used by a VDBE opcode.  The test procedures
64896** use this information to make sure that the zero-blob functionality
64897** is working correctly.   This variable has no function other than to
64898** help verify the correct operation of the library.
64899*/
64900#ifdef SQLITE_TEST
64901SQLITE_API int sqlite3_max_blobsize = 0;
64902static void updateMaxBlobsize(Mem *p){
64903  if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
64904    sqlite3_max_blobsize = p->n;
64905  }
64906}
64907#endif
64908
64909/*
64910** The next global variable is incremented each type the OP_Found opcode
64911** is executed. This is used to test whether or not the foreign key
64912** operation implemented using OP_FkIsZero is working. This variable
64913** has no function other than to help verify the correct operation of the
64914** library.
64915*/
64916#ifdef SQLITE_TEST
64917SQLITE_API int sqlite3_found_count = 0;
64918#endif
64919
64920/*
64921** Test a register to see if it exceeds the current maximum blob size.
64922** If it does, record the new maximum blob size.
64923*/
64924#if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
64925# define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
64926#else
64927# define UPDATE_MAX_BLOBSIZE(P)
64928#endif
64929
64930/*
64931** Convert the given register into a string if it isn't one
64932** already. Return non-zero if a malloc() fails.
64933*/
64934#define Stringify(P, enc) \
64935   if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
64936     { goto no_mem; }
64937
64938/*
64939** An ephemeral string value (signified by the MEM_Ephem flag) contains
64940** a pointer to a dynamically allocated string where some other entity
64941** is responsible for deallocating that string.  Because the register
64942** does not control the string, it might be deleted without the register
64943** knowing it.
64944**
64945** This routine converts an ephemeral string into a dynamically allocated
64946** string that the register itself controls.  In other words, it
64947** converts an MEM_Ephem string into an MEM_Dyn string.
64948*/
64949#define Deephemeralize(P) \
64950   if( ((P)->flags&MEM_Ephem)!=0 \
64951       && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
64952
64953/* Return true if the cursor was opened using the OP_OpenSorter opcode. */
64954# define isSorter(x) ((x)->pSorter!=0)
64955
64956/*
64957** Argument pMem points at a register that will be passed to a
64958** user-defined function or returned to the user as the result of a query.
64959** This routine sets the pMem->type variable used by the sqlite3_value_*()
64960** routines.
64961*/
64962SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem){
64963  int flags = pMem->flags;
64964  if( flags & MEM_Null ){
64965    pMem->type = SQLITE_NULL;
64966  }
64967  else if( flags & MEM_Int ){
64968    pMem->type = SQLITE_INTEGER;
64969  }
64970  else if( flags & MEM_Real ){
64971    pMem->type = SQLITE_FLOAT;
64972  }
64973  else if( flags & MEM_Str ){
64974    pMem->type = SQLITE_TEXT;
64975  }else{
64976    pMem->type = SQLITE_BLOB;
64977  }
64978}
64979
64980/*
64981** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
64982** if we run out of memory.
64983*/
64984static VdbeCursor *allocateCursor(
64985  Vdbe *p,              /* The virtual machine */
64986  int iCur,             /* Index of the new VdbeCursor */
64987  int nField,           /* Number of fields in the table or index */
64988  int iDb,              /* Database the cursor belongs to, or -1 */
64989  int isBtreeCursor     /* True for B-Tree.  False for pseudo-table or vtab */
64990){
64991  /* Find the memory cell that will be used to store the blob of memory
64992  ** required for this VdbeCursor structure. It is convenient to use a
64993  ** vdbe memory cell to manage the memory allocation required for a
64994  ** VdbeCursor structure for the following reasons:
64995  **
64996  **   * Sometimes cursor numbers are used for a couple of different
64997  **     purposes in a vdbe program. The different uses might require
64998  **     different sized allocations. Memory cells provide growable
64999  **     allocations.
65000  **
65001  **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
65002  **     be freed lazily via the sqlite3_release_memory() API. This
65003  **     minimizes the number of malloc calls made by the system.
65004  **
65005  ** Memory cells for cursors are allocated at the top of the address
65006  ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
65007  ** cursor 1 is managed by memory cell (p->nMem-1), etc.
65008  */
65009  Mem *pMem = &p->aMem[p->nMem-iCur];
65010
65011  int nByte;
65012  VdbeCursor *pCx = 0;
65013  nByte =
65014      ROUND8(sizeof(VdbeCursor)) +
65015      (isBtreeCursor?sqlite3BtreeCursorSize():0) +
65016      2*nField*sizeof(u32);
65017
65018  assert( iCur<p->nCursor );
65019  if( p->apCsr[iCur] ){
65020    sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
65021    p->apCsr[iCur] = 0;
65022  }
65023  if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
65024    p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
65025    memset(pCx, 0, sizeof(VdbeCursor));
65026    pCx->iDb = iDb;
65027    pCx->nField = nField;
65028    if( nField ){
65029      pCx->aType = (u32 *)&pMem->z[ROUND8(sizeof(VdbeCursor))];
65030    }
65031    if( isBtreeCursor ){
65032      pCx->pCursor = (BtCursor*)
65033          &pMem->z[ROUND8(sizeof(VdbeCursor))+2*nField*sizeof(u32)];
65034      sqlite3BtreeCursorZero(pCx->pCursor);
65035    }
65036  }
65037  return pCx;
65038}
65039
65040/*
65041** Try to convert a value into a numeric representation if we can
65042** do so without loss of information.  In other words, if the string
65043** looks like a number, convert it into a number.  If it does not
65044** look like a number, leave it alone.
65045*/
65046static void applyNumericAffinity(Mem *pRec){
65047  if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
65048    double rValue;
65049    i64 iValue;
65050    u8 enc = pRec->enc;
65051    if( (pRec->flags&MEM_Str)==0 ) return;
65052    if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
65053    if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
65054      pRec->u.i = iValue;
65055      pRec->flags |= MEM_Int;
65056    }else{
65057      pRec->r = rValue;
65058      pRec->flags |= MEM_Real;
65059    }
65060  }
65061}
65062
65063/*
65064** Processing is determine by the affinity parameter:
65065**
65066** SQLITE_AFF_INTEGER:
65067** SQLITE_AFF_REAL:
65068** SQLITE_AFF_NUMERIC:
65069**    Try to convert pRec to an integer representation or a
65070**    floating-point representation if an integer representation
65071**    is not possible.  Note that the integer representation is
65072**    always preferred, even if the affinity is REAL, because
65073**    an integer representation is more space efficient on disk.
65074**
65075** SQLITE_AFF_TEXT:
65076**    Convert pRec to a text representation.
65077**
65078** SQLITE_AFF_NONE:
65079**    No-op.  pRec is unchanged.
65080*/
65081static void applyAffinity(
65082  Mem *pRec,          /* The value to apply affinity to */
65083  char affinity,      /* The affinity to be applied */
65084  u8 enc              /* Use this text encoding */
65085){
65086  if( affinity==SQLITE_AFF_TEXT ){
65087    /* Only attempt the conversion to TEXT if there is an integer or real
65088    ** representation (blob and NULL do not get converted) but no string
65089    ** representation.
65090    */
65091    if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
65092      sqlite3VdbeMemStringify(pRec, enc);
65093    }
65094    pRec->flags &= ~(MEM_Real|MEM_Int);
65095  }else if( affinity!=SQLITE_AFF_NONE ){
65096    assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
65097             || affinity==SQLITE_AFF_NUMERIC );
65098    applyNumericAffinity(pRec);
65099    if( pRec->flags & MEM_Real ){
65100      sqlite3VdbeIntegerAffinity(pRec);
65101    }
65102  }
65103}
65104
65105/*
65106** Try to convert the type of a function argument or a result column
65107** into a numeric representation.  Use either INTEGER or REAL whichever
65108** is appropriate.  But only do the conversion if it is possible without
65109** loss of information and return the revised type of the argument.
65110*/
65111SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
65112  Mem *pMem = (Mem*)pVal;
65113  if( pMem->type==SQLITE_TEXT ){
65114    applyNumericAffinity(pMem);
65115    sqlite3VdbeMemStoreType(pMem);
65116  }
65117  return pMem->type;
65118}
65119
65120/*
65121** Exported version of applyAffinity(). This one works on sqlite3_value*,
65122** not the internal Mem* type.
65123*/
65124SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
65125  sqlite3_value *pVal,
65126  u8 affinity,
65127  u8 enc
65128){
65129  applyAffinity((Mem *)pVal, affinity, enc);
65130}
65131
65132#ifdef SQLITE_DEBUG
65133/*
65134** Write a nice string representation of the contents of cell pMem
65135** into buffer zBuf, length nBuf.
65136*/
65137SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
65138  char *zCsr = zBuf;
65139  int f = pMem->flags;
65140
65141  static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
65142
65143  if( f&MEM_Blob ){
65144    int i;
65145    char c;
65146    if( f & MEM_Dyn ){
65147      c = 'z';
65148      assert( (f & (MEM_Static|MEM_Ephem))==0 );
65149    }else if( f & MEM_Static ){
65150      c = 't';
65151      assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
65152    }else if( f & MEM_Ephem ){
65153      c = 'e';
65154      assert( (f & (MEM_Static|MEM_Dyn))==0 );
65155    }else{
65156      c = 's';
65157    }
65158
65159    sqlite3_snprintf(100, zCsr, "%c", c);
65160    zCsr += sqlite3Strlen30(zCsr);
65161    sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
65162    zCsr += sqlite3Strlen30(zCsr);
65163    for(i=0; i<16 && i<pMem->n; i++){
65164      sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
65165      zCsr += sqlite3Strlen30(zCsr);
65166    }
65167    for(i=0; i<16 && i<pMem->n; i++){
65168      char z = pMem->z[i];
65169      if( z<32 || z>126 ) *zCsr++ = '.';
65170      else *zCsr++ = z;
65171    }
65172
65173    sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
65174    zCsr += sqlite3Strlen30(zCsr);
65175    if( f & MEM_Zero ){
65176      sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
65177      zCsr += sqlite3Strlen30(zCsr);
65178    }
65179    *zCsr = '\0';
65180  }else if( f & MEM_Str ){
65181    int j, k;
65182    zBuf[0] = ' ';
65183    if( f & MEM_Dyn ){
65184      zBuf[1] = 'z';
65185      assert( (f & (MEM_Static|MEM_Ephem))==0 );
65186    }else if( f & MEM_Static ){
65187      zBuf[1] = 't';
65188      assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
65189    }else if( f & MEM_Ephem ){
65190      zBuf[1] = 'e';
65191      assert( (f & (MEM_Static|MEM_Dyn))==0 );
65192    }else{
65193      zBuf[1] = 's';
65194    }
65195    k = 2;
65196    sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
65197    k += sqlite3Strlen30(&zBuf[k]);
65198    zBuf[k++] = '[';
65199    for(j=0; j<15 && j<pMem->n; j++){
65200      u8 c = pMem->z[j];
65201      if( c>=0x20 && c<0x7f ){
65202        zBuf[k++] = c;
65203      }else{
65204        zBuf[k++] = '.';
65205      }
65206    }
65207    zBuf[k++] = ']';
65208    sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
65209    k += sqlite3Strlen30(&zBuf[k]);
65210    zBuf[k++] = 0;
65211  }
65212}
65213#endif
65214
65215#ifdef SQLITE_DEBUG
65216/*
65217** Print the value of a register for tracing purposes:
65218*/
65219static void memTracePrint(FILE *out, Mem *p){
65220  if( p->flags & MEM_Invalid ){
65221    fprintf(out, " undefined");
65222  }else if( p->flags & MEM_Null ){
65223    fprintf(out, " NULL");
65224  }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
65225    fprintf(out, " si:%lld", p->u.i);
65226  }else if( p->flags & MEM_Int ){
65227    fprintf(out, " i:%lld", p->u.i);
65228#ifndef SQLITE_OMIT_FLOATING_POINT
65229  }else if( p->flags & MEM_Real ){
65230    fprintf(out, " r:%g", p->r);
65231#endif
65232  }else if( p->flags & MEM_RowSet ){
65233    fprintf(out, " (rowset)");
65234  }else{
65235    char zBuf[200];
65236    sqlite3VdbeMemPrettyPrint(p, zBuf);
65237    fprintf(out, " ");
65238    fprintf(out, "%s", zBuf);
65239  }
65240}
65241static void registerTrace(FILE *out, int iReg, Mem *p){
65242  fprintf(out, "REG[%d] = ", iReg);
65243  memTracePrint(out, p);
65244  fprintf(out, "\n");
65245}
65246#endif
65247
65248#ifdef SQLITE_DEBUG
65249#  define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
65250#else
65251#  define REGISTER_TRACE(R,M)
65252#endif
65253
65254
65255#ifdef VDBE_PROFILE
65256
65257/*
65258** hwtime.h contains inline assembler code for implementing
65259** high-performance timing routines.
65260*/
65261/************** Include hwtime.h in the middle of vdbe.c *********************/
65262/************** Begin file hwtime.h ******************************************/
65263/*
65264** 2008 May 27
65265**
65266** The author disclaims copyright to this source code.  In place of
65267** a legal notice, here is a blessing:
65268**
65269**    May you do good and not evil.
65270**    May you find forgiveness for yourself and forgive others.
65271**    May you share freely, never taking more than you give.
65272**
65273******************************************************************************
65274**
65275** This file contains inline asm code for retrieving "high-performance"
65276** counters for x86 class CPUs.
65277*/
65278#ifndef _HWTIME_H_
65279#define _HWTIME_H_
65280
65281/*
65282** The following routine only works on pentium-class (or newer) processors.
65283** It uses the RDTSC opcode to read the cycle count value out of the
65284** processor and returns that value.  This can be used for high-res
65285** profiling.
65286*/
65287#if (defined(__GNUC__) || defined(_MSC_VER)) && \
65288      (defined(i386) || defined(__i386__) || defined(_M_IX86))
65289
65290  #if defined(__GNUC__)
65291
65292  __inline__ sqlite_uint64 sqlite3Hwtime(void){
65293     unsigned int lo, hi;
65294     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
65295     return (sqlite_uint64)hi << 32 | lo;
65296  }
65297
65298  #elif defined(_MSC_VER)
65299
65300  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
65301     __asm {
65302        rdtsc
65303        ret       ; return value at EDX:EAX
65304     }
65305  }
65306
65307  #endif
65308
65309#elif (defined(__GNUC__) && defined(__x86_64__))
65310
65311  __inline__ sqlite_uint64 sqlite3Hwtime(void){
65312      unsigned long val;
65313      __asm__ __volatile__ ("rdtsc" : "=A" (val));
65314      return val;
65315  }
65316
65317#elif (defined(__GNUC__) && defined(__ppc__))
65318
65319  __inline__ sqlite_uint64 sqlite3Hwtime(void){
65320      unsigned long long retval;
65321      unsigned long junk;
65322      __asm__ __volatile__ ("\n\
65323          1:      mftbu   %1\n\
65324                  mftb    %L0\n\
65325                  mftbu   %0\n\
65326                  cmpw    %0,%1\n\
65327                  bne     1b"
65328                  : "=r" (retval), "=r" (junk));
65329      return retval;
65330  }
65331
65332#else
65333
65334  #error Need implementation of sqlite3Hwtime() for your platform.
65335
65336  /*
65337  ** To compile without implementing sqlite3Hwtime() for your platform,
65338  ** you can remove the above #error and use the following
65339  ** stub function.  You will lose timing support for many
65340  ** of the debugging and testing utilities, but it should at
65341  ** least compile and run.
65342  */
65343SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
65344
65345#endif
65346
65347#endif /* !defined(_HWTIME_H_) */
65348
65349/************** End of hwtime.h **********************************************/
65350/************** Continuing where we left off in vdbe.c ***********************/
65351
65352#endif
65353
65354/*
65355** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
65356** sqlite3_interrupt() routine has been called.  If it has been, then
65357** processing of the VDBE program is interrupted.
65358**
65359** This macro added to every instruction that does a jump in order to
65360** implement a loop.  This test used to be on every single instruction,
65361** but that meant we more testing than we needed.  By only testing the
65362** flag on jump instructions, we get a (small) speed improvement.
65363*/
65364#define CHECK_FOR_INTERRUPT \
65365   if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
65366
65367
65368#ifndef NDEBUG
65369/*
65370** This function is only called from within an assert() expression. It
65371** checks that the sqlite3.nTransaction variable is correctly set to
65372** the number of non-transaction savepoints currently in the
65373** linked list starting at sqlite3.pSavepoint.
65374**
65375** Usage:
65376**
65377**     assert( checkSavepointCount(db) );
65378*/
65379static int checkSavepointCount(sqlite3 *db){
65380  int n = 0;
65381  Savepoint *p;
65382  for(p=db->pSavepoint; p; p=p->pNext) n++;
65383  assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
65384  return 1;
65385}
65386#endif
65387
65388/*
65389** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
65390** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
65391** in memory obtained from sqlite3DbMalloc).
65392*/
65393static void importVtabErrMsg(Vdbe *p, sqlite3_vtab *pVtab){
65394  sqlite3 *db = p->db;
65395  sqlite3DbFree(db, p->zErrMsg);
65396  p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
65397  sqlite3_free(pVtab->zErrMsg);
65398  pVtab->zErrMsg = 0;
65399}
65400
65401
65402/*
65403** Execute as much of a VDBE program as we can then return.
65404**
65405** sqlite3VdbeMakeReady() must be called before this routine in order to
65406** close the program with a final OP_Halt and to set up the callbacks
65407** and the error message pointer.
65408**
65409** Whenever a row or result data is available, this routine will either
65410** invoke the result callback (if there is one) or return with
65411** SQLITE_ROW.
65412**
65413** If an attempt is made to open a locked database, then this routine
65414** will either invoke the busy callback (if there is one) or it will
65415** return SQLITE_BUSY.
65416**
65417** If an error occurs, an error message is written to memory obtained
65418** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
65419** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
65420**
65421** If the callback ever returns non-zero, then the program exits
65422** immediately.  There will be no error message but the p->rc field is
65423** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
65424**
65425** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
65426** routine to return SQLITE_ERROR.
65427**
65428** Other fatal errors return SQLITE_ERROR.
65429**
65430** After this routine has finished, sqlite3VdbeFinalize() should be
65431** used to clean up the mess that was left behind.
65432*/
65433SQLITE_PRIVATE int sqlite3VdbeExec(
65434  Vdbe *p                    /* The VDBE */
65435){
65436  int pc=0;                  /* The program counter */
65437  Op *aOp = p->aOp;          /* Copy of p->aOp */
65438  Op *pOp;                   /* Current operation */
65439  int rc = SQLITE_OK;        /* Value to return */
65440  sqlite3 *db = p->db;       /* The database */
65441  u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
65442  u8 encoding = ENC(db);     /* The database encoding */
65443#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
65444  int checkProgress;         /* True if progress callbacks are enabled */
65445  int nProgressOps = 0;      /* Opcodes executed since progress callback. */
65446#endif
65447  Mem *aMem = p->aMem;       /* Copy of p->aMem */
65448  Mem *pIn1 = 0;             /* 1st input operand */
65449  Mem *pIn2 = 0;             /* 2nd input operand */
65450  Mem *pIn3 = 0;             /* 3rd input operand */
65451  Mem *pOut = 0;             /* Output operand */
65452  int iCompare = 0;          /* Result of last OP_Compare operation */
65453  int *aPermute = 0;         /* Permutation of columns for OP_Compare */
65454  i64 lastRowid = db->lastRowid;  /* Saved value of the last insert ROWID */
65455#ifdef VDBE_PROFILE
65456  u64 start;                 /* CPU clock count at start of opcode */
65457  int origPc;                /* Program counter at start of opcode */
65458#endif
65459  /********************************************************************
65460  ** Automatically generated code
65461  **
65462  ** The following union is automatically generated by the
65463  ** vdbe-compress.tcl script.  The purpose of this union is to
65464  ** reduce the amount of stack space required by this function.
65465  ** See comments in the vdbe-compress.tcl script for details.
65466  */
65467  union vdbeExecUnion {
65468    struct OP_Yield_stack_vars {
65469      int pcDest;
65470    } aa;
65471    struct OP_Null_stack_vars {
65472      int cnt;
65473      u16 nullFlag;
65474    } ab;
65475    struct OP_Variable_stack_vars {
65476      Mem *pVar;       /* Value being transferred */
65477    } ac;
65478    struct OP_Move_stack_vars {
65479      char *zMalloc;   /* Holding variable for allocated memory */
65480      int n;           /* Number of registers left to copy */
65481      int p1;          /* Register to copy from */
65482      int p2;          /* Register to copy to */
65483    } ad;
65484    struct OP_Copy_stack_vars {
65485      int n;
65486    } ae;
65487    struct OP_ResultRow_stack_vars {
65488      Mem *pMem;
65489      int i;
65490    } af;
65491    struct OP_Concat_stack_vars {
65492      i64 nByte;
65493    } ag;
65494    struct OP_Remainder_stack_vars {
65495      char bIntint;   /* Started out as two integer operands */
65496      int flags;      /* Combined MEM_* flags from both inputs */
65497      i64 iA;         /* Integer value of left operand */
65498      i64 iB;         /* Integer value of right operand */
65499      double rA;      /* Real value of left operand */
65500      double rB;      /* Real value of right operand */
65501    } ah;
65502    struct OP_Function_stack_vars {
65503      int i;
65504      Mem *pArg;
65505      sqlite3_context ctx;
65506      sqlite3_value **apVal;
65507      int n;
65508    } ai;
65509    struct OP_ShiftRight_stack_vars {
65510      i64 iA;
65511      u64 uA;
65512      i64 iB;
65513      u8 op;
65514    } aj;
65515    struct OP_Ge_stack_vars {
65516      int res;            /* Result of the comparison of pIn1 against pIn3 */
65517      char affinity;      /* Affinity to use for comparison */
65518      u16 flags1;         /* Copy of initial value of pIn1->flags */
65519      u16 flags3;         /* Copy of initial value of pIn3->flags */
65520    } ak;
65521    struct OP_Compare_stack_vars {
65522      int n;
65523      int i;
65524      int p1;
65525      int p2;
65526      const KeyInfo *pKeyInfo;
65527      int idx;
65528      CollSeq *pColl;    /* Collating sequence to use on this term */
65529      int bRev;          /* True for DESCENDING sort order */
65530    } al;
65531    struct OP_Or_stack_vars {
65532      int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
65533      int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
65534    } am;
65535    struct OP_IfNot_stack_vars {
65536      int c;
65537    } an;
65538    struct OP_Column_stack_vars {
65539      u32 payloadSize;   /* Number of bytes in the record */
65540      i64 payloadSize64; /* Number of bytes in the record */
65541      int p1;            /* P1 value of the opcode */
65542      int p2;            /* column number to retrieve */
65543      VdbeCursor *pC;    /* The VDBE cursor */
65544      char *zRec;        /* Pointer to complete record-data */
65545      BtCursor *pCrsr;   /* The BTree cursor */
65546      u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
65547      u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
65548      int nField;        /* number of fields in the record */
65549      int len;           /* The length of the serialized data for the column */
65550      int i;             /* Loop counter */
65551      char *zData;       /* Part of the record being decoded */
65552      Mem *pDest;        /* Where to write the extracted value */
65553      Mem sMem;          /* For storing the record being decoded */
65554      u8 *zIdx;          /* Index into header */
65555      u8 *zEndHdr;       /* Pointer to first byte after the header */
65556      u32 offset;        /* Offset into the data */
65557      u32 szField;       /* Number of bytes in the content of a field */
65558      int szHdr;         /* Size of the header size field at start of record */
65559      int avail;         /* Number of bytes of available data */
65560      u32 t;             /* A type code from the record header */
65561      Mem *pReg;         /* PseudoTable input register */
65562    } ao;
65563    struct OP_Affinity_stack_vars {
65564      const char *zAffinity;   /* The affinity to be applied */
65565      char cAff;               /* A single character of affinity */
65566    } ap;
65567    struct OP_MakeRecord_stack_vars {
65568      u8 *zNewRecord;        /* A buffer to hold the data for the new record */
65569      Mem *pRec;             /* The new record */
65570      u64 nData;             /* Number of bytes of data space */
65571      int nHdr;              /* Number of bytes of header space */
65572      i64 nByte;             /* Data space required for this record */
65573      int nZero;             /* Number of zero bytes at the end of the record */
65574      int nVarint;           /* Number of bytes in a varint */
65575      u32 serial_type;       /* Type field */
65576      Mem *pData0;           /* First field to be combined into the record */
65577      Mem *pLast;            /* Last field of the record */
65578      int nField;            /* Number of fields in the record */
65579      char *zAffinity;       /* The affinity string for the record */
65580      int file_format;       /* File format to use for encoding */
65581      int i;                 /* Space used in zNewRecord[] */
65582      int len;               /* Length of a field */
65583    } aq;
65584    struct OP_Count_stack_vars {
65585      i64 nEntry;
65586      BtCursor *pCrsr;
65587    } ar;
65588    struct OP_Savepoint_stack_vars {
65589      int p1;                         /* Value of P1 operand */
65590      char *zName;                    /* Name of savepoint */
65591      int nName;
65592      Savepoint *pNew;
65593      Savepoint *pSavepoint;
65594      Savepoint *pTmp;
65595      int iSavepoint;
65596      int ii;
65597    } as;
65598    struct OP_AutoCommit_stack_vars {
65599      int desiredAutoCommit;
65600      int iRollback;
65601      int turnOnAC;
65602    } at;
65603    struct OP_Transaction_stack_vars {
65604      Btree *pBt;
65605    } au;
65606    struct OP_ReadCookie_stack_vars {
65607      int iMeta;
65608      int iDb;
65609      int iCookie;
65610    } av;
65611    struct OP_SetCookie_stack_vars {
65612      Db *pDb;
65613    } aw;
65614    struct OP_VerifyCookie_stack_vars {
65615      int iMeta;
65616      int iGen;
65617      Btree *pBt;
65618    } ax;
65619    struct OP_OpenWrite_stack_vars {
65620      int nField;
65621      KeyInfo *pKeyInfo;
65622      int p2;
65623      int iDb;
65624      int wrFlag;
65625      Btree *pX;
65626      VdbeCursor *pCur;
65627      Db *pDb;
65628    } ay;
65629    struct OP_OpenEphemeral_stack_vars {
65630      VdbeCursor *pCx;
65631    } az;
65632    struct OP_SorterOpen_stack_vars {
65633      VdbeCursor *pCx;
65634    } ba;
65635    struct OP_OpenPseudo_stack_vars {
65636      VdbeCursor *pCx;
65637    } bb;
65638    struct OP_SeekGt_stack_vars {
65639      int res;
65640      int oc;
65641      VdbeCursor *pC;
65642      UnpackedRecord r;
65643      int nField;
65644      i64 iKey;      /* The rowid we are to seek to */
65645    } bc;
65646    struct OP_Seek_stack_vars {
65647      VdbeCursor *pC;
65648    } bd;
65649    struct OP_Found_stack_vars {
65650      int alreadyExists;
65651      VdbeCursor *pC;
65652      int res;
65653      char *pFree;
65654      UnpackedRecord *pIdxKey;
65655      UnpackedRecord r;
65656      char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
65657    } be;
65658    struct OP_IsUnique_stack_vars {
65659      u16 ii;
65660      VdbeCursor *pCx;
65661      BtCursor *pCrsr;
65662      u16 nField;
65663      Mem *aMx;
65664      UnpackedRecord r;                  /* B-Tree index search key */
65665      i64 R;                             /* Rowid stored in register P3 */
65666    } bf;
65667    struct OP_NotExists_stack_vars {
65668      VdbeCursor *pC;
65669      BtCursor *pCrsr;
65670      int res;
65671      u64 iKey;
65672    } bg;
65673    struct OP_NewRowid_stack_vars {
65674      i64 v;                 /* The new rowid */
65675      VdbeCursor *pC;        /* Cursor of table to get the new rowid */
65676      int res;               /* Result of an sqlite3BtreeLast() */
65677      int cnt;               /* Counter to limit the number of searches */
65678      Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
65679      VdbeFrame *pFrame;     /* Root frame of VDBE */
65680    } bh;
65681    struct OP_InsertInt_stack_vars {
65682      Mem *pData;       /* MEM cell holding data for the record to be inserted */
65683      Mem *pKey;        /* MEM cell holding key  for the record */
65684      i64 iKey;         /* The integer ROWID or key for the record to be inserted */
65685      VdbeCursor *pC;   /* Cursor to table into which insert is written */
65686      int nZero;        /* Number of zero-bytes to append */
65687      int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
65688      const char *zDb;  /* database name - used by the update hook */
65689      const char *zTbl; /* Table name - used by the opdate hook */
65690      int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
65691    } bi;
65692    struct OP_Delete_stack_vars {
65693      i64 iKey;
65694      VdbeCursor *pC;
65695    } bj;
65696    struct OP_SorterCompare_stack_vars {
65697      VdbeCursor *pC;
65698      int res;
65699    } bk;
65700    struct OP_SorterData_stack_vars {
65701      VdbeCursor *pC;
65702    } bl;
65703    struct OP_RowData_stack_vars {
65704      VdbeCursor *pC;
65705      BtCursor *pCrsr;
65706      u32 n;
65707      i64 n64;
65708    } bm;
65709    struct OP_Rowid_stack_vars {
65710      VdbeCursor *pC;
65711      i64 v;
65712      sqlite3_vtab *pVtab;
65713      const sqlite3_module *pModule;
65714    } bn;
65715    struct OP_NullRow_stack_vars {
65716      VdbeCursor *pC;
65717    } bo;
65718    struct OP_Last_stack_vars {
65719      VdbeCursor *pC;
65720      BtCursor *pCrsr;
65721      int res;
65722    } bp;
65723    struct OP_Rewind_stack_vars {
65724      VdbeCursor *pC;
65725      BtCursor *pCrsr;
65726      int res;
65727    } bq;
65728    struct OP_Next_stack_vars {
65729      VdbeCursor *pC;
65730      int res;
65731    } br;
65732    struct OP_IdxInsert_stack_vars {
65733      VdbeCursor *pC;
65734      BtCursor *pCrsr;
65735      int nKey;
65736      const char *zKey;
65737    } bs;
65738    struct OP_IdxDelete_stack_vars {
65739      VdbeCursor *pC;
65740      BtCursor *pCrsr;
65741      int res;
65742      UnpackedRecord r;
65743    } bt;
65744    struct OP_IdxRowid_stack_vars {
65745      BtCursor *pCrsr;
65746      VdbeCursor *pC;
65747      i64 rowid;
65748    } bu;
65749    struct OP_IdxGE_stack_vars {
65750      VdbeCursor *pC;
65751      int res;
65752      UnpackedRecord r;
65753    } bv;
65754    struct OP_Destroy_stack_vars {
65755      int iMoved;
65756      int iCnt;
65757      Vdbe *pVdbe;
65758      int iDb;
65759    } bw;
65760    struct OP_Clear_stack_vars {
65761      int nChange;
65762    } bx;
65763    struct OP_CreateTable_stack_vars {
65764      int pgno;
65765      int flags;
65766      Db *pDb;
65767    } by;
65768    struct OP_ParseSchema_stack_vars {
65769      int iDb;
65770      const char *zMaster;
65771      char *zSql;
65772      InitData initData;
65773    } bz;
65774    struct OP_IntegrityCk_stack_vars {
65775      int nRoot;      /* Number of tables to check.  (Number of root pages.) */
65776      int *aRoot;     /* Array of rootpage numbers for tables to be checked */
65777      int j;          /* Loop counter */
65778      int nErr;       /* Number of errors reported */
65779      char *z;        /* Text of the error report */
65780      Mem *pnErr;     /* Register keeping track of errors remaining */
65781    } ca;
65782    struct OP_RowSetRead_stack_vars {
65783      i64 val;
65784    } cb;
65785    struct OP_RowSetTest_stack_vars {
65786      int iSet;
65787      int exists;
65788    } cc;
65789    struct OP_Program_stack_vars {
65790      int nMem;               /* Number of memory registers for sub-program */
65791      int nByte;              /* Bytes of runtime space required for sub-program */
65792      Mem *pRt;               /* Register to allocate runtime space */
65793      Mem *pMem;              /* Used to iterate through memory cells */
65794      Mem *pEnd;              /* Last memory cell in new array */
65795      VdbeFrame *pFrame;      /* New vdbe frame to execute in */
65796      SubProgram *pProgram;   /* Sub-program to execute */
65797      void *t;                /* Token identifying trigger */
65798    } cd;
65799    struct OP_Param_stack_vars {
65800      VdbeFrame *pFrame;
65801      Mem *pIn;
65802    } ce;
65803    struct OP_MemMax_stack_vars {
65804      Mem *pIn1;
65805      VdbeFrame *pFrame;
65806    } cf;
65807    struct OP_AggStep_stack_vars {
65808      int n;
65809      int i;
65810      Mem *pMem;
65811      Mem *pRec;
65812      sqlite3_context ctx;
65813      sqlite3_value **apVal;
65814    } cg;
65815    struct OP_AggFinal_stack_vars {
65816      Mem *pMem;
65817    } ch;
65818    struct OP_Checkpoint_stack_vars {
65819      int i;                          /* Loop counter */
65820      int aRes[3];                    /* Results */
65821      Mem *pMem;                      /* Write results here */
65822    } ci;
65823    struct OP_JournalMode_stack_vars {
65824      Btree *pBt;                     /* Btree to change journal mode of */
65825      Pager *pPager;                  /* Pager associated with pBt */
65826      int eNew;                       /* New journal mode */
65827      int eOld;                       /* The old journal mode */
65828#ifndef SQLITE_OMIT_WAL
65829      const char *zFilename;          /* Name of database file for pPager */
65830#endif
65831    } cj;
65832    struct OP_IncrVacuum_stack_vars {
65833      Btree *pBt;
65834    } ck;
65835    struct OP_VBegin_stack_vars {
65836      VTable *pVTab;
65837    } cl;
65838    struct OP_VOpen_stack_vars {
65839      VdbeCursor *pCur;
65840      sqlite3_vtab_cursor *pVtabCursor;
65841      sqlite3_vtab *pVtab;
65842      sqlite3_module *pModule;
65843    } cm;
65844    struct OP_VFilter_stack_vars {
65845      int nArg;
65846      int iQuery;
65847      const sqlite3_module *pModule;
65848      Mem *pQuery;
65849      Mem *pArgc;
65850      sqlite3_vtab_cursor *pVtabCursor;
65851      sqlite3_vtab *pVtab;
65852      VdbeCursor *pCur;
65853      int res;
65854      int i;
65855      Mem **apArg;
65856    } cn;
65857    struct OP_VColumn_stack_vars {
65858      sqlite3_vtab *pVtab;
65859      const sqlite3_module *pModule;
65860      Mem *pDest;
65861      sqlite3_context sContext;
65862    } co;
65863    struct OP_VNext_stack_vars {
65864      sqlite3_vtab *pVtab;
65865      const sqlite3_module *pModule;
65866      int res;
65867      VdbeCursor *pCur;
65868    } cp;
65869    struct OP_VRename_stack_vars {
65870      sqlite3_vtab *pVtab;
65871      Mem *pName;
65872    } cq;
65873    struct OP_VUpdate_stack_vars {
65874      sqlite3_vtab *pVtab;
65875      sqlite3_module *pModule;
65876      int nArg;
65877      int i;
65878      sqlite_int64 rowid;
65879      Mem **apArg;
65880      Mem *pX;
65881    } cr;
65882    struct OP_Trace_stack_vars {
65883      char *zTrace;
65884      char *z;
65885    } cs;
65886  } u;
65887  /* End automatically generated code
65888  ********************************************************************/
65889
65890  assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
65891  sqlite3VdbeEnter(p);
65892  if( p->rc==SQLITE_NOMEM ){
65893    /* This happens if a malloc() inside a call to sqlite3_column_text() or
65894    ** sqlite3_column_text16() failed.  */
65895    goto no_mem;
65896  }
65897  assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
65898  p->rc = SQLITE_OK;
65899  assert( p->explain==0 );
65900  p->pResultSet = 0;
65901  db->busyHandler.nBusy = 0;
65902  CHECK_FOR_INTERRUPT;
65903  sqlite3VdbeIOTraceSql(p);
65904#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
65905  checkProgress = db->xProgress!=0;
65906#endif
65907#ifdef SQLITE_DEBUG
65908  sqlite3BeginBenignMalloc();
65909  if( p->pc==0  && (p->db->flags & SQLITE_VdbeListing)!=0 ){
65910    int i;
65911    printf("VDBE Program Listing:\n");
65912    sqlite3VdbePrintSql(p);
65913    for(i=0; i<p->nOp; i++){
65914      sqlite3VdbePrintOp(stdout, i, &aOp[i]);
65915    }
65916  }
65917  sqlite3EndBenignMalloc();
65918#endif
65919  for(pc=p->pc; rc==SQLITE_OK; pc++){
65920    assert( pc>=0 && pc<p->nOp );
65921    if( db->mallocFailed ) goto no_mem;
65922#ifdef VDBE_PROFILE
65923    origPc = pc;
65924    start = sqlite3Hwtime();
65925#endif
65926    pOp = &aOp[pc];
65927
65928    /* Only allow tracing if SQLITE_DEBUG is defined.
65929    */
65930#ifdef SQLITE_DEBUG
65931    if( p->trace ){
65932      if( pc==0 ){
65933        printf("VDBE Execution Trace:\n");
65934        sqlite3VdbePrintSql(p);
65935      }
65936      sqlite3VdbePrintOp(p->trace, pc, pOp);
65937    }
65938#endif
65939
65940
65941    /* Check to see if we need to simulate an interrupt.  This only happens
65942    ** if we have a special test build.
65943    */
65944#ifdef SQLITE_TEST
65945    if( sqlite3_interrupt_count>0 ){
65946      sqlite3_interrupt_count--;
65947      if( sqlite3_interrupt_count==0 ){
65948        sqlite3_interrupt(db);
65949      }
65950    }
65951#endif
65952
65953#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
65954    /* Call the progress callback if it is configured and the required number
65955    ** of VDBE ops have been executed (either since this invocation of
65956    ** sqlite3VdbeExec() or since last time the progress callback was called).
65957    ** If the progress callback returns non-zero, exit the virtual machine with
65958    ** a return code SQLITE_ABORT.
65959    */
65960    if( checkProgress ){
65961      if( db->nProgressOps==nProgressOps ){
65962        int prc;
65963        prc = db->xProgress(db->pProgressArg);
65964        if( prc!=0 ){
65965          rc = SQLITE_INTERRUPT;
65966          goto vdbe_error_halt;
65967        }
65968        nProgressOps = 0;
65969      }
65970      nProgressOps++;
65971    }
65972#endif
65973
65974    /* On any opcode with the "out2-prerelease" tag, free any
65975    ** external allocations out of mem[p2] and set mem[p2] to be
65976    ** an undefined integer.  Opcodes will either fill in the integer
65977    ** value or convert mem[p2] to a different type.
65978    */
65979    assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
65980    if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
65981      assert( pOp->p2>0 );
65982      assert( pOp->p2<=p->nMem );
65983      pOut = &aMem[pOp->p2];
65984      memAboutToChange(p, pOut);
65985      VdbeMemRelease(pOut);
65986      pOut->flags = MEM_Int;
65987    }
65988
65989    /* Sanity checking on other operands */
65990#ifdef SQLITE_DEBUG
65991    if( (pOp->opflags & OPFLG_IN1)!=0 ){
65992      assert( pOp->p1>0 );
65993      assert( pOp->p1<=p->nMem );
65994      assert( memIsValid(&aMem[pOp->p1]) );
65995      REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
65996    }
65997    if( (pOp->opflags & OPFLG_IN2)!=0 ){
65998      assert( pOp->p2>0 );
65999      assert( pOp->p2<=p->nMem );
66000      assert( memIsValid(&aMem[pOp->p2]) );
66001      REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
66002    }
66003    if( (pOp->opflags & OPFLG_IN3)!=0 ){
66004      assert( pOp->p3>0 );
66005      assert( pOp->p3<=p->nMem );
66006      assert( memIsValid(&aMem[pOp->p3]) );
66007      REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
66008    }
66009    if( (pOp->opflags & OPFLG_OUT2)!=0 ){
66010      assert( pOp->p2>0 );
66011      assert( pOp->p2<=p->nMem );
66012      memAboutToChange(p, &aMem[pOp->p2]);
66013    }
66014    if( (pOp->opflags & OPFLG_OUT3)!=0 ){
66015      assert( pOp->p3>0 );
66016      assert( pOp->p3<=p->nMem );
66017      memAboutToChange(p, &aMem[pOp->p3]);
66018    }
66019#endif
66020
66021    switch( pOp->opcode ){
66022
66023/*****************************************************************************
66024** What follows is a massive switch statement where each case implements a
66025** separate instruction in the virtual machine.  If we follow the usual
66026** indentation conventions, each case should be indented by 6 spaces.  But
66027** that is a lot of wasted space on the left margin.  So the code within
66028** the switch statement will break with convention and be flush-left. Another
66029** big comment (similar to this one) will mark the point in the code where
66030** we transition back to normal indentation.
66031**
66032** The formatting of each case is important.  The makefile for SQLite
66033** generates two C files "opcodes.h" and "opcodes.c" by scanning this
66034** file looking for lines that begin with "case OP_".  The opcodes.h files
66035** will be filled with #defines that give unique integer values to each
66036** opcode and the opcodes.c file is filled with an array of strings where
66037** each string is the symbolic name for the corresponding opcode.  If the
66038** case statement is followed by a comment of the form "/# same as ... #/"
66039** that comment is used to determine the particular value of the opcode.
66040**
66041** Other keywords in the comment that follows each case are used to
66042** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
66043** Keywords include: in1, in2, in3, out2_prerelease, out2, out3.  See
66044** the mkopcodeh.awk script for additional information.
66045**
66046** Documentation about VDBE opcodes is generated by scanning this file
66047** for lines of that contain "Opcode:".  That line and all subsequent
66048** comment lines are used in the generation of the opcode.html documentation
66049** file.
66050**
66051** SUMMARY:
66052**
66053**     Formatting is important to scripts that scan this file.
66054**     Do not deviate from the formatting style currently in use.
66055**
66056*****************************************************************************/
66057
66058/* Opcode:  Goto * P2 * * *
66059**
66060** An unconditional jump to address P2.
66061** The next instruction executed will be
66062** the one at index P2 from the beginning of
66063** the program.
66064*/
66065case OP_Goto: {             /* jump */
66066  CHECK_FOR_INTERRUPT;
66067  pc = pOp->p2 - 1;
66068  break;
66069}
66070
66071/* Opcode:  Gosub P1 P2 * * *
66072**
66073** Write the current address onto register P1
66074** and then jump to address P2.
66075*/
66076case OP_Gosub: {            /* jump */
66077  assert( pOp->p1>0 && pOp->p1<=p->nMem );
66078  pIn1 = &aMem[pOp->p1];
66079  assert( (pIn1->flags & MEM_Dyn)==0 );
66080  memAboutToChange(p, pIn1);
66081  pIn1->flags = MEM_Int;
66082  pIn1->u.i = pc;
66083  REGISTER_TRACE(pOp->p1, pIn1);
66084  pc = pOp->p2 - 1;
66085  break;
66086}
66087
66088/* Opcode:  Return P1 * * * *
66089**
66090** Jump to the next instruction after the address in register P1.
66091*/
66092case OP_Return: {           /* in1 */
66093  pIn1 = &aMem[pOp->p1];
66094  assert( pIn1->flags & MEM_Int );
66095  pc = (int)pIn1->u.i;
66096  break;
66097}
66098
66099/* Opcode:  Yield P1 * * * *
66100**
66101** Swap the program counter with the value in register P1.
66102*/
66103case OP_Yield: {            /* in1 */
66104#if 0  /* local variables moved into u.aa */
66105  int pcDest;
66106#endif /* local variables moved into u.aa */
66107  pIn1 = &aMem[pOp->p1];
66108  assert( (pIn1->flags & MEM_Dyn)==0 );
66109  pIn1->flags = MEM_Int;
66110  u.aa.pcDest = (int)pIn1->u.i;
66111  pIn1->u.i = pc;
66112  REGISTER_TRACE(pOp->p1, pIn1);
66113  pc = u.aa.pcDest;
66114  break;
66115}
66116
66117/* Opcode:  HaltIfNull  P1 P2 P3 P4 *
66118**
66119** Check the value in register P3.  If it is NULL then Halt using
66120** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
66121** value in register P3 is not NULL, then this routine is a no-op.
66122*/
66123case OP_HaltIfNull: {      /* in3 */
66124  pIn3 = &aMem[pOp->p3];
66125  if( (pIn3->flags & MEM_Null)==0 ) break;
66126  /* Fall through into OP_Halt */
66127}
66128
66129/* Opcode:  Halt P1 P2 * P4 *
66130**
66131** Exit immediately.  All open cursors, etc are closed
66132** automatically.
66133**
66134** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
66135** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
66136** For errors, it can be some other value.  If P1!=0 then P2 will determine
66137** whether or not to rollback the current transaction.  Do not rollback
66138** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
66139** then back out all changes that have occurred during this execution of the
66140** VDBE, but do not rollback the transaction.
66141**
66142** If P4 is not null then it is an error message string.
66143**
66144** There is an implied "Halt 0 0 0" instruction inserted at the very end of
66145** every program.  So a jump past the last instruction of the program
66146** is the same as executing Halt.
66147*/
66148case OP_Halt: {
66149  if( pOp->p1==SQLITE_OK && p->pFrame ){
66150    /* Halt the sub-program. Return control to the parent frame. */
66151    VdbeFrame *pFrame = p->pFrame;
66152    p->pFrame = pFrame->pParent;
66153    p->nFrame--;
66154    sqlite3VdbeSetChanges(db, p->nChange);
66155    pc = sqlite3VdbeFrameRestore(pFrame);
66156    lastRowid = db->lastRowid;
66157    if( pOp->p2==OE_Ignore ){
66158      /* Instruction pc is the OP_Program that invoked the sub-program
66159      ** currently being halted. If the p2 instruction of this OP_Halt
66160      ** instruction is set to OE_Ignore, then the sub-program is throwing
66161      ** an IGNORE exception. In this case jump to the address specified
66162      ** as the p2 of the calling OP_Program.  */
66163      pc = p->aOp[pc].p2-1;
66164    }
66165    aOp = p->aOp;
66166    aMem = p->aMem;
66167    break;
66168  }
66169
66170  p->rc = pOp->p1;
66171  p->errorAction = (u8)pOp->p2;
66172  p->pc = pc;
66173  if( pOp->p4.z ){
66174    assert( p->rc!=SQLITE_OK );
66175    sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
66176    testcase( sqlite3GlobalConfig.xLog!=0 );
66177    sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pc, p->zSql, pOp->p4.z);
66178  }else if( p->rc ){
66179    testcase( sqlite3GlobalConfig.xLog!=0 );
66180    sqlite3_log(pOp->p1, "constraint failed at %d in [%s]", pc, p->zSql);
66181  }
66182  rc = sqlite3VdbeHalt(p);
66183  assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
66184  if( rc==SQLITE_BUSY ){
66185    p->rc = rc = SQLITE_BUSY;
66186  }else{
66187    assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
66188    assert( rc==SQLITE_OK || db->nDeferredCons>0 );
66189    rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
66190  }
66191  goto vdbe_return;
66192}
66193
66194/* Opcode: Integer P1 P2 * * *
66195**
66196** The 32-bit integer value P1 is written into register P2.
66197*/
66198case OP_Integer: {         /* out2-prerelease */
66199  pOut->u.i = pOp->p1;
66200  break;
66201}
66202
66203/* Opcode: Int64 * P2 * P4 *
66204**
66205** P4 is a pointer to a 64-bit integer value.
66206** Write that value into register P2.
66207*/
66208case OP_Int64: {           /* out2-prerelease */
66209  assert( pOp->p4.pI64!=0 );
66210  pOut->u.i = *pOp->p4.pI64;
66211  break;
66212}
66213
66214#ifndef SQLITE_OMIT_FLOATING_POINT
66215/* Opcode: Real * P2 * P4 *
66216**
66217** P4 is a pointer to a 64-bit floating point value.
66218** Write that value into register P2.
66219*/
66220case OP_Real: {            /* same as TK_FLOAT, out2-prerelease */
66221  pOut->flags = MEM_Real;
66222  assert( !sqlite3IsNaN(*pOp->p4.pReal) );
66223  pOut->r = *pOp->p4.pReal;
66224  break;
66225}
66226#endif
66227
66228/* Opcode: String8 * P2 * P4 *
66229**
66230** P4 points to a nul terminated UTF-8 string. This opcode is transformed
66231** into an OP_String before it is executed for the first time.
66232*/
66233case OP_String8: {         /* same as TK_STRING, out2-prerelease */
66234  assert( pOp->p4.z!=0 );
66235  pOp->opcode = OP_String;
66236  pOp->p1 = sqlite3Strlen30(pOp->p4.z);
66237
66238#ifndef SQLITE_OMIT_UTF16
66239  if( encoding!=SQLITE_UTF8 ){
66240    rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
66241    if( rc==SQLITE_TOOBIG ) goto too_big;
66242    if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
66243    assert( pOut->zMalloc==pOut->z );
66244    assert( pOut->flags & MEM_Dyn );
66245    pOut->zMalloc = 0;
66246    pOut->flags |= MEM_Static;
66247    pOut->flags &= ~MEM_Dyn;
66248    if( pOp->p4type==P4_DYNAMIC ){
66249      sqlite3DbFree(db, pOp->p4.z);
66250    }
66251    pOp->p4type = P4_DYNAMIC;
66252    pOp->p4.z = pOut->z;
66253    pOp->p1 = pOut->n;
66254  }
66255#endif
66256  if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
66257    goto too_big;
66258  }
66259  /* Fall through to the next case, OP_String */
66260}
66261
66262/* Opcode: String P1 P2 * P4 *
66263**
66264** The string value P4 of length P1 (bytes) is stored in register P2.
66265*/
66266case OP_String: {          /* out2-prerelease */
66267  assert( pOp->p4.z!=0 );
66268  pOut->flags = MEM_Str|MEM_Static|MEM_Term;
66269  pOut->z = pOp->p4.z;
66270  pOut->n = pOp->p1;
66271  pOut->enc = encoding;
66272  UPDATE_MAX_BLOBSIZE(pOut);
66273  break;
66274}
66275
66276/* Opcode: Null P1 P2 P3 * *
66277**
66278** Write a NULL into registers P2.  If P3 greater than P2, then also write
66279** NULL into register P3 and every register in between P2 and P3.  If P3
66280** is less than P2 (typically P3 is zero) then only register P2 is
66281** set to NULL.
66282**
66283** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
66284** NULL values will not compare equal even if SQLITE_NULLEQ is set on
66285** OP_Ne or OP_Eq.
66286*/
66287case OP_Null: {           /* out2-prerelease */
66288#if 0  /* local variables moved into u.ab */
66289  int cnt;
66290  u16 nullFlag;
66291#endif /* local variables moved into u.ab */
66292  u.ab.cnt = pOp->p3-pOp->p2;
66293  assert( pOp->p3<=p->nMem );
66294  pOut->flags = u.ab.nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
66295  while( u.ab.cnt>0 ){
66296    pOut++;
66297    memAboutToChange(p, pOut);
66298    VdbeMemRelease(pOut);
66299    pOut->flags = u.ab.nullFlag;
66300    u.ab.cnt--;
66301  }
66302  break;
66303}
66304
66305
66306/* Opcode: Blob P1 P2 * P4
66307**
66308** P4 points to a blob of data P1 bytes long.  Store this
66309** blob in register P2.
66310*/
66311case OP_Blob: {                /* out2-prerelease */
66312  assert( pOp->p1 <= SQLITE_MAX_LENGTH );
66313  sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
66314  pOut->enc = encoding;
66315  UPDATE_MAX_BLOBSIZE(pOut);
66316  break;
66317}
66318
66319/* Opcode: Variable P1 P2 * P4 *
66320**
66321** Transfer the values of bound parameter P1 into register P2
66322**
66323** If the parameter is named, then its name appears in P4 and P3==1.
66324** The P4 value is used by sqlite3_bind_parameter_name().
66325*/
66326case OP_Variable: {            /* out2-prerelease */
66327#if 0  /* local variables moved into u.ac */
66328  Mem *pVar;       /* Value being transferred */
66329#endif /* local variables moved into u.ac */
66330
66331  assert( pOp->p1>0 && pOp->p1<=p->nVar );
66332  assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] );
66333  u.ac.pVar = &p->aVar[pOp->p1 - 1];
66334  if( sqlite3VdbeMemTooBig(u.ac.pVar) ){
66335    goto too_big;
66336  }
66337  sqlite3VdbeMemShallowCopy(pOut, u.ac.pVar, MEM_Static);
66338  UPDATE_MAX_BLOBSIZE(pOut);
66339  break;
66340}
66341
66342/* Opcode: Move P1 P2 P3 * *
66343**
66344** Move the values in register P1..P1+P3 over into
66345** registers P2..P2+P3.  Registers P1..P1+P3 are
66346** left holding a NULL.  It is an error for register ranges
66347** P1..P1+P3 and P2..P2+P3 to overlap.
66348*/
66349case OP_Move: {
66350#if 0  /* local variables moved into u.ad */
66351  char *zMalloc;   /* Holding variable for allocated memory */
66352  int n;           /* Number of registers left to copy */
66353  int p1;          /* Register to copy from */
66354  int p2;          /* Register to copy to */
66355#endif /* local variables moved into u.ad */
66356
66357  u.ad.n = pOp->p3 + 1;
66358  u.ad.p1 = pOp->p1;
66359  u.ad.p2 = pOp->p2;
66360  assert( u.ad.n>0 && u.ad.p1>0 && u.ad.p2>0 );
66361  assert( u.ad.p1+u.ad.n<=u.ad.p2 || u.ad.p2+u.ad.n<=u.ad.p1 );
66362
66363  pIn1 = &aMem[u.ad.p1];
66364  pOut = &aMem[u.ad.p2];
66365  while( u.ad.n-- ){
66366    assert( pOut<=&aMem[p->nMem] );
66367    assert( pIn1<=&aMem[p->nMem] );
66368    assert( memIsValid(pIn1) );
66369    memAboutToChange(p, pOut);
66370    u.ad.zMalloc = pOut->zMalloc;
66371    pOut->zMalloc = 0;
66372    sqlite3VdbeMemMove(pOut, pIn1);
66373#ifdef SQLITE_DEBUG
66374    if( pOut->pScopyFrom>=&aMem[u.ad.p1] && pOut->pScopyFrom<&aMem[u.ad.p1+pOp->p3] ){
66375      pOut->pScopyFrom += u.ad.p1 - pOp->p2;
66376    }
66377#endif
66378    pIn1->zMalloc = u.ad.zMalloc;
66379    REGISTER_TRACE(u.ad.p2++, pOut);
66380    pIn1++;
66381    pOut++;
66382  }
66383  break;
66384}
66385
66386/* Opcode: Copy P1 P2 P3 * *
66387**
66388** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
66389**
66390** This instruction makes a deep copy of the value.  A duplicate
66391** is made of any string or blob constant.  See also OP_SCopy.
66392*/
66393case OP_Copy: {
66394#if 0  /* local variables moved into u.ae */
66395  int n;
66396#endif /* local variables moved into u.ae */
66397
66398  u.ae.n = pOp->p3;
66399  pIn1 = &aMem[pOp->p1];
66400  pOut = &aMem[pOp->p2];
66401  assert( pOut!=pIn1 );
66402  while( 1 ){
66403    sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
66404    Deephemeralize(pOut);
66405#ifdef SQLITE_DEBUG
66406    pOut->pScopyFrom = 0;
66407#endif
66408    REGISTER_TRACE(pOp->p2+pOp->p3-u.ae.n, pOut);
66409    if( (u.ae.n--)==0 ) break;
66410    pOut++;
66411    pIn1++;
66412  }
66413  break;
66414}
66415
66416/* Opcode: SCopy P1 P2 * * *
66417**
66418** Make a shallow copy of register P1 into register P2.
66419**
66420** This instruction makes a shallow copy of the value.  If the value
66421** is a string or blob, then the copy is only a pointer to the
66422** original and hence if the original changes so will the copy.
66423** Worse, if the original is deallocated, the copy becomes invalid.
66424** Thus the program must guarantee that the original will not change
66425** during the lifetime of the copy.  Use OP_Copy to make a complete
66426** copy.
66427*/
66428case OP_SCopy: {            /* in1, out2 */
66429  pIn1 = &aMem[pOp->p1];
66430  pOut = &aMem[pOp->p2];
66431  assert( pOut!=pIn1 );
66432  sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
66433#ifdef SQLITE_DEBUG
66434  if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
66435#endif
66436  REGISTER_TRACE(pOp->p2, pOut);
66437  break;
66438}
66439
66440/* Opcode: ResultRow P1 P2 * * *
66441**
66442** The registers P1 through P1+P2-1 contain a single row of
66443** results. This opcode causes the sqlite3_step() call to terminate
66444** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
66445** structure to provide access to the top P1 values as the result
66446** row.
66447*/
66448case OP_ResultRow: {
66449#if 0  /* local variables moved into u.af */
66450  Mem *pMem;
66451  int i;
66452#endif /* local variables moved into u.af */
66453  assert( p->nResColumn==pOp->p2 );
66454  assert( pOp->p1>0 );
66455  assert( pOp->p1+pOp->p2<=p->nMem+1 );
66456
66457  /* If this statement has violated immediate foreign key constraints, do
66458  ** not return the number of rows modified. And do not RELEASE the statement
66459  ** transaction. It needs to be rolled back.  */
66460  if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
66461    assert( db->flags&SQLITE_CountRows );
66462    assert( p->usesStmtJournal );
66463    break;
66464  }
66465
66466  /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
66467  ** DML statements invoke this opcode to return the number of rows
66468  ** modified to the user. This is the only way that a VM that
66469  ** opens a statement transaction may invoke this opcode.
66470  **
66471  ** In case this is such a statement, close any statement transaction
66472  ** opened by this VM before returning control to the user. This is to
66473  ** ensure that statement-transactions are always nested, not overlapping.
66474  ** If the open statement-transaction is not closed here, then the user
66475  ** may step another VM that opens its own statement transaction. This
66476  ** may lead to overlapping statement transactions.
66477  **
66478  ** The statement transaction is never a top-level transaction.  Hence
66479  ** the RELEASE call below can never fail.
66480  */
66481  assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
66482  rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
66483  if( NEVER(rc!=SQLITE_OK) ){
66484    break;
66485  }
66486
66487  /* Invalidate all ephemeral cursor row caches */
66488  p->cacheCtr = (p->cacheCtr + 2)|1;
66489
66490  /* Make sure the results of the current row are \000 terminated
66491  ** and have an assigned type.  The results are de-ephemeralized as
66492  ** a side effect.
66493  */
66494  u.af.pMem = p->pResultSet = &aMem[pOp->p1];
66495  for(u.af.i=0; u.af.i<pOp->p2; u.af.i++){
66496    assert( memIsValid(&u.af.pMem[u.af.i]) );
66497    Deephemeralize(&u.af.pMem[u.af.i]);
66498    assert( (u.af.pMem[u.af.i].flags & MEM_Ephem)==0
66499            || (u.af.pMem[u.af.i].flags & (MEM_Str|MEM_Blob))==0 );
66500    sqlite3VdbeMemNulTerminate(&u.af.pMem[u.af.i]);
66501    sqlite3VdbeMemStoreType(&u.af.pMem[u.af.i]);
66502    REGISTER_TRACE(pOp->p1+u.af.i, &u.af.pMem[u.af.i]);
66503  }
66504  if( db->mallocFailed ) goto no_mem;
66505
66506  /* Return SQLITE_ROW
66507  */
66508  p->pc = pc + 1;
66509  rc = SQLITE_ROW;
66510  goto vdbe_return;
66511}
66512
66513/* Opcode: Concat P1 P2 P3 * *
66514**
66515** Add the text in register P1 onto the end of the text in
66516** register P2 and store the result in register P3.
66517** If either the P1 or P2 text are NULL then store NULL in P3.
66518**
66519**   P3 = P2 || P1
66520**
66521** It is illegal for P1 and P3 to be the same register. Sometimes,
66522** if P3 is the same register as P2, the implementation is able
66523** to avoid a memcpy().
66524*/
66525case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
66526#if 0  /* local variables moved into u.ag */
66527  i64 nByte;
66528#endif /* local variables moved into u.ag */
66529
66530  pIn1 = &aMem[pOp->p1];
66531  pIn2 = &aMem[pOp->p2];
66532  pOut = &aMem[pOp->p3];
66533  assert( pIn1!=pOut );
66534  if( (pIn1->flags | pIn2->flags) & MEM_Null ){
66535    sqlite3VdbeMemSetNull(pOut);
66536    break;
66537  }
66538  if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
66539  Stringify(pIn1, encoding);
66540  Stringify(pIn2, encoding);
66541  u.ag.nByte = pIn1->n + pIn2->n;
66542  if( u.ag.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
66543    goto too_big;
66544  }
66545  MemSetTypeFlag(pOut, MEM_Str);
66546  if( sqlite3VdbeMemGrow(pOut, (int)u.ag.nByte+2, pOut==pIn2) ){
66547    goto no_mem;
66548  }
66549  if( pOut!=pIn2 ){
66550    memcpy(pOut->z, pIn2->z, pIn2->n);
66551  }
66552  memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
66553  pOut->z[u.ag.nByte] = 0;
66554  pOut->z[u.ag.nByte+1] = 0;
66555  pOut->flags |= MEM_Term;
66556  pOut->n = (int)u.ag.nByte;
66557  pOut->enc = encoding;
66558  UPDATE_MAX_BLOBSIZE(pOut);
66559  break;
66560}
66561
66562/* Opcode: Add P1 P2 P3 * *
66563**
66564** Add the value in register P1 to the value in register P2
66565** and store the result in register P3.
66566** If either input is NULL, the result is NULL.
66567*/
66568/* Opcode: Multiply P1 P2 P3 * *
66569**
66570**
66571** Multiply the value in register P1 by the value in register P2
66572** and store the result in register P3.
66573** If either input is NULL, the result is NULL.
66574*/
66575/* Opcode: Subtract P1 P2 P3 * *
66576**
66577** Subtract the value in register P1 from the value in register P2
66578** and store the result in register P3.
66579** If either input is NULL, the result is NULL.
66580*/
66581/* Opcode: Divide P1 P2 P3 * *
66582**
66583** Divide the value in register P1 by the value in register P2
66584** and store the result in register P3 (P3=P2/P1). If the value in
66585** register P1 is zero, then the result is NULL. If either input is
66586** NULL, the result is NULL.
66587*/
66588/* Opcode: Remainder P1 P2 P3 * *
66589**
66590** Compute the remainder after integer division of the value in
66591** register P1 by the value in register P2 and store the result in P3.
66592** If the value in register P2 is zero the result is NULL.
66593** If either operand is NULL, the result is NULL.
66594*/
66595case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
66596case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
66597case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
66598case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
66599case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
66600#if 0  /* local variables moved into u.ah */
66601  char bIntint;   /* Started out as two integer operands */
66602  int flags;      /* Combined MEM_* flags from both inputs */
66603  i64 iA;         /* Integer value of left operand */
66604  i64 iB;         /* Integer value of right operand */
66605  double rA;      /* Real value of left operand */
66606  double rB;      /* Real value of right operand */
66607#endif /* local variables moved into u.ah */
66608
66609  pIn1 = &aMem[pOp->p1];
66610  applyNumericAffinity(pIn1);
66611  pIn2 = &aMem[pOp->p2];
66612  applyNumericAffinity(pIn2);
66613  pOut = &aMem[pOp->p3];
66614  u.ah.flags = pIn1->flags | pIn2->flags;
66615  if( (u.ah.flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
66616  if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
66617    u.ah.iA = pIn1->u.i;
66618    u.ah.iB = pIn2->u.i;
66619    u.ah.bIntint = 1;
66620    switch( pOp->opcode ){
66621      case OP_Add:       if( sqlite3AddInt64(&u.ah.iB,u.ah.iA) ) goto fp_math;  break;
66622      case OP_Subtract:  if( sqlite3SubInt64(&u.ah.iB,u.ah.iA) ) goto fp_math;  break;
66623      case OP_Multiply:  if( sqlite3MulInt64(&u.ah.iB,u.ah.iA) ) goto fp_math;  break;
66624      case OP_Divide: {
66625        if( u.ah.iA==0 ) goto arithmetic_result_is_null;
66626        if( u.ah.iA==-1 && u.ah.iB==SMALLEST_INT64 ) goto fp_math;
66627        u.ah.iB /= u.ah.iA;
66628        break;
66629      }
66630      default: {
66631        if( u.ah.iA==0 ) goto arithmetic_result_is_null;
66632        if( u.ah.iA==-1 ) u.ah.iA = 1;
66633        u.ah.iB %= u.ah.iA;
66634        break;
66635      }
66636    }
66637    pOut->u.i = u.ah.iB;
66638    MemSetTypeFlag(pOut, MEM_Int);
66639  }else{
66640    u.ah.bIntint = 0;
66641fp_math:
66642    u.ah.rA = sqlite3VdbeRealValue(pIn1);
66643    u.ah.rB = sqlite3VdbeRealValue(pIn2);
66644    switch( pOp->opcode ){
66645      case OP_Add:         u.ah.rB += u.ah.rA;       break;
66646      case OP_Subtract:    u.ah.rB -= u.ah.rA;       break;
66647      case OP_Multiply:    u.ah.rB *= u.ah.rA;       break;
66648      case OP_Divide: {
66649        /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
66650        if( u.ah.rA==(double)0 ) goto arithmetic_result_is_null;
66651        u.ah.rB /= u.ah.rA;
66652        break;
66653      }
66654      default: {
66655        u.ah.iA = (i64)u.ah.rA;
66656        u.ah.iB = (i64)u.ah.rB;
66657        if( u.ah.iA==0 ) goto arithmetic_result_is_null;
66658        if( u.ah.iA==-1 ) u.ah.iA = 1;
66659        u.ah.rB = (double)(u.ah.iB % u.ah.iA);
66660        break;
66661      }
66662    }
66663#ifdef SQLITE_OMIT_FLOATING_POINT
66664    pOut->u.i = u.ah.rB;
66665    MemSetTypeFlag(pOut, MEM_Int);
66666#else
66667    if( sqlite3IsNaN(u.ah.rB) ){
66668      goto arithmetic_result_is_null;
66669    }
66670    pOut->r = u.ah.rB;
66671    MemSetTypeFlag(pOut, MEM_Real);
66672    if( (u.ah.flags & MEM_Real)==0 && !u.ah.bIntint ){
66673      sqlite3VdbeIntegerAffinity(pOut);
66674    }
66675#endif
66676  }
66677  break;
66678
66679arithmetic_result_is_null:
66680  sqlite3VdbeMemSetNull(pOut);
66681  break;
66682}
66683
66684/* Opcode: CollSeq P1 * * P4
66685**
66686** P4 is a pointer to a CollSeq struct. If the next call to a user function
66687** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
66688** be returned. This is used by the built-in min(), max() and nullif()
66689** functions.
66690**
66691** If P1 is not zero, then it is a register that a subsequent min() or
66692** max() aggregate will set to 1 if the current row is not the minimum or
66693** maximum.  The P1 register is initialized to 0 by this instruction.
66694**
66695** The interface used by the implementation of the aforementioned functions
66696** to retrieve the collation sequence set by this opcode is not available
66697** publicly, only to user functions defined in func.c.
66698*/
66699case OP_CollSeq: {
66700  assert( pOp->p4type==P4_COLLSEQ );
66701  if( pOp->p1 ){
66702    sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
66703  }
66704  break;
66705}
66706
66707/* Opcode: Function P1 P2 P3 P4 P5
66708**
66709** Invoke a user function (P4 is a pointer to a Function structure that
66710** defines the function) with P5 arguments taken from register P2 and
66711** successors.  The result of the function is stored in register P3.
66712** Register P3 must not be one of the function inputs.
66713**
66714** P1 is a 32-bit bitmask indicating whether or not each argument to the
66715** function was determined to be constant at compile time. If the first
66716** argument was constant then bit 0 of P1 is set. This is used to determine
66717** whether meta data associated with a user function argument using the
66718** sqlite3_set_auxdata() API may be safely retained until the next
66719** invocation of this opcode.
66720**
66721** See also: AggStep and AggFinal
66722*/
66723case OP_Function: {
66724#if 0  /* local variables moved into u.ai */
66725  int i;
66726  Mem *pArg;
66727  sqlite3_context ctx;
66728  sqlite3_value **apVal;
66729  int n;
66730#endif /* local variables moved into u.ai */
66731
66732  u.ai.n = pOp->p5;
66733  u.ai.apVal = p->apArg;
66734  assert( u.ai.apVal || u.ai.n==0 );
66735  assert( pOp->p3>0 && pOp->p3<=p->nMem );
66736  pOut = &aMem[pOp->p3];
66737  memAboutToChange(p, pOut);
66738
66739  assert( u.ai.n==0 || (pOp->p2>0 && pOp->p2+u.ai.n<=p->nMem+1) );
66740  assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+u.ai.n );
66741  u.ai.pArg = &aMem[pOp->p2];
66742  for(u.ai.i=0; u.ai.i<u.ai.n; u.ai.i++, u.ai.pArg++){
66743    assert( memIsValid(u.ai.pArg) );
66744    u.ai.apVal[u.ai.i] = u.ai.pArg;
66745    Deephemeralize(u.ai.pArg);
66746    sqlite3VdbeMemStoreType(u.ai.pArg);
66747    REGISTER_TRACE(pOp->p2+u.ai.i, u.ai.pArg);
66748  }
66749
66750  assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
66751  if( pOp->p4type==P4_FUNCDEF ){
66752    u.ai.ctx.pFunc = pOp->p4.pFunc;
66753    u.ai.ctx.pVdbeFunc = 0;
66754  }else{
66755    u.ai.ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;
66756    u.ai.ctx.pFunc = u.ai.ctx.pVdbeFunc->pFunc;
66757  }
66758
66759  u.ai.ctx.s.flags = MEM_Null;
66760  u.ai.ctx.s.db = db;
66761  u.ai.ctx.s.xDel = 0;
66762  u.ai.ctx.s.zMalloc = 0;
66763
66764  /* The output cell may already have a buffer allocated. Move
66765  ** the pointer to u.ai.ctx.s so in case the user-function can use
66766  ** the already allocated buffer instead of allocating a new one.
66767  */
66768  sqlite3VdbeMemMove(&u.ai.ctx.s, pOut);
66769  MemSetTypeFlag(&u.ai.ctx.s, MEM_Null);
66770
66771  u.ai.ctx.isError = 0;
66772  if( u.ai.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
66773    assert( pOp>aOp );
66774    assert( pOp[-1].p4type==P4_COLLSEQ );
66775    assert( pOp[-1].opcode==OP_CollSeq );
66776    u.ai.ctx.pColl = pOp[-1].p4.pColl;
66777  }
66778  db->lastRowid = lastRowid;
66779  (*u.ai.ctx.pFunc->xFunc)(&u.ai.ctx, u.ai.n, u.ai.apVal); /* IMP: R-24505-23230 */
66780  lastRowid = db->lastRowid;
66781
66782  /* If any auxiliary data functions have been called by this user function,
66783  ** immediately call the destructor for any non-static values.
66784  */
66785  if( u.ai.ctx.pVdbeFunc ){
66786    sqlite3VdbeDeleteAuxData(u.ai.ctx.pVdbeFunc, pOp->p1);
66787    pOp->p4.pVdbeFunc = u.ai.ctx.pVdbeFunc;
66788    pOp->p4type = P4_VDBEFUNC;
66789  }
66790
66791  if( db->mallocFailed ){
66792    /* Even though a malloc() has failed, the implementation of the
66793    ** user function may have called an sqlite3_result_XXX() function
66794    ** to return a value. The following call releases any resources
66795    ** associated with such a value.
66796    */
66797    sqlite3VdbeMemRelease(&u.ai.ctx.s);
66798    goto no_mem;
66799  }
66800
66801  /* If the function returned an error, throw an exception */
66802  if( u.ai.ctx.isError ){
66803    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.ai.ctx.s));
66804    rc = u.ai.ctx.isError;
66805  }
66806
66807  /* Copy the result of the function into register P3 */
66808  sqlite3VdbeChangeEncoding(&u.ai.ctx.s, encoding);
66809  sqlite3VdbeMemMove(pOut, &u.ai.ctx.s);
66810  if( sqlite3VdbeMemTooBig(pOut) ){
66811    goto too_big;
66812  }
66813
66814#if 0
66815  /* The app-defined function has done something that as caused this
66816  ** statement to expire.  (Perhaps the function called sqlite3_exec()
66817  ** with a CREATE TABLE statement.)
66818  */
66819  if( p->expired ) rc = SQLITE_ABORT;
66820#endif
66821
66822  REGISTER_TRACE(pOp->p3, pOut);
66823  UPDATE_MAX_BLOBSIZE(pOut);
66824  break;
66825}
66826
66827/* Opcode: BitAnd P1 P2 P3 * *
66828**
66829** Take the bit-wise AND of the values in register P1 and P2 and
66830** store the result in register P3.
66831** If either input is NULL, the result is NULL.
66832*/
66833/* Opcode: BitOr P1 P2 P3 * *
66834**
66835** Take the bit-wise OR of the values in register P1 and P2 and
66836** store the result in register P3.
66837** If either input is NULL, the result is NULL.
66838*/
66839/* Opcode: ShiftLeft P1 P2 P3 * *
66840**
66841** Shift the integer value in register P2 to the left by the
66842** number of bits specified by the integer in register P1.
66843** Store the result in register P3.
66844** If either input is NULL, the result is NULL.
66845*/
66846/* Opcode: ShiftRight P1 P2 P3 * *
66847**
66848** Shift the integer value in register P2 to the right by the
66849** number of bits specified by the integer in register P1.
66850** Store the result in register P3.
66851** If either input is NULL, the result is NULL.
66852*/
66853case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
66854case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
66855case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
66856case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
66857#if 0  /* local variables moved into u.aj */
66858  i64 iA;
66859  u64 uA;
66860  i64 iB;
66861  u8 op;
66862#endif /* local variables moved into u.aj */
66863
66864  pIn1 = &aMem[pOp->p1];
66865  pIn2 = &aMem[pOp->p2];
66866  pOut = &aMem[pOp->p3];
66867  if( (pIn1->flags | pIn2->flags) & MEM_Null ){
66868    sqlite3VdbeMemSetNull(pOut);
66869    break;
66870  }
66871  u.aj.iA = sqlite3VdbeIntValue(pIn2);
66872  u.aj.iB = sqlite3VdbeIntValue(pIn1);
66873  u.aj.op = pOp->opcode;
66874  if( u.aj.op==OP_BitAnd ){
66875    u.aj.iA &= u.aj.iB;
66876  }else if( u.aj.op==OP_BitOr ){
66877    u.aj.iA |= u.aj.iB;
66878  }else if( u.aj.iB!=0 ){
66879    assert( u.aj.op==OP_ShiftRight || u.aj.op==OP_ShiftLeft );
66880
66881    /* If shifting by a negative amount, shift in the other direction */
66882    if( u.aj.iB<0 ){
66883      assert( OP_ShiftRight==OP_ShiftLeft+1 );
66884      u.aj.op = 2*OP_ShiftLeft + 1 - u.aj.op;
66885      u.aj.iB = u.aj.iB>(-64) ? -u.aj.iB : 64;
66886    }
66887
66888    if( u.aj.iB>=64 ){
66889      u.aj.iA = (u.aj.iA>=0 || u.aj.op==OP_ShiftLeft) ? 0 : -1;
66890    }else{
66891      memcpy(&u.aj.uA, &u.aj.iA, sizeof(u.aj.uA));
66892      if( u.aj.op==OP_ShiftLeft ){
66893        u.aj.uA <<= u.aj.iB;
66894      }else{
66895        u.aj.uA >>= u.aj.iB;
66896        /* Sign-extend on a right shift of a negative number */
66897        if( u.aj.iA<0 ) u.aj.uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-u.aj.iB);
66898      }
66899      memcpy(&u.aj.iA, &u.aj.uA, sizeof(u.aj.iA));
66900    }
66901  }
66902  pOut->u.i = u.aj.iA;
66903  MemSetTypeFlag(pOut, MEM_Int);
66904  break;
66905}
66906
66907/* Opcode: AddImm  P1 P2 * * *
66908**
66909** Add the constant P2 to the value in register P1.
66910** The result is always an integer.
66911**
66912** To force any register to be an integer, just add 0.
66913*/
66914case OP_AddImm: {            /* in1 */
66915  pIn1 = &aMem[pOp->p1];
66916  memAboutToChange(p, pIn1);
66917  sqlite3VdbeMemIntegerify(pIn1);
66918  pIn1->u.i += pOp->p2;
66919  break;
66920}
66921
66922/* Opcode: MustBeInt P1 P2 * * *
66923**
66924** Force the value in register P1 to be an integer.  If the value
66925** in P1 is not an integer and cannot be converted into an integer
66926** without data loss, then jump immediately to P2, or if P2==0
66927** raise an SQLITE_MISMATCH exception.
66928*/
66929case OP_MustBeInt: {            /* jump, in1 */
66930  pIn1 = &aMem[pOp->p1];
66931  applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
66932  if( (pIn1->flags & MEM_Int)==0 ){
66933    if( pOp->p2==0 ){
66934      rc = SQLITE_MISMATCH;
66935      goto abort_due_to_error;
66936    }else{
66937      pc = pOp->p2 - 1;
66938    }
66939  }else{
66940    MemSetTypeFlag(pIn1, MEM_Int);
66941  }
66942  break;
66943}
66944
66945#ifndef SQLITE_OMIT_FLOATING_POINT
66946/* Opcode: RealAffinity P1 * * * *
66947**
66948** If register P1 holds an integer convert it to a real value.
66949**
66950** This opcode is used when extracting information from a column that
66951** has REAL affinity.  Such column values may still be stored as
66952** integers, for space efficiency, but after extraction we want them
66953** to have only a real value.
66954*/
66955case OP_RealAffinity: {                  /* in1 */
66956  pIn1 = &aMem[pOp->p1];
66957  if( pIn1->flags & MEM_Int ){
66958    sqlite3VdbeMemRealify(pIn1);
66959  }
66960  break;
66961}
66962#endif
66963
66964#ifndef SQLITE_OMIT_CAST
66965/* Opcode: ToText P1 * * * *
66966**
66967** Force the value in register P1 to be text.
66968** If the value is numeric, convert it to a string using the
66969** equivalent of printf().  Blob values are unchanged and
66970** are afterwards simply interpreted as text.
66971**
66972** A NULL value is not changed by this routine.  It remains NULL.
66973*/
66974case OP_ToText: {                  /* same as TK_TO_TEXT, in1 */
66975  pIn1 = &aMem[pOp->p1];
66976  memAboutToChange(p, pIn1);
66977  if( pIn1->flags & MEM_Null ) break;
66978  assert( MEM_Str==(MEM_Blob>>3) );
66979  pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
66980  applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
66981  rc = ExpandBlob(pIn1);
66982  assert( pIn1->flags & MEM_Str || db->mallocFailed );
66983  pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
66984  UPDATE_MAX_BLOBSIZE(pIn1);
66985  break;
66986}
66987
66988/* Opcode: ToBlob P1 * * * *
66989**
66990** Force the value in register P1 to be a BLOB.
66991** If the value is numeric, convert it to a string first.
66992** Strings are simply reinterpreted as blobs with no change
66993** to the underlying data.
66994**
66995** A NULL value is not changed by this routine.  It remains NULL.
66996*/
66997case OP_ToBlob: {                  /* same as TK_TO_BLOB, in1 */
66998  pIn1 = &aMem[pOp->p1];
66999  if( pIn1->flags & MEM_Null ) break;
67000  if( (pIn1->flags & MEM_Blob)==0 ){
67001    applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
67002    assert( pIn1->flags & MEM_Str || db->mallocFailed );
67003    MemSetTypeFlag(pIn1, MEM_Blob);
67004  }else{
67005    pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
67006  }
67007  UPDATE_MAX_BLOBSIZE(pIn1);
67008  break;
67009}
67010
67011/* Opcode: ToNumeric P1 * * * *
67012**
67013** Force the value in register P1 to be numeric (either an
67014** integer or a floating-point number.)
67015** If the value is text or blob, try to convert it to an using the
67016** equivalent of atoi() or atof() and store 0 if no such conversion
67017** is possible.
67018**
67019** A NULL value is not changed by this routine.  It remains NULL.
67020*/
67021case OP_ToNumeric: {                  /* same as TK_TO_NUMERIC, in1 */
67022  pIn1 = &aMem[pOp->p1];
67023  sqlite3VdbeMemNumerify(pIn1);
67024  break;
67025}
67026#endif /* SQLITE_OMIT_CAST */
67027
67028/* Opcode: ToInt P1 * * * *
67029**
67030** Force the value in register P1 to be an integer.  If
67031** The value is currently a real number, drop its fractional part.
67032** If the value is text or blob, try to convert it to an integer using the
67033** equivalent of atoi() and store 0 if no such conversion is possible.
67034**
67035** A NULL value is not changed by this routine.  It remains NULL.
67036*/
67037case OP_ToInt: {                  /* same as TK_TO_INT, in1 */
67038  pIn1 = &aMem[pOp->p1];
67039  if( (pIn1->flags & MEM_Null)==0 ){
67040    sqlite3VdbeMemIntegerify(pIn1);
67041  }
67042  break;
67043}
67044
67045#if !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT)
67046/* Opcode: ToReal P1 * * * *
67047**
67048** Force the value in register P1 to be a floating point number.
67049** If The value is currently an integer, convert it.
67050** If the value is text or blob, try to convert it to an integer using the
67051** equivalent of atoi() and store 0.0 if no such conversion is possible.
67052**
67053** A NULL value is not changed by this routine.  It remains NULL.
67054*/
67055case OP_ToReal: {                  /* same as TK_TO_REAL, in1 */
67056  pIn1 = &aMem[pOp->p1];
67057  memAboutToChange(p, pIn1);
67058  if( (pIn1->flags & MEM_Null)==0 ){
67059    sqlite3VdbeMemRealify(pIn1);
67060  }
67061  break;
67062}
67063#endif /* !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT) */
67064
67065/* Opcode: Lt P1 P2 P3 P4 P5
67066**
67067** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
67068** jump to address P2.
67069**
67070** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
67071** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL
67072** bit is clear then fall through if either operand is NULL.
67073**
67074** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
67075** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
67076** to coerce both inputs according to this affinity before the
67077** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
67078** affinity is used. Note that the affinity conversions are stored
67079** back into the input registers P1 and P3.  So this opcode can cause
67080** persistent changes to registers P1 and P3.
67081**
67082** Once any conversions have taken place, and neither value is NULL,
67083** the values are compared. If both values are blobs then memcmp() is
67084** used to determine the results of the comparison.  If both values
67085** are text, then the appropriate collating function specified in
67086** P4 is  used to do the comparison.  If P4 is not specified then
67087** memcmp() is used to compare text string.  If both values are
67088** numeric, then a numeric comparison is used. If the two values
67089** are of different types, then numbers are considered less than
67090** strings and strings are considered less than blobs.
67091**
67092** If the SQLITE_STOREP2 bit of P5 is set, then do not jump.  Instead,
67093** store a boolean result (either 0, or 1, or NULL) in register P2.
67094**
67095** If the SQLITE_NULLEQ bit is set in P5, then NULL values are considered
67096** equal to one another, provided that they do not have their MEM_Cleared
67097** bit set.
67098*/
67099/* Opcode: Ne P1 P2 P3 P4 P5
67100**
67101** This works just like the Lt opcode except that the jump is taken if
67102** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
67103** additional information.
67104**
67105** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
67106** true or false and is never NULL.  If both operands are NULL then the result
67107** of comparison is false.  If either operand is NULL then the result is true.
67108** If neither operand is NULL the result is the same as it would be if
67109** the SQLITE_NULLEQ flag were omitted from P5.
67110*/
67111/* Opcode: Eq P1 P2 P3 P4 P5
67112**
67113** This works just like the Lt opcode except that the jump is taken if
67114** the operands in registers P1 and P3 are equal.
67115** See the Lt opcode for additional information.
67116**
67117** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
67118** true or false and is never NULL.  If both operands are NULL then the result
67119** of comparison is true.  If either operand is NULL then the result is false.
67120** If neither operand is NULL the result is the same as it would be if
67121** the SQLITE_NULLEQ flag were omitted from P5.
67122*/
67123/* Opcode: Le P1 P2 P3 P4 P5
67124**
67125** This works just like the Lt opcode except that the jump is taken if
67126** the content of register P3 is less than or equal to the content of
67127** register P1.  See the Lt opcode for additional information.
67128*/
67129/* Opcode: Gt P1 P2 P3 P4 P5
67130**
67131** This works just like the Lt opcode except that the jump is taken if
67132** the content of register P3 is greater than the content of
67133** register P1.  See the Lt opcode for additional information.
67134*/
67135/* Opcode: Ge P1 P2 P3 P4 P5
67136**
67137** This works just like the Lt opcode except that the jump is taken if
67138** the content of register P3 is greater than or equal to the content of
67139** register P1.  See the Lt opcode for additional information.
67140*/
67141case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
67142case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
67143case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
67144case OP_Le:               /* same as TK_LE, jump, in1, in3 */
67145case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
67146case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
67147#if 0  /* local variables moved into u.ak */
67148  int res;            /* Result of the comparison of pIn1 against pIn3 */
67149  char affinity;      /* Affinity to use for comparison */
67150  u16 flags1;         /* Copy of initial value of pIn1->flags */
67151  u16 flags3;         /* Copy of initial value of pIn3->flags */
67152#endif /* local variables moved into u.ak */
67153
67154  pIn1 = &aMem[pOp->p1];
67155  pIn3 = &aMem[pOp->p3];
67156  u.ak.flags1 = pIn1->flags;
67157  u.ak.flags3 = pIn3->flags;
67158  if( (u.ak.flags1 | u.ak.flags3)&MEM_Null ){
67159    /* One or both operands are NULL */
67160    if( pOp->p5 & SQLITE_NULLEQ ){
67161      /* If SQLITE_NULLEQ is set (which will only happen if the operator is
67162      ** OP_Eq or OP_Ne) then take the jump or not depending on whether
67163      ** or not both operands are null.
67164      */
67165      assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
67166      assert( (u.ak.flags1 & MEM_Cleared)==0 );
67167      if( (u.ak.flags1&MEM_Null)!=0
67168       && (u.ak.flags3&MEM_Null)!=0
67169       && (u.ak.flags3&MEM_Cleared)==0
67170      ){
67171        u.ak.res = 0;  /* Results are equal */
67172      }else{
67173        u.ak.res = 1;  /* Results are not equal */
67174      }
67175    }else{
67176      /* SQLITE_NULLEQ is clear and at least one operand is NULL,
67177      ** then the result is always NULL.
67178      ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
67179      */
67180      if( pOp->p5 & SQLITE_STOREP2 ){
67181        pOut = &aMem[pOp->p2];
67182        MemSetTypeFlag(pOut, MEM_Null);
67183        REGISTER_TRACE(pOp->p2, pOut);
67184      }else if( pOp->p5 & SQLITE_JUMPIFNULL ){
67185        pc = pOp->p2-1;
67186      }
67187      break;
67188    }
67189  }else{
67190    /* Neither operand is NULL.  Do a comparison. */
67191    u.ak.affinity = pOp->p5 & SQLITE_AFF_MASK;
67192    if( u.ak.affinity ){
67193      applyAffinity(pIn1, u.ak.affinity, encoding);
67194      applyAffinity(pIn3, u.ak.affinity, encoding);
67195      if( db->mallocFailed ) goto no_mem;
67196    }
67197
67198    assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
67199    ExpandBlob(pIn1);
67200    ExpandBlob(pIn3);
67201    u.ak.res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
67202  }
67203  switch( pOp->opcode ){
67204    case OP_Eq:    u.ak.res = u.ak.res==0;     break;
67205    case OP_Ne:    u.ak.res = u.ak.res!=0;     break;
67206    case OP_Lt:    u.ak.res = u.ak.res<0;      break;
67207    case OP_Le:    u.ak.res = u.ak.res<=0;     break;
67208    case OP_Gt:    u.ak.res = u.ak.res>0;      break;
67209    default:       u.ak.res = u.ak.res>=0;     break;
67210  }
67211
67212  if( pOp->p5 & SQLITE_STOREP2 ){
67213    pOut = &aMem[pOp->p2];
67214    memAboutToChange(p, pOut);
67215    MemSetTypeFlag(pOut, MEM_Int);
67216    pOut->u.i = u.ak.res;
67217    REGISTER_TRACE(pOp->p2, pOut);
67218  }else if( u.ak.res ){
67219    pc = pOp->p2-1;
67220  }
67221
67222  /* Undo any changes made by applyAffinity() to the input registers. */
67223  pIn1->flags = (pIn1->flags&~MEM_TypeMask) | (u.ak.flags1&MEM_TypeMask);
67224  pIn3->flags = (pIn3->flags&~MEM_TypeMask) | (u.ak.flags3&MEM_TypeMask);
67225  break;
67226}
67227
67228/* Opcode: Permutation * * * P4 *
67229**
67230** Set the permutation used by the OP_Compare operator to be the array
67231** of integers in P4.
67232**
67233** The permutation is only valid until the next OP_Compare that has
67234** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
67235** occur immediately prior to the OP_Compare.
67236*/
67237case OP_Permutation: {
67238  assert( pOp->p4type==P4_INTARRAY );
67239  assert( pOp->p4.ai );
67240  aPermute = pOp->p4.ai;
67241  break;
67242}
67243
67244/* Opcode: Compare P1 P2 P3 P4 P5
67245**
67246** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
67247** vector "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
67248** the comparison for use by the next OP_Jump instruct.
67249**
67250** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
67251** determined by the most recent OP_Permutation operator.  If the
67252** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
67253** order.
67254**
67255** P4 is a KeyInfo structure that defines collating sequences and sort
67256** orders for the comparison.  The permutation applies to registers
67257** only.  The KeyInfo elements are used sequentially.
67258**
67259** The comparison is a sort comparison, so NULLs compare equal,
67260** NULLs are less than numbers, numbers are less than strings,
67261** and strings are less than blobs.
67262*/
67263case OP_Compare: {
67264#if 0  /* local variables moved into u.al */
67265  int n;
67266  int i;
67267  int p1;
67268  int p2;
67269  const KeyInfo *pKeyInfo;
67270  int idx;
67271  CollSeq *pColl;    /* Collating sequence to use on this term */
67272  int bRev;          /* True for DESCENDING sort order */
67273#endif /* local variables moved into u.al */
67274
67275  if( (pOp->p5 & OPFLAG_PERMUTE)==0 ) aPermute = 0;
67276  u.al.n = pOp->p3;
67277  u.al.pKeyInfo = pOp->p4.pKeyInfo;
67278  assert( u.al.n>0 );
67279  assert( u.al.pKeyInfo!=0 );
67280  u.al.p1 = pOp->p1;
67281  u.al.p2 = pOp->p2;
67282#if SQLITE_DEBUG
67283  if( aPermute ){
67284    int k, mx = 0;
67285    for(k=0; k<u.al.n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
67286    assert( u.al.p1>0 && u.al.p1+mx<=p->nMem+1 );
67287    assert( u.al.p2>0 && u.al.p2+mx<=p->nMem+1 );
67288  }else{
67289    assert( u.al.p1>0 && u.al.p1+u.al.n<=p->nMem+1 );
67290    assert( u.al.p2>0 && u.al.p2+u.al.n<=p->nMem+1 );
67291  }
67292#endif /* SQLITE_DEBUG */
67293  for(u.al.i=0; u.al.i<u.al.n; u.al.i++){
67294    u.al.idx = aPermute ? aPermute[u.al.i] : u.al.i;
67295    assert( memIsValid(&aMem[u.al.p1+u.al.idx]) );
67296    assert( memIsValid(&aMem[u.al.p2+u.al.idx]) );
67297    REGISTER_TRACE(u.al.p1+u.al.idx, &aMem[u.al.p1+u.al.idx]);
67298    REGISTER_TRACE(u.al.p2+u.al.idx, &aMem[u.al.p2+u.al.idx]);
67299    assert( u.al.i<u.al.pKeyInfo->nField );
67300    u.al.pColl = u.al.pKeyInfo->aColl[u.al.i];
67301    u.al.bRev = u.al.pKeyInfo->aSortOrder[u.al.i];
67302    iCompare = sqlite3MemCompare(&aMem[u.al.p1+u.al.idx], &aMem[u.al.p2+u.al.idx], u.al.pColl);
67303    if( iCompare ){
67304      if( u.al.bRev ) iCompare = -iCompare;
67305      break;
67306    }
67307  }
67308  aPermute = 0;
67309  break;
67310}
67311
67312/* Opcode: Jump P1 P2 P3 * *
67313**
67314** Jump to the instruction at address P1, P2, or P3 depending on whether
67315** in the most recent OP_Compare instruction the P1 vector was less than
67316** equal to, or greater than the P2 vector, respectively.
67317*/
67318case OP_Jump: {             /* jump */
67319  if( iCompare<0 ){
67320    pc = pOp->p1 - 1;
67321  }else if( iCompare==0 ){
67322    pc = pOp->p2 - 1;
67323  }else{
67324    pc = pOp->p3 - 1;
67325  }
67326  break;
67327}
67328
67329/* Opcode: And P1 P2 P3 * *
67330**
67331** Take the logical AND of the values in registers P1 and P2 and
67332** write the result into register P3.
67333**
67334** If either P1 or P2 is 0 (false) then the result is 0 even if
67335** the other input is NULL.  A NULL and true or two NULLs give
67336** a NULL output.
67337*/
67338/* Opcode: Or P1 P2 P3 * *
67339**
67340** Take the logical OR of the values in register P1 and P2 and
67341** store the answer in register P3.
67342**
67343** If either P1 or P2 is nonzero (true) then the result is 1 (true)
67344** even if the other input is NULL.  A NULL and false or two NULLs
67345** give a NULL output.
67346*/
67347case OP_And:              /* same as TK_AND, in1, in2, out3 */
67348case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
67349#if 0  /* local variables moved into u.am */
67350  int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
67351  int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
67352#endif /* local variables moved into u.am */
67353
67354  pIn1 = &aMem[pOp->p1];
67355  if( pIn1->flags & MEM_Null ){
67356    u.am.v1 = 2;
67357  }else{
67358    u.am.v1 = sqlite3VdbeIntValue(pIn1)!=0;
67359  }
67360  pIn2 = &aMem[pOp->p2];
67361  if( pIn2->flags & MEM_Null ){
67362    u.am.v2 = 2;
67363  }else{
67364    u.am.v2 = sqlite3VdbeIntValue(pIn2)!=0;
67365  }
67366  if( pOp->opcode==OP_And ){
67367    static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
67368    u.am.v1 = and_logic[u.am.v1*3+u.am.v2];
67369  }else{
67370    static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
67371    u.am.v1 = or_logic[u.am.v1*3+u.am.v2];
67372  }
67373  pOut = &aMem[pOp->p3];
67374  if( u.am.v1==2 ){
67375    MemSetTypeFlag(pOut, MEM_Null);
67376  }else{
67377    pOut->u.i = u.am.v1;
67378    MemSetTypeFlag(pOut, MEM_Int);
67379  }
67380  break;
67381}
67382
67383/* Opcode: Not P1 P2 * * *
67384**
67385** Interpret the value in register P1 as a boolean value.  Store the
67386** boolean complement in register P2.  If the value in register P1 is
67387** NULL, then a NULL is stored in P2.
67388*/
67389case OP_Not: {                /* same as TK_NOT, in1, out2 */
67390  pIn1 = &aMem[pOp->p1];
67391  pOut = &aMem[pOp->p2];
67392  if( pIn1->flags & MEM_Null ){
67393    sqlite3VdbeMemSetNull(pOut);
67394  }else{
67395    sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));
67396  }
67397  break;
67398}
67399
67400/* Opcode: BitNot P1 P2 * * *
67401**
67402** Interpret the content of register P1 as an integer.  Store the
67403** ones-complement of the P1 value into register P2.  If P1 holds
67404** a NULL then store a NULL in P2.
67405*/
67406case OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */
67407  pIn1 = &aMem[pOp->p1];
67408  pOut = &aMem[pOp->p2];
67409  if( pIn1->flags & MEM_Null ){
67410    sqlite3VdbeMemSetNull(pOut);
67411  }else{
67412    sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1));
67413  }
67414  break;
67415}
67416
67417/* Opcode: Once P1 P2 * * *
67418**
67419** Check if OP_Once flag P1 is set. If so, jump to instruction P2. Otherwise,
67420** set the flag and fall through to the next instruction.
67421*/
67422case OP_Once: {             /* jump */
67423  assert( pOp->p1<p->nOnceFlag );
67424  if( p->aOnceFlag[pOp->p1] ){
67425    pc = pOp->p2-1;
67426  }else{
67427    p->aOnceFlag[pOp->p1] = 1;
67428  }
67429  break;
67430}
67431
67432/* Opcode: If P1 P2 P3 * *
67433**
67434** Jump to P2 if the value in register P1 is true.  The value
67435** is considered true if it is numeric and non-zero.  If the value
67436** in P1 is NULL then take the jump if P3 is non-zero.
67437*/
67438/* Opcode: IfNot P1 P2 P3 * *
67439**
67440** Jump to P2 if the value in register P1 is False.  The value
67441** is considered false if it has a numeric value of zero.  If the value
67442** in P1 is NULL then take the jump if P3 is zero.
67443*/
67444case OP_If:                 /* jump, in1 */
67445case OP_IfNot: {            /* jump, in1 */
67446#if 0  /* local variables moved into u.an */
67447  int c;
67448#endif /* local variables moved into u.an */
67449  pIn1 = &aMem[pOp->p1];
67450  if( pIn1->flags & MEM_Null ){
67451    u.an.c = pOp->p3;
67452  }else{
67453#ifdef SQLITE_OMIT_FLOATING_POINT
67454    u.an.c = sqlite3VdbeIntValue(pIn1)!=0;
67455#else
67456    u.an.c = sqlite3VdbeRealValue(pIn1)!=0.0;
67457#endif
67458    if( pOp->opcode==OP_IfNot ) u.an.c = !u.an.c;
67459  }
67460  if( u.an.c ){
67461    pc = pOp->p2-1;
67462  }
67463  break;
67464}
67465
67466/* Opcode: IsNull P1 P2 * * *
67467**
67468** Jump to P2 if the value in register P1 is NULL.
67469*/
67470case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
67471  pIn1 = &aMem[pOp->p1];
67472  if( (pIn1->flags & MEM_Null)!=0 ){
67473    pc = pOp->p2 - 1;
67474  }
67475  break;
67476}
67477
67478/* Opcode: NotNull P1 P2 * * *
67479**
67480** Jump to P2 if the value in register P1 is not NULL.
67481*/
67482case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
67483  pIn1 = &aMem[pOp->p1];
67484  if( (pIn1->flags & MEM_Null)==0 ){
67485    pc = pOp->p2 - 1;
67486  }
67487  break;
67488}
67489
67490/* Opcode: Column P1 P2 P3 P4 P5
67491**
67492** Interpret the data that cursor P1 points to as a structure built using
67493** the MakeRecord instruction.  (See the MakeRecord opcode for additional
67494** information about the format of the data.)  Extract the P2-th column
67495** from this record.  If there are less that (P2+1)
67496** values in the record, extract a NULL.
67497**
67498** The value extracted is stored in register P3.
67499**
67500** If the column contains fewer than P2 fields, then extract a NULL.  Or,
67501** if the P4 argument is a P4_MEM use the value of the P4 argument as
67502** the result.
67503**
67504** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
67505** then the cache of the cursor is reset prior to extracting the column.
67506** The first OP_Column against a pseudo-table after the value of the content
67507** register has changed should have this bit set.
67508**
67509** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 when
67510** the result is guaranteed to only be used as the argument of a length()
67511** or typeof() function, respectively.  The loading of large blobs can be
67512** skipped for length() and all content loading can be skipped for typeof().
67513*/
67514case OP_Column: {
67515#if 0  /* local variables moved into u.ao */
67516  u32 payloadSize;   /* Number of bytes in the record */
67517  i64 payloadSize64; /* Number of bytes in the record */
67518  int p1;            /* P1 value of the opcode */
67519  int p2;            /* column number to retrieve */
67520  VdbeCursor *pC;    /* The VDBE cursor */
67521  char *zRec;        /* Pointer to complete record-data */
67522  BtCursor *pCrsr;   /* The BTree cursor */
67523  u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
67524  u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
67525  int nField;        /* number of fields in the record */
67526  int len;           /* The length of the serialized data for the column */
67527  int i;             /* Loop counter */
67528  char *zData;       /* Part of the record being decoded */
67529  Mem *pDest;        /* Where to write the extracted value */
67530  Mem sMem;          /* For storing the record being decoded */
67531  u8 *zIdx;          /* Index into header */
67532  u8 *zEndHdr;       /* Pointer to first byte after the header */
67533  u32 offset;        /* Offset into the data */
67534  u32 szField;       /* Number of bytes in the content of a field */
67535  int szHdr;         /* Size of the header size field at start of record */
67536  int avail;         /* Number of bytes of available data */
67537  u32 t;             /* A type code from the record header */
67538  Mem *pReg;         /* PseudoTable input register */
67539#endif /* local variables moved into u.ao */
67540
67541
67542  u.ao.p1 = pOp->p1;
67543  u.ao.p2 = pOp->p2;
67544  u.ao.pC = 0;
67545  memset(&u.ao.sMem, 0, sizeof(u.ao.sMem));
67546  assert( u.ao.p1<p->nCursor );
67547  assert( pOp->p3>0 && pOp->p3<=p->nMem );
67548  u.ao.pDest = &aMem[pOp->p3];
67549  memAboutToChange(p, u.ao.pDest);
67550  u.ao.zRec = 0;
67551
67552  /* This block sets the variable u.ao.payloadSize to be the total number of
67553  ** bytes in the record.
67554  **
67555  ** u.ao.zRec is set to be the complete text of the record if it is available.
67556  ** The complete record text is always available for pseudo-tables
67557  ** If the record is stored in a cursor, the complete record text
67558  ** might be available in the  u.ao.pC->aRow cache.  Or it might not be.
67559  ** If the data is unavailable,  u.ao.zRec is set to NULL.
67560  **
67561  ** We also compute the number of columns in the record.  For cursors,
67562  ** the number of columns is stored in the VdbeCursor.nField element.
67563  */
67564  u.ao.pC = p->apCsr[u.ao.p1];
67565  assert( u.ao.pC!=0 );
67566#ifndef SQLITE_OMIT_VIRTUALTABLE
67567  assert( u.ao.pC->pVtabCursor==0 );
67568#endif
67569  u.ao.pCrsr = u.ao.pC->pCursor;
67570  if( u.ao.pCrsr!=0 ){
67571    /* The record is stored in a B-Tree */
67572    rc = sqlite3VdbeCursorMoveto(u.ao.pC);
67573    if( rc ) goto abort_due_to_error;
67574    if( u.ao.pC->nullRow ){
67575      u.ao.payloadSize = 0;
67576    }else if( u.ao.pC->cacheStatus==p->cacheCtr ){
67577      u.ao.payloadSize = u.ao.pC->payloadSize;
67578      u.ao.zRec = (char*)u.ao.pC->aRow;
67579    }else if( u.ao.pC->isIndex ){
67580      assert( sqlite3BtreeCursorIsValid(u.ao.pCrsr) );
67581      VVA_ONLY(rc =) sqlite3BtreeKeySize(u.ao.pCrsr, &u.ao.payloadSize64);
67582      assert( rc==SQLITE_OK );   /* True because of CursorMoveto() call above */
67583      /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
67584      ** payload size, so it is impossible for u.ao.payloadSize64 to be
67585      ** larger than 32 bits. */
67586      assert( (u.ao.payloadSize64 & SQLITE_MAX_U32)==(u64)u.ao.payloadSize64 );
67587      u.ao.payloadSize = (u32)u.ao.payloadSize64;
67588    }else{
67589      assert( sqlite3BtreeCursorIsValid(u.ao.pCrsr) );
67590      VVA_ONLY(rc =) sqlite3BtreeDataSize(u.ao.pCrsr, &u.ao.payloadSize);
67591      assert( rc==SQLITE_OK );   /* DataSize() cannot fail */
67592    }
67593  }else if( ALWAYS(u.ao.pC->pseudoTableReg>0) ){
67594    u.ao.pReg = &aMem[u.ao.pC->pseudoTableReg];
67595    if( u.ao.pC->multiPseudo ){
67596      sqlite3VdbeMemShallowCopy(u.ao.pDest, u.ao.pReg+u.ao.p2, MEM_Ephem);
67597      Deephemeralize(u.ao.pDest);
67598      goto op_column_out;
67599    }
67600    assert( u.ao.pReg->flags & MEM_Blob );
67601    assert( memIsValid(u.ao.pReg) );
67602    u.ao.payloadSize = u.ao.pReg->n;
67603    u.ao.zRec = u.ao.pReg->z;
67604    u.ao.pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr;
67605    assert( u.ao.payloadSize==0 || u.ao.zRec!=0 );
67606  }else{
67607    /* Consider the row to be NULL */
67608    u.ao.payloadSize = 0;
67609  }
67610
67611  /* If u.ao.payloadSize is 0, then just store a NULL.  This can happen because of
67612  ** nullRow or because of a corrupt database. */
67613  if( u.ao.payloadSize==0 ){
67614    MemSetTypeFlag(u.ao.pDest, MEM_Null);
67615    goto op_column_out;
67616  }
67617  assert( db->aLimit[SQLITE_LIMIT_LENGTH]>=0 );
67618  if( u.ao.payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
67619    goto too_big;
67620  }
67621
67622  u.ao.nField = u.ao.pC->nField;
67623  assert( u.ao.p2<u.ao.nField );
67624
67625  /* Read and parse the table header.  Store the results of the parse
67626  ** into the record header cache fields of the cursor.
67627  */
67628  u.ao.aType = u.ao.pC->aType;
67629  if( u.ao.pC->cacheStatus==p->cacheCtr ){
67630    u.ao.aOffset = u.ao.pC->aOffset;
67631  }else{
67632    assert(u.ao.aType);
67633    u.ao.avail = 0;
67634    u.ao.pC->aOffset = u.ao.aOffset = &u.ao.aType[u.ao.nField];
67635    u.ao.pC->payloadSize = u.ao.payloadSize;
67636    u.ao.pC->cacheStatus = p->cacheCtr;
67637
67638    /* Figure out how many bytes are in the header */
67639    if( u.ao.zRec ){
67640      u.ao.zData = u.ao.zRec;
67641    }else{
67642      if( u.ao.pC->isIndex ){
67643        u.ao.zData = (char*)sqlite3BtreeKeyFetch(u.ao.pCrsr, &u.ao.avail);
67644      }else{
67645        u.ao.zData = (char*)sqlite3BtreeDataFetch(u.ao.pCrsr, &u.ao.avail);
67646      }
67647      /* If KeyFetch()/DataFetch() managed to get the entire payload,
67648      ** save the payload in the u.ao.pC->aRow cache.  That will save us from
67649      ** having to make additional calls to fetch the content portion of
67650      ** the record.
67651      */
67652      assert( u.ao.avail>=0 );
67653      if( u.ao.payloadSize <= (u32)u.ao.avail ){
67654        u.ao.zRec = u.ao.zData;
67655        u.ao.pC->aRow = (u8*)u.ao.zData;
67656      }else{
67657        u.ao.pC->aRow = 0;
67658      }
67659    }
67660    /* The following assert is true in all cases except when
67661    ** the database file has been corrupted externally.
67662    **    assert( u.ao.zRec!=0 || u.ao.avail>=u.ao.payloadSize || u.ao.avail>=9 ); */
67663    u.ao.szHdr = getVarint32((u8*)u.ao.zData, u.ao.offset);
67664
67665    /* Make sure a corrupt database has not given us an oversize header.
67666    ** Do this now to avoid an oversize memory allocation.
67667    **
67668    ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
67669    ** types use so much data space that there can only be 4096 and 32 of
67670    ** them, respectively.  So the maximum header length results from a
67671    ** 3-byte type for each of the maximum of 32768 columns plus three
67672    ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
67673    */
67674    if( u.ao.offset > 98307 ){
67675      rc = SQLITE_CORRUPT_BKPT;
67676      goto op_column_out;
67677    }
67678
67679    /* Compute in u.ao.len the number of bytes of data we need to read in order
67680    ** to get u.ao.nField type values.  u.ao.offset is an upper bound on this.  But
67681    ** u.ao.nField might be significantly less than the true number of columns
67682    ** in the table, and in that case, 5*u.ao.nField+3 might be smaller than u.ao.offset.
67683    ** We want to minimize u.ao.len in order to limit the size of the memory
67684    ** allocation, especially if a corrupt database file has caused u.ao.offset
67685    ** to be oversized. Offset is limited to 98307 above.  But 98307 might
67686    ** still exceed Robson memory allocation limits on some configurations.
67687    ** On systems that cannot tolerate large memory allocations, u.ao.nField*5+3
67688    ** will likely be much smaller since u.ao.nField will likely be less than
67689    ** 20 or so.  This insures that Robson memory allocation limits are
67690    ** not exceeded even for corrupt database files.
67691    */
67692    u.ao.len = u.ao.nField*5 + 3;
67693    if( u.ao.len > (int)u.ao.offset ) u.ao.len = (int)u.ao.offset;
67694
67695    /* The KeyFetch() or DataFetch() above are fast and will get the entire
67696    ** record header in most cases.  But they will fail to get the complete
67697    ** record header if the record header does not fit on a single page
67698    ** in the B-Tree.  When that happens, use sqlite3VdbeMemFromBtree() to
67699    ** acquire the complete header text.
67700    */
67701    if( !u.ao.zRec && u.ao.avail<u.ao.len ){
67702      u.ao.sMem.flags = 0;
67703      u.ao.sMem.db = 0;
67704      rc = sqlite3VdbeMemFromBtree(u.ao.pCrsr, 0, u.ao.len, u.ao.pC->isIndex, &u.ao.sMem);
67705      if( rc!=SQLITE_OK ){
67706        goto op_column_out;
67707      }
67708      u.ao.zData = u.ao.sMem.z;
67709    }
67710    u.ao.zEndHdr = (u8 *)&u.ao.zData[u.ao.len];
67711    u.ao.zIdx = (u8 *)&u.ao.zData[u.ao.szHdr];
67712
67713    /* Scan the header and use it to fill in the u.ao.aType[] and u.ao.aOffset[]
67714    ** arrays.  u.ao.aType[u.ao.i] will contain the type integer for the u.ao.i-th
67715    ** column and u.ao.aOffset[u.ao.i] will contain the u.ao.offset from the beginning
67716    ** of the record to the start of the data for the u.ao.i-th column
67717    */
67718    for(u.ao.i=0; u.ao.i<u.ao.nField; u.ao.i++){
67719      if( u.ao.zIdx<u.ao.zEndHdr ){
67720        u.ao.aOffset[u.ao.i] = u.ao.offset;
67721        if( u.ao.zIdx[0]<0x80 ){
67722          u.ao.t = u.ao.zIdx[0];
67723          u.ao.zIdx++;
67724        }else{
67725          u.ao.zIdx += sqlite3GetVarint32(u.ao.zIdx, &u.ao.t);
67726        }
67727        u.ao.aType[u.ao.i] = u.ao.t;
67728        u.ao.szField = sqlite3VdbeSerialTypeLen(u.ao.t);
67729        u.ao.offset += u.ao.szField;
67730        if( u.ao.offset<u.ao.szField ){  /* True if u.ao.offset overflows */
67731          u.ao.zIdx = &u.ao.zEndHdr[1];  /* Forces SQLITE_CORRUPT return below */
67732          break;
67733        }
67734      }else{
67735        /* If u.ao.i is less that u.ao.nField, then there are fewer fields in this
67736        ** record than SetNumColumns indicated there are columns in the
67737        ** table. Set the u.ao.offset for any extra columns not present in
67738        ** the record to 0. This tells code below to store the default value
67739        ** for the column instead of deserializing a value from the record.
67740        */
67741        u.ao.aOffset[u.ao.i] = 0;
67742      }
67743    }
67744    sqlite3VdbeMemRelease(&u.ao.sMem);
67745    u.ao.sMem.flags = MEM_Null;
67746
67747    /* If we have read more header data than was contained in the header,
67748    ** or if the end of the last field appears to be past the end of the
67749    ** record, or if the end of the last field appears to be before the end
67750    ** of the record (when all fields present), then we must be dealing
67751    ** with a corrupt database.
67752    */
67753    if( (u.ao.zIdx > u.ao.zEndHdr) || (u.ao.offset > u.ao.payloadSize)
67754         || (u.ao.zIdx==u.ao.zEndHdr && u.ao.offset!=u.ao.payloadSize) ){
67755      rc = SQLITE_CORRUPT_BKPT;
67756      goto op_column_out;
67757    }
67758  }
67759
67760  /* Get the column information. If u.ao.aOffset[u.ao.p2] is non-zero, then
67761  ** deserialize the value from the record. If u.ao.aOffset[u.ao.p2] is zero,
67762  ** then there are not enough fields in the record to satisfy the
67763  ** request.  In this case, set the value NULL or to P4 if P4 is
67764  ** a pointer to a Mem object.
67765  */
67766  if( u.ao.aOffset[u.ao.p2] ){
67767    assert( rc==SQLITE_OK );
67768    if( u.ao.zRec ){
67769      /* This is the common case where the whole row fits on a single page */
67770      VdbeMemRelease(u.ao.pDest);
67771      sqlite3VdbeSerialGet((u8 *)&u.ao.zRec[u.ao.aOffset[u.ao.p2]], u.ao.aType[u.ao.p2], u.ao.pDest);
67772    }else{
67773      /* This branch happens only when the row overflows onto multiple pages */
67774      u.ao.t = u.ao.aType[u.ao.p2];
67775      if( (pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
67776       && ((u.ao.t>=12 && (u.ao.t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0)
67777      ){
67778        /* Content is irrelevant for the typeof() function and for
67779        ** the length(X) function if X is a blob.  So we might as well use
67780        ** bogus content rather than reading content from disk.  NULL works
67781        ** for text and blob and whatever is in the u.ao.payloadSize64 variable
67782        ** will work for everything else. */
67783        u.ao.zData = u.ao.t<12 ? (char*)&u.ao.payloadSize64 : 0;
67784      }else{
67785        u.ao.len = sqlite3VdbeSerialTypeLen(u.ao.t);
67786        sqlite3VdbeMemMove(&u.ao.sMem, u.ao.pDest);
67787        rc = sqlite3VdbeMemFromBtree(u.ao.pCrsr, u.ao.aOffset[u.ao.p2], u.ao.len,  u.ao.pC->isIndex,
67788                                     &u.ao.sMem);
67789        if( rc!=SQLITE_OK ){
67790          goto op_column_out;
67791        }
67792        u.ao.zData = u.ao.sMem.z;
67793      }
67794      sqlite3VdbeSerialGet((u8*)u.ao.zData, u.ao.t, u.ao.pDest);
67795    }
67796    u.ao.pDest->enc = encoding;
67797  }else{
67798    if( pOp->p4type==P4_MEM ){
67799      sqlite3VdbeMemShallowCopy(u.ao.pDest, pOp->p4.pMem, MEM_Static);
67800    }else{
67801      MemSetTypeFlag(u.ao.pDest, MEM_Null);
67802    }
67803  }
67804
67805  /* If we dynamically allocated space to hold the data (in the
67806  ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
67807  ** dynamically allocated space over to the u.ao.pDest structure.
67808  ** This prevents a memory copy.
67809  */
67810  if( u.ao.sMem.zMalloc ){
67811    assert( u.ao.sMem.z==u.ao.sMem.zMalloc );
67812    assert( !(u.ao.pDest->flags & MEM_Dyn) );
67813    assert( !(u.ao.pDest->flags & (MEM_Blob|MEM_Str)) || u.ao.pDest->z==u.ao.sMem.z );
67814    u.ao.pDest->flags &= ~(MEM_Ephem|MEM_Static);
67815    u.ao.pDest->flags |= MEM_Term;
67816    u.ao.pDest->z = u.ao.sMem.z;
67817    u.ao.pDest->zMalloc = u.ao.sMem.zMalloc;
67818  }
67819
67820  rc = sqlite3VdbeMemMakeWriteable(u.ao.pDest);
67821
67822op_column_out:
67823  UPDATE_MAX_BLOBSIZE(u.ao.pDest);
67824  REGISTER_TRACE(pOp->p3, u.ao.pDest);
67825  break;
67826}
67827
67828/* Opcode: Affinity P1 P2 * P4 *
67829**
67830** Apply affinities to a range of P2 registers starting with P1.
67831**
67832** P4 is a string that is P2 characters long. The nth character of the
67833** string indicates the column affinity that should be used for the nth
67834** memory cell in the range.
67835*/
67836case OP_Affinity: {
67837#if 0  /* local variables moved into u.ap */
67838  const char *zAffinity;   /* The affinity to be applied */
67839  char cAff;               /* A single character of affinity */
67840#endif /* local variables moved into u.ap */
67841
67842  u.ap.zAffinity = pOp->p4.z;
67843  assert( u.ap.zAffinity!=0 );
67844  assert( u.ap.zAffinity[pOp->p2]==0 );
67845  pIn1 = &aMem[pOp->p1];
67846  while( (u.ap.cAff = *(u.ap.zAffinity++))!=0 ){
67847    assert( pIn1 <= &p->aMem[p->nMem] );
67848    assert( memIsValid(pIn1) );
67849    ExpandBlob(pIn1);
67850    applyAffinity(pIn1, u.ap.cAff, encoding);
67851    pIn1++;
67852  }
67853  break;
67854}
67855
67856/* Opcode: MakeRecord P1 P2 P3 P4 *
67857**
67858** Convert P2 registers beginning with P1 into the [record format]
67859** use as a data record in a database table or as a key
67860** in an index.  The OP_Column opcode can decode the record later.
67861**
67862** P4 may be a string that is P2 characters long.  The nth character of the
67863** string indicates the column affinity that should be used for the nth
67864** field of the index key.
67865**
67866** The mapping from character to affinity is given by the SQLITE_AFF_
67867** macros defined in sqliteInt.h.
67868**
67869** If P4 is NULL then all index fields have the affinity NONE.
67870*/
67871case OP_MakeRecord: {
67872#if 0  /* local variables moved into u.aq */
67873  u8 *zNewRecord;        /* A buffer to hold the data for the new record */
67874  Mem *pRec;             /* The new record */
67875  u64 nData;             /* Number of bytes of data space */
67876  int nHdr;              /* Number of bytes of header space */
67877  i64 nByte;             /* Data space required for this record */
67878  int nZero;             /* Number of zero bytes at the end of the record */
67879  int nVarint;           /* Number of bytes in a varint */
67880  u32 serial_type;       /* Type field */
67881  Mem *pData0;           /* First field to be combined into the record */
67882  Mem *pLast;            /* Last field of the record */
67883  int nField;            /* Number of fields in the record */
67884  char *zAffinity;       /* The affinity string for the record */
67885  int file_format;       /* File format to use for encoding */
67886  int i;                 /* Space used in zNewRecord[] */
67887  int len;               /* Length of a field */
67888#endif /* local variables moved into u.aq */
67889
67890  /* Assuming the record contains N fields, the record format looks
67891  ** like this:
67892  **
67893  ** ------------------------------------------------------------------------
67894  ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
67895  ** ------------------------------------------------------------------------
67896  **
67897  ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
67898  ** and so froth.
67899  **
67900  ** Each type field is a varint representing the serial type of the
67901  ** corresponding data element (see sqlite3VdbeSerialType()). The
67902  ** hdr-size field is also a varint which is the offset from the beginning
67903  ** of the record to data0.
67904  */
67905  u.aq.nData = 0;         /* Number of bytes of data space */
67906  u.aq.nHdr = 0;          /* Number of bytes of header space */
67907  u.aq.nZero = 0;         /* Number of zero bytes at the end of the record */
67908  u.aq.nField = pOp->p1;
67909  u.aq.zAffinity = pOp->p4.z;
67910  assert( u.aq.nField>0 && pOp->p2>0 && pOp->p2+u.aq.nField<=p->nMem+1 );
67911  u.aq.pData0 = &aMem[u.aq.nField];
67912  u.aq.nField = pOp->p2;
67913  u.aq.pLast = &u.aq.pData0[u.aq.nField-1];
67914  u.aq.file_format = p->minWriteFileFormat;
67915
67916  /* Identify the output register */
67917  assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
67918  pOut = &aMem[pOp->p3];
67919  memAboutToChange(p, pOut);
67920
67921  /* Loop through the elements that will make up the record to figure
67922  ** out how much space is required for the new record.
67923  */
67924  for(u.aq.pRec=u.aq.pData0; u.aq.pRec<=u.aq.pLast; u.aq.pRec++){
67925    assert( memIsValid(u.aq.pRec) );
67926    if( u.aq.zAffinity ){
67927      applyAffinity(u.aq.pRec, u.aq.zAffinity[u.aq.pRec-u.aq.pData0], encoding);
67928    }
67929    if( u.aq.pRec->flags&MEM_Zero && u.aq.pRec->n>0 ){
67930      sqlite3VdbeMemExpandBlob(u.aq.pRec);
67931    }
67932    u.aq.serial_type = sqlite3VdbeSerialType(u.aq.pRec, u.aq.file_format);
67933    u.aq.len = sqlite3VdbeSerialTypeLen(u.aq.serial_type);
67934    u.aq.nData += u.aq.len;
67935    u.aq.nHdr += sqlite3VarintLen(u.aq.serial_type);
67936    if( u.aq.pRec->flags & MEM_Zero ){
67937      /* Only pure zero-filled BLOBs can be input to this Opcode.
67938      ** We do not allow blobs with a prefix and a zero-filled tail. */
67939      u.aq.nZero += u.aq.pRec->u.nZero;
67940    }else if( u.aq.len ){
67941      u.aq.nZero = 0;
67942    }
67943  }
67944
67945  /* Add the initial header varint and total the size */
67946  u.aq.nHdr += u.aq.nVarint = sqlite3VarintLen(u.aq.nHdr);
67947  if( u.aq.nVarint<sqlite3VarintLen(u.aq.nHdr) ){
67948    u.aq.nHdr++;
67949  }
67950  u.aq.nByte = u.aq.nHdr+u.aq.nData-u.aq.nZero;
67951  if( u.aq.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
67952    goto too_big;
67953  }
67954
67955  /* Make sure the output register has a buffer large enough to store
67956  ** the new record. The output register (pOp->p3) is not allowed to
67957  ** be one of the input registers (because the following call to
67958  ** sqlite3VdbeMemGrow() could clobber the value before it is used).
67959  */
67960  if( sqlite3VdbeMemGrow(pOut, (int)u.aq.nByte, 0) ){
67961    goto no_mem;
67962  }
67963  u.aq.zNewRecord = (u8 *)pOut->z;
67964
67965  /* Write the record */
67966  u.aq.i = putVarint32(u.aq.zNewRecord, u.aq.nHdr);
67967  for(u.aq.pRec=u.aq.pData0; u.aq.pRec<=u.aq.pLast; u.aq.pRec++){
67968    u.aq.serial_type = sqlite3VdbeSerialType(u.aq.pRec, u.aq.file_format);
67969    u.aq.i += putVarint32(&u.aq.zNewRecord[u.aq.i], u.aq.serial_type);      /* serial type */
67970  }
67971  for(u.aq.pRec=u.aq.pData0; u.aq.pRec<=u.aq.pLast; u.aq.pRec++){  /* serial data */
67972    u.aq.i += sqlite3VdbeSerialPut(&u.aq.zNewRecord[u.aq.i], (int)(u.aq.nByte-u.aq.i), u.aq.pRec,u.aq.file_format);
67973  }
67974  assert( u.aq.i==u.aq.nByte );
67975
67976  assert( pOp->p3>0 && pOp->p3<=p->nMem );
67977  pOut->n = (int)u.aq.nByte;
67978  pOut->flags = MEM_Blob | MEM_Dyn;
67979  pOut->xDel = 0;
67980  if( u.aq.nZero ){
67981    pOut->u.nZero = u.aq.nZero;
67982    pOut->flags |= MEM_Zero;
67983  }
67984  pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
67985  REGISTER_TRACE(pOp->p3, pOut);
67986  UPDATE_MAX_BLOBSIZE(pOut);
67987  break;
67988}
67989
67990/* Opcode: Count P1 P2 * * *
67991**
67992** Store the number of entries (an integer value) in the table or index
67993** opened by cursor P1 in register P2
67994*/
67995#ifndef SQLITE_OMIT_BTREECOUNT
67996case OP_Count: {         /* out2-prerelease */
67997#if 0  /* local variables moved into u.ar */
67998  i64 nEntry;
67999  BtCursor *pCrsr;
68000#endif /* local variables moved into u.ar */
68001
68002  u.ar.pCrsr = p->apCsr[pOp->p1]->pCursor;
68003  if( ALWAYS(u.ar.pCrsr) ){
68004    rc = sqlite3BtreeCount(u.ar.pCrsr, &u.ar.nEntry);
68005  }else{
68006    u.ar.nEntry = 0;
68007  }
68008  pOut->u.i = u.ar.nEntry;
68009  break;
68010}
68011#endif
68012
68013/* Opcode: Savepoint P1 * * P4 *
68014**
68015** Open, release or rollback the savepoint named by parameter P4, depending
68016** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
68017** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
68018*/
68019case OP_Savepoint: {
68020#if 0  /* local variables moved into u.as */
68021  int p1;                         /* Value of P1 operand */
68022  char *zName;                    /* Name of savepoint */
68023  int nName;
68024  Savepoint *pNew;
68025  Savepoint *pSavepoint;
68026  Savepoint *pTmp;
68027  int iSavepoint;
68028  int ii;
68029#endif /* local variables moved into u.as */
68030
68031  u.as.p1 = pOp->p1;
68032  u.as.zName = pOp->p4.z;
68033
68034  /* Assert that the u.as.p1 parameter is valid. Also that if there is no open
68035  ** transaction, then there cannot be any savepoints.
68036  */
68037  assert( db->pSavepoint==0 || db->autoCommit==0 );
68038  assert( u.as.p1==SAVEPOINT_BEGIN||u.as.p1==SAVEPOINT_RELEASE||u.as.p1==SAVEPOINT_ROLLBACK );
68039  assert( db->pSavepoint || db->isTransactionSavepoint==0 );
68040  assert( checkSavepointCount(db) );
68041
68042  if( u.as.p1==SAVEPOINT_BEGIN ){
68043    if( db->writeVdbeCnt>0 ){
68044      /* A new savepoint cannot be created if there are active write
68045      ** statements (i.e. open read/write incremental blob handles).
68046      */
68047      sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
68048        "SQL statements in progress");
68049      rc = SQLITE_BUSY;
68050    }else{
68051      u.as.nName = sqlite3Strlen30(u.as.zName);
68052
68053#ifndef SQLITE_OMIT_VIRTUALTABLE
68054      /* This call is Ok even if this savepoint is actually a transaction
68055      ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
68056      ** If this is a transaction savepoint being opened, it is guaranteed
68057      ** that the db->aVTrans[] array is empty.  */
68058      assert( db->autoCommit==0 || db->nVTrans==0 );
68059      rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
68060                                db->nStatement+db->nSavepoint);
68061      if( rc!=SQLITE_OK ) goto abort_due_to_error;
68062#endif
68063
68064      /* Create a new savepoint structure. */
68065      u.as.pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+u.as.nName+1);
68066      if( u.as.pNew ){
68067        u.as.pNew->zName = (char *)&u.as.pNew[1];
68068        memcpy(u.as.pNew->zName, u.as.zName, u.as.nName+1);
68069
68070        /* If there is no open transaction, then mark this as a special
68071        ** "transaction savepoint". */
68072        if( db->autoCommit ){
68073          db->autoCommit = 0;
68074          db->isTransactionSavepoint = 1;
68075        }else{
68076          db->nSavepoint++;
68077        }
68078
68079        /* Link the new savepoint into the database handle's list. */
68080        u.as.pNew->pNext = db->pSavepoint;
68081        db->pSavepoint = u.as.pNew;
68082        u.as.pNew->nDeferredCons = db->nDeferredCons;
68083      }
68084    }
68085  }else{
68086    u.as.iSavepoint = 0;
68087
68088    /* Find the named savepoint. If there is no such savepoint, then an
68089    ** an error is returned to the user.  */
68090    for(
68091      u.as.pSavepoint = db->pSavepoint;
68092      u.as.pSavepoint && sqlite3StrICmp(u.as.pSavepoint->zName, u.as.zName);
68093      u.as.pSavepoint = u.as.pSavepoint->pNext
68094    ){
68095      u.as.iSavepoint++;
68096    }
68097    if( !u.as.pSavepoint ){
68098      sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", u.as.zName);
68099      rc = SQLITE_ERROR;
68100    }else if( db->writeVdbeCnt>0 && u.as.p1==SAVEPOINT_RELEASE ){
68101      /* It is not possible to release (commit) a savepoint if there are
68102      ** active write statements.
68103      */
68104      sqlite3SetString(&p->zErrMsg, db,
68105        "cannot release savepoint - SQL statements in progress"
68106      );
68107      rc = SQLITE_BUSY;
68108    }else{
68109
68110      /* Determine whether or not this is a transaction savepoint. If so,
68111      ** and this is a RELEASE command, then the current transaction
68112      ** is committed.
68113      */
68114      int isTransaction = u.as.pSavepoint->pNext==0 && db->isTransactionSavepoint;
68115      if( isTransaction && u.as.p1==SAVEPOINT_RELEASE ){
68116        if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
68117          goto vdbe_return;
68118        }
68119        db->autoCommit = 1;
68120        if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
68121          p->pc = pc;
68122          db->autoCommit = 0;
68123          p->rc = rc = SQLITE_BUSY;
68124          goto vdbe_return;
68125        }
68126        db->isTransactionSavepoint = 0;
68127        rc = p->rc;
68128      }else{
68129        u.as.iSavepoint = db->nSavepoint - u.as.iSavepoint - 1;
68130        if( u.as.p1==SAVEPOINT_ROLLBACK ){
68131          for(u.as.ii=0; u.as.ii<db->nDb; u.as.ii++){
68132            sqlite3BtreeTripAllCursors(db->aDb[u.as.ii].pBt, SQLITE_ABORT);
68133          }
68134        }
68135        for(u.as.ii=0; u.as.ii<db->nDb; u.as.ii++){
68136          rc = sqlite3BtreeSavepoint(db->aDb[u.as.ii].pBt, u.as.p1, u.as.iSavepoint);
68137          if( rc!=SQLITE_OK ){
68138            goto abort_due_to_error;
68139          }
68140        }
68141        if( u.as.p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
68142          sqlite3ExpirePreparedStatements(db);
68143          sqlite3ResetAllSchemasOfConnection(db);
68144          db->flags = (db->flags | SQLITE_InternChanges);
68145        }
68146      }
68147
68148      /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
68149      ** savepoints nested inside of the savepoint being operated on. */
68150      while( db->pSavepoint!=u.as.pSavepoint ){
68151        u.as.pTmp = db->pSavepoint;
68152        db->pSavepoint = u.as.pTmp->pNext;
68153        sqlite3DbFree(db, u.as.pTmp);
68154        db->nSavepoint--;
68155      }
68156
68157      /* If it is a RELEASE, then destroy the savepoint being operated on
68158      ** too. If it is a ROLLBACK TO, then set the number of deferred
68159      ** constraint violations present in the database to the value stored
68160      ** when the savepoint was created.  */
68161      if( u.as.p1==SAVEPOINT_RELEASE ){
68162        assert( u.as.pSavepoint==db->pSavepoint );
68163        db->pSavepoint = u.as.pSavepoint->pNext;
68164        sqlite3DbFree(db, u.as.pSavepoint);
68165        if( !isTransaction ){
68166          db->nSavepoint--;
68167        }
68168      }else{
68169        db->nDeferredCons = u.as.pSavepoint->nDeferredCons;
68170      }
68171
68172      if( !isTransaction ){
68173        rc = sqlite3VtabSavepoint(db, u.as.p1, u.as.iSavepoint);
68174        if( rc!=SQLITE_OK ) goto abort_due_to_error;
68175      }
68176    }
68177  }
68178
68179  break;
68180}
68181
68182/* Opcode: AutoCommit P1 P2 * * *
68183**
68184** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
68185** back any currently active btree transactions. If there are any active
68186** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
68187** there are active writing VMs or active VMs that use shared cache.
68188**
68189** This instruction causes the VM to halt.
68190*/
68191case OP_AutoCommit: {
68192#if 0  /* local variables moved into u.at */
68193  int desiredAutoCommit;
68194  int iRollback;
68195  int turnOnAC;
68196#endif /* local variables moved into u.at */
68197
68198  u.at.desiredAutoCommit = pOp->p1;
68199  u.at.iRollback = pOp->p2;
68200  u.at.turnOnAC = u.at.desiredAutoCommit && !db->autoCommit;
68201  assert( u.at.desiredAutoCommit==1 || u.at.desiredAutoCommit==0 );
68202  assert( u.at.desiredAutoCommit==1 || u.at.iRollback==0 );
68203  assert( db->activeVdbeCnt>0 );  /* At least this one VM is active */
68204
68205#if 0
68206  if( u.at.turnOnAC && u.at.iRollback && db->activeVdbeCnt>1 ){
68207    /* If this instruction implements a ROLLBACK and other VMs are
68208    ** still running, and a transaction is active, return an error indicating
68209    ** that the other VMs must complete first.
68210    */
68211    sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
68212        "SQL statements in progress");
68213    rc = SQLITE_BUSY;
68214  }else
68215#endif
68216  if( u.at.turnOnAC && !u.at.iRollback && db->writeVdbeCnt>0 ){
68217    /* If this instruction implements a COMMIT and other VMs are writing
68218    ** return an error indicating that the other VMs must complete first.
68219    */
68220    sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
68221        "SQL statements in progress");
68222    rc = SQLITE_BUSY;
68223  }else if( u.at.desiredAutoCommit!=db->autoCommit ){
68224    if( u.at.iRollback ){
68225      assert( u.at.desiredAutoCommit==1 );
68226      sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
68227      db->autoCommit = 1;
68228    }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
68229      goto vdbe_return;
68230    }else{
68231      db->autoCommit = (u8)u.at.desiredAutoCommit;
68232      if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
68233        p->pc = pc;
68234        db->autoCommit = (u8)(1-u.at.desiredAutoCommit);
68235        p->rc = rc = SQLITE_BUSY;
68236        goto vdbe_return;
68237      }
68238    }
68239    assert( db->nStatement==0 );
68240    sqlite3CloseSavepoints(db);
68241    if( p->rc==SQLITE_OK ){
68242      rc = SQLITE_DONE;
68243    }else{
68244      rc = SQLITE_ERROR;
68245    }
68246    goto vdbe_return;
68247  }else{
68248    sqlite3SetString(&p->zErrMsg, db,
68249        (!u.at.desiredAutoCommit)?"cannot start a transaction within a transaction":(
68250        (u.at.iRollback)?"cannot rollback - no transaction is active":
68251                   "cannot commit - no transaction is active"));
68252
68253    rc = SQLITE_ERROR;
68254  }
68255  break;
68256}
68257
68258/* Opcode: Transaction P1 P2 * * *
68259**
68260** Begin a transaction.  The transaction ends when a Commit or Rollback
68261** opcode is encountered.  Depending on the ON CONFLICT setting, the
68262** transaction might also be rolled back if an error is encountered.
68263**
68264** P1 is the index of the database file on which the transaction is
68265** started.  Index 0 is the main database file and index 1 is the
68266** file used for temporary tables.  Indices of 2 or more are used for
68267** attached databases.
68268**
68269** If P2 is non-zero, then a write-transaction is started.  A RESERVED lock is
68270** obtained on the database file when a write-transaction is started.  No
68271** other process can start another write transaction while this transaction is
68272** underway.  Starting a write transaction also creates a rollback journal. A
68273** write transaction must be started before any changes can be made to the
68274** database.  If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
68275** on the file.
68276**
68277** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
68278** true (this flag is set if the Vdbe may modify more than one row and may
68279** throw an ABORT exception), a statement transaction may also be opened.
68280** More specifically, a statement transaction is opened iff the database
68281** connection is currently not in autocommit mode, or if there are other
68282** active statements. A statement transaction allows the changes made by this
68283** VDBE to be rolled back after an error without having to roll back the
68284** entire transaction. If no error is encountered, the statement transaction
68285** will automatically commit when the VDBE halts.
68286**
68287** If P2 is zero, then a read-lock is obtained on the database file.
68288*/
68289case OP_Transaction: {
68290#if 0  /* local variables moved into u.au */
68291  Btree *pBt;
68292#endif /* local variables moved into u.au */
68293
68294  assert( pOp->p1>=0 && pOp->p1<db->nDb );
68295  assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
68296  u.au.pBt = db->aDb[pOp->p1].pBt;
68297
68298  if( u.au.pBt ){
68299    rc = sqlite3BtreeBeginTrans(u.au.pBt, pOp->p2);
68300    if( rc==SQLITE_BUSY ){
68301      p->pc = pc;
68302      p->rc = rc = SQLITE_BUSY;
68303      goto vdbe_return;
68304    }
68305    if( rc!=SQLITE_OK ){
68306      goto abort_due_to_error;
68307    }
68308
68309    if( pOp->p2 && p->usesStmtJournal
68310     && (db->autoCommit==0 || db->activeVdbeCnt>1)
68311    ){
68312      assert( sqlite3BtreeIsInTrans(u.au.pBt) );
68313      if( p->iStatement==0 ){
68314        assert( db->nStatement>=0 && db->nSavepoint>=0 );
68315        db->nStatement++;
68316        p->iStatement = db->nSavepoint + db->nStatement;
68317      }
68318
68319      rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
68320      if( rc==SQLITE_OK ){
68321        rc = sqlite3BtreeBeginStmt(u.au.pBt, p->iStatement);
68322      }
68323
68324      /* Store the current value of the database handles deferred constraint
68325      ** counter. If the statement transaction needs to be rolled back,
68326      ** the value of this counter needs to be restored too.  */
68327      p->nStmtDefCons = db->nDeferredCons;
68328    }
68329  }
68330  break;
68331}
68332
68333/* Opcode: ReadCookie P1 P2 P3 * *
68334**
68335** Read cookie number P3 from database P1 and write it into register P2.
68336** P3==1 is the schema version.  P3==2 is the database format.
68337** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
68338** the main database file and P1==1 is the database file used to store
68339** temporary tables.
68340**
68341** There must be a read-lock on the database (either a transaction
68342** must be started or there must be an open cursor) before
68343** executing this instruction.
68344*/
68345case OP_ReadCookie: {               /* out2-prerelease */
68346#if 0  /* local variables moved into u.av */
68347  int iMeta;
68348  int iDb;
68349  int iCookie;
68350#endif /* local variables moved into u.av */
68351
68352  u.av.iDb = pOp->p1;
68353  u.av.iCookie = pOp->p3;
68354  assert( pOp->p3<SQLITE_N_BTREE_META );
68355  assert( u.av.iDb>=0 && u.av.iDb<db->nDb );
68356  assert( db->aDb[u.av.iDb].pBt!=0 );
68357  assert( (p->btreeMask & (((yDbMask)1)<<u.av.iDb))!=0 );
68358
68359  sqlite3BtreeGetMeta(db->aDb[u.av.iDb].pBt, u.av.iCookie, (u32 *)&u.av.iMeta);
68360  pOut->u.i = u.av.iMeta;
68361  break;
68362}
68363
68364/* Opcode: SetCookie P1 P2 P3 * *
68365**
68366** Write the content of register P3 (interpreted as an integer)
68367** into cookie number P2 of database P1.  P2==1 is the schema version.
68368** P2==2 is the database format. P2==3 is the recommended pager cache
68369** size, and so forth.  P1==0 is the main database file and P1==1 is the
68370** database file used to store temporary tables.
68371**
68372** A transaction must be started before executing this opcode.
68373*/
68374case OP_SetCookie: {       /* in3 */
68375#if 0  /* local variables moved into u.aw */
68376  Db *pDb;
68377#endif /* local variables moved into u.aw */
68378  assert( pOp->p2<SQLITE_N_BTREE_META );
68379  assert( pOp->p1>=0 && pOp->p1<db->nDb );
68380  assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
68381  u.aw.pDb = &db->aDb[pOp->p1];
68382  assert( u.aw.pDb->pBt!=0 );
68383  assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
68384  pIn3 = &aMem[pOp->p3];
68385  sqlite3VdbeMemIntegerify(pIn3);
68386  /* See note about index shifting on OP_ReadCookie */
68387  rc = sqlite3BtreeUpdateMeta(u.aw.pDb->pBt, pOp->p2, (int)pIn3->u.i);
68388  if( pOp->p2==BTREE_SCHEMA_VERSION ){
68389    /* When the schema cookie changes, record the new cookie internally */
68390    u.aw.pDb->pSchema->schema_cookie = (int)pIn3->u.i;
68391    db->flags |= SQLITE_InternChanges;
68392  }else if( pOp->p2==BTREE_FILE_FORMAT ){
68393    /* Record changes in the file format */
68394    u.aw.pDb->pSchema->file_format = (u8)pIn3->u.i;
68395  }
68396  if( pOp->p1==1 ){
68397    /* Invalidate all prepared statements whenever the TEMP database
68398    ** schema is changed.  Ticket #1644 */
68399    sqlite3ExpirePreparedStatements(db);
68400    p->expired = 0;
68401  }
68402  break;
68403}
68404
68405/* Opcode: VerifyCookie P1 P2 P3 * *
68406**
68407** Check the value of global database parameter number 0 (the
68408** schema version) and make sure it is equal to P2 and that the
68409** generation counter on the local schema parse equals P3.
68410**
68411** P1 is the database number which is 0 for the main database file
68412** and 1 for the file holding temporary tables and some higher number
68413** for auxiliary databases.
68414**
68415** The cookie changes its value whenever the database schema changes.
68416** This operation is used to detect when that the cookie has changed
68417** and that the current process needs to reread the schema.
68418**
68419** Either a transaction needs to have been started or an OP_Open needs
68420** to be executed (to establish a read lock) before this opcode is
68421** invoked.
68422*/
68423case OP_VerifyCookie: {
68424#if 0  /* local variables moved into u.ax */
68425  int iMeta;
68426  int iGen;
68427  Btree *pBt;
68428#endif /* local variables moved into u.ax */
68429
68430  assert( pOp->p1>=0 && pOp->p1<db->nDb );
68431  assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
68432  assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
68433  u.ax.pBt = db->aDb[pOp->p1].pBt;
68434  if( u.ax.pBt ){
68435    sqlite3BtreeGetMeta(u.ax.pBt, BTREE_SCHEMA_VERSION, (u32 *)&u.ax.iMeta);
68436    u.ax.iGen = db->aDb[pOp->p1].pSchema->iGeneration;
68437  }else{
68438    u.ax.iGen = u.ax.iMeta = 0;
68439  }
68440  if( u.ax.iMeta!=pOp->p2 || u.ax.iGen!=pOp->p3 ){
68441    sqlite3DbFree(db, p->zErrMsg);
68442    p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
68443    /* If the schema-cookie from the database file matches the cookie
68444    ** stored with the in-memory representation of the schema, do
68445    ** not reload the schema from the database file.
68446    **
68447    ** If virtual-tables are in use, this is not just an optimization.
68448    ** Often, v-tables store their data in other SQLite tables, which
68449    ** are queried from within xNext() and other v-table methods using
68450    ** prepared queries. If such a query is out-of-date, we do not want to
68451    ** discard the database schema, as the user code implementing the
68452    ** v-table would have to be ready for the sqlite3_vtab structure itself
68453    ** to be invalidated whenever sqlite3_step() is called from within
68454    ** a v-table method.
68455    */
68456    if( db->aDb[pOp->p1].pSchema->schema_cookie!=u.ax.iMeta ){
68457      sqlite3ResetOneSchema(db, pOp->p1);
68458    }
68459
68460    p->expired = 1;
68461    rc = SQLITE_SCHEMA;
68462  }
68463  break;
68464}
68465
68466/* Opcode: OpenRead P1 P2 P3 P4 P5
68467**
68468** Open a read-only cursor for the database table whose root page is
68469** P2 in a database file.  The database file is determined by P3.
68470** P3==0 means the main database, P3==1 means the database used for
68471** temporary tables, and P3>1 means used the corresponding attached
68472** database.  Give the new cursor an identifier of P1.  The P1
68473** values need not be contiguous but all P1 values should be small integers.
68474** It is an error for P1 to be negative.
68475**
68476** If P5!=0 then use the content of register P2 as the root page, not
68477** the value of P2 itself.
68478**
68479** There will be a read lock on the database whenever there is an
68480** open cursor.  If the database was unlocked prior to this instruction
68481** then a read lock is acquired as part of this instruction.  A read
68482** lock allows other processes to read the database but prohibits
68483** any other process from modifying the database.  The read lock is
68484** released when all cursors are closed.  If this instruction attempts
68485** to get a read lock but fails, the script terminates with an
68486** SQLITE_BUSY error code.
68487**
68488** The P4 value may be either an integer (P4_INT32) or a pointer to
68489** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
68490** structure, then said structure defines the content and collating
68491** sequence of the index being opened. Otherwise, if P4 is an integer
68492** value, it is set to the number of columns in the table.
68493**
68494** See also OpenWrite.
68495*/
68496/* Opcode: OpenWrite P1 P2 P3 P4 P5
68497**
68498** Open a read/write cursor named P1 on the table or index whose root
68499** page is P2.  Or if P5!=0 use the content of register P2 to find the
68500** root page.
68501**
68502** The P4 value may be either an integer (P4_INT32) or a pointer to
68503** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
68504** structure, then said structure defines the content and collating
68505** sequence of the index being opened. Otherwise, if P4 is an integer
68506** value, it is set to the number of columns in the table, or to the
68507** largest index of any column of the table that is actually used.
68508**
68509** This instruction works just like OpenRead except that it opens the cursor
68510** in read/write mode.  For a given table, there can be one or more read-only
68511** cursors or a single read/write cursor but not both.
68512**
68513** See also OpenRead.
68514*/
68515case OP_OpenRead:
68516case OP_OpenWrite: {
68517#if 0  /* local variables moved into u.ay */
68518  int nField;
68519  KeyInfo *pKeyInfo;
68520  int p2;
68521  int iDb;
68522  int wrFlag;
68523  Btree *pX;
68524  VdbeCursor *pCur;
68525  Db *pDb;
68526#endif /* local variables moved into u.ay */
68527
68528  assert( (pOp->p5&(OPFLAG_P2ISREG|OPFLAG_BULKCSR))==pOp->p5 );
68529  assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 );
68530
68531  if( p->expired ){
68532    rc = SQLITE_ABORT;
68533    break;
68534  }
68535
68536  u.ay.nField = 0;
68537  u.ay.pKeyInfo = 0;
68538  u.ay.p2 = pOp->p2;
68539  u.ay.iDb = pOp->p3;
68540  assert( u.ay.iDb>=0 && u.ay.iDb<db->nDb );
68541  assert( (p->btreeMask & (((yDbMask)1)<<u.ay.iDb))!=0 );
68542  u.ay.pDb = &db->aDb[u.ay.iDb];
68543  u.ay.pX = u.ay.pDb->pBt;
68544  assert( u.ay.pX!=0 );
68545  if( pOp->opcode==OP_OpenWrite ){
68546    u.ay.wrFlag = 1;
68547    assert( sqlite3SchemaMutexHeld(db, u.ay.iDb, 0) );
68548    if( u.ay.pDb->pSchema->file_format < p->minWriteFileFormat ){
68549      p->minWriteFileFormat = u.ay.pDb->pSchema->file_format;
68550    }
68551  }else{
68552    u.ay.wrFlag = 0;
68553  }
68554  if( pOp->p5 & OPFLAG_P2ISREG ){
68555    assert( u.ay.p2>0 );
68556    assert( u.ay.p2<=p->nMem );
68557    pIn2 = &aMem[u.ay.p2];
68558    assert( memIsValid(pIn2) );
68559    assert( (pIn2->flags & MEM_Int)!=0 );
68560    sqlite3VdbeMemIntegerify(pIn2);
68561    u.ay.p2 = (int)pIn2->u.i;
68562    /* The u.ay.p2 value always comes from a prior OP_CreateTable opcode and
68563    ** that opcode will always set the u.ay.p2 value to 2 or more or else fail.
68564    ** If there were a failure, the prepared statement would have halted
68565    ** before reaching this instruction. */
68566    if( NEVER(u.ay.p2<2) ) {
68567      rc = SQLITE_CORRUPT_BKPT;
68568      goto abort_due_to_error;
68569    }
68570  }
68571  if( pOp->p4type==P4_KEYINFO ){
68572    u.ay.pKeyInfo = pOp->p4.pKeyInfo;
68573    u.ay.pKeyInfo->enc = ENC(p->db);
68574    u.ay.nField = u.ay.pKeyInfo->nField+1;
68575  }else if( pOp->p4type==P4_INT32 ){
68576    u.ay.nField = pOp->p4.i;
68577  }
68578  assert( pOp->p1>=0 );
68579  u.ay.pCur = allocateCursor(p, pOp->p1, u.ay.nField, u.ay.iDb, 1);
68580  if( u.ay.pCur==0 ) goto no_mem;
68581  u.ay.pCur->nullRow = 1;
68582  u.ay.pCur->isOrdered = 1;
68583  rc = sqlite3BtreeCursor(u.ay.pX, u.ay.p2, u.ay.wrFlag, u.ay.pKeyInfo, u.ay.pCur->pCursor);
68584  u.ay.pCur->pKeyInfo = u.ay.pKeyInfo;
68585  assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
68586  sqlite3BtreeCursorHints(u.ay.pCur->pCursor, (pOp->p5 & OPFLAG_BULKCSR));
68587
68588  /* Since it performs no memory allocation or IO, the only value that
68589  ** sqlite3BtreeCursor() may return is SQLITE_OK. */
68590  assert( rc==SQLITE_OK );
68591
68592  /* Set the VdbeCursor.isTable and isIndex variables. Previous versions of
68593  ** SQLite used to check if the root-page flags were sane at this point
68594  ** and report database corruption if they were not, but this check has
68595  ** since moved into the btree layer.  */
68596  u.ay.pCur->isTable = pOp->p4type!=P4_KEYINFO;
68597  u.ay.pCur->isIndex = !u.ay.pCur->isTable;
68598  break;
68599}
68600
68601/* Opcode: OpenEphemeral P1 P2 * P4 P5
68602**
68603** Open a new cursor P1 to a transient table.
68604** The cursor is always opened read/write even if
68605** the main database is read-only.  The ephemeral
68606** table is deleted automatically when the cursor is closed.
68607**
68608** P2 is the number of columns in the ephemeral table.
68609** The cursor points to a BTree table if P4==0 and to a BTree index
68610** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
68611** that defines the format of keys in the index.
68612**
68613** This opcode was once called OpenTemp.  But that created
68614** confusion because the term "temp table", might refer either
68615** to a TEMP table at the SQL level, or to a table opened by
68616** this opcode.  Then this opcode was call OpenVirtual.  But
68617** that created confusion with the whole virtual-table idea.
68618**
68619** The P5 parameter can be a mask of the BTREE_* flags defined
68620** in btree.h.  These flags control aspects of the operation of
68621** the btree.  The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
68622** added automatically.
68623*/
68624/* Opcode: OpenAutoindex P1 P2 * P4 *
68625**
68626** This opcode works the same as OP_OpenEphemeral.  It has a
68627** different name to distinguish its use.  Tables created using
68628** by this opcode will be used for automatically created transient
68629** indices in joins.
68630*/
68631case OP_OpenAutoindex:
68632case OP_OpenEphemeral: {
68633#if 0  /* local variables moved into u.az */
68634  VdbeCursor *pCx;
68635#endif /* local variables moved into u.az */
68636  static const int vfsFlags =
68637      SQLITE_OPEN_READWRITE |
68638      SQLITE_OPEN_CREATE |
68639      SQLITE_OPEN_EXCLUSIVE |
68640      SQLITE_OPEN_DELETEONCLOSE |
68641      SQLITE_OPEN_TRANSIENT_DB;
68642
68643  assert( pOp->p1>=0 );
68644  u.az.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
68645  if( u.az.pCx==0 ) goto no_mem;
68646  u.az.pCx->nullRow = 1;
68647  rc = sqlite3BtreeOpen(db->pVfs, 0, db, &u.az.pCx->pBt,
68648                        BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
68649  if( rc==SQLITE_OK ){
68650    rc = sqlite3BtreeBeginTrans(u.az.pCx->pBt, 1);
68651  }
68652  if( rc==SQLITE_OK ){
68653    /* If a transient index is required, create it by calling
68654    ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
68655    ** opening it. If a transient table is required, just use the
68656    ** automatically created table with root-page 1 (an BLOB_INTKEY table).
68657    */
68658    if( pOp->p4.pKeyInfo ){
68659      int pgno;
68660      assert( pOp->p4type==P4_KEYINFO );
68661      rc = sqlite3BtreeCreateTable(u.az.pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5);
68662      if( rc==SQLITE_OK ){
68663        assert( pgno==MASTER_ROOT+1 );
68664        rc = sqlite3BtreeCursor(u.az.pCx->pBt, pgno, 1,
68665                                (KeyInfo*)pOp->p4.z, u.az.pCx->pCursor);
68666        u.az.pCx->pKeyInfo = pOp->p4.pKeyInfo;
68667        u.az.pCx->pKeyInfo->enc = ENC(p->db);
68668      }
68669      u.az.pCx->isTable = 0;
68670    }else{
68671      rc = sqlite3BtreeCursor(u.az.pCx->pBt, MASTER_ROOT, 1, 0, u.az.pCx->pCursor);
68672      u.az.pCx->isTable = 1;
68673    }
68674  }
68675  u.az.pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
68676  u.az.pCx->isIndex = !u.az.pCx->isTable;
68677  break;
68678}
68679
68680/* Opcode: SorterOpen P1 P2 * P4 *
68681**
68682** This opcode works like OP_OpenEphemeral except that it opens
68683** a transient index that is specifically designed to sort large
68684** tables using an external merge-sort algorithm.
68685*/
68686case OP_SorterOpen: {
68687#if 0  /* local variables moved into u.ba */
68688  VdbeCursor *pCx;
68689#endif /* local variables moved into u.ba */
68690
68691  u.ba.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
68692  if( u.ba.pCx==0 ) goto no_mem;
68693  u.ba.pCx->pKeyInfo = pOp->p4.pKeyInfo;
68694  u.ba.pCx->pKeyInfo->enc = ENC(p->db);
68695  u.ba.pCx->isSorter = 1;
68696  rc = sqlite3VdbeSorterInit(db, u.ba.pCx);
68697  break;
68698}
68699
68700/* Opcode: OpenPseudo P1 P2 P3 * P5
68701**
68702** Open a new cursor that points to a fake table that contains a single
68703** row of data.  The content of that one row in the content of memory
68704** register P2 when P5==0.  In other words, cursor P1 becomes an alias for the
68705** MEM_Blob content contained in register P2.  When P5==1, then the
68706** row is represented by P3 consecutive registers beginning with P2.
68707**
68708** A pseudo-table created by this opcode is used to hold a single
68709** row output from the sorter so that the row can be decomposed into
68710** individual columns using the OP_Column opcode.  The OP_Column opcode
68711** is the only cursor opcode that works with a pseudo-table.
68712**
68713** P3 is the number of fields in the records that will be stored by
68714** the pseudo-table.
68715*/
68716case OP_OpenPseudo: {
68717#if 0  /* local variables moved into u.bb */
68718  VdbeCursor *pCx;
68719#endif /* local variables moved into u.bb */
68720
68721  assert( pOp->p1>=0 );
68722  u.bb.pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
68723  if( u.bb.pCx==0 ) goto no_mem;
68724  u.bb.pCx->nullRow = 1;
68725  u.bb.pCx->pseudoTableReg = pOp->p2;
68726  u.bb.pCx->isTable = 1;
68727  u.bb.pCx->isIndex = 0;
68728  u.bb.pCx->multiPseudo = pOp->p5;
68729  break;
68730}
68731
68732/* Opcode: Close P1 * * * *
68733**
68734** Close a cursor previously opened as P1.  If P1 is not
68735** currently open, this instruction is a no-op.
68736*/
68737case OP_Close: {
68738  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68739  sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
68740  p->apCsr[pOp->p1] = 0;
68741  break;
68742}
68743
68744/* Opcode: SeekGe P1 P2 P3 P4 *
68745**
68746** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
68747** use the value in register P3 as the key.  If cursor P1 refers
68748** to an SQL index, then P3 is the first in an array of P4 registers
68749** that are used as an unpacked index key.
68750**
68751** Reposition cursor P1 so that  it points to the smallest entry that
68752** is greater than or equal to the key value. If there are no records
68753** greater than or equal to the key and P2 is not zero, then jump to P2.
68754**
68755** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe
68756*/
68757/* Opcode: SeekGt P1 P2 P3 P4 *
68758**
68759** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
68760** use the value in register P3 as a key. If cursor P1 refers
68761** to an SQL index, then P3 is the first in an array of P4 registers
68762** that are used as an unpacked index key.
68763**
68764** Reposition cursor P1 so that  it points to the smallest entry that
68765** is greater than the key value. If there are no records greater than
68766** the key and P2 is not zero, then jump to P2.
68767**
68768** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe
68769*/
68770/* Opcode: SeekLt P1 P2 P3 P4 *
68771**
68772** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
68773** use the value in register P3 as a key. If cursor P1 refers
68774** to an SQL index, then P3 is the first in an array of P4 registers
68775** that are used as an unpacked index key.
68776**
68777** Reposition cursor P1 so that  it points to the largest entry that
68778** is less than the key value. If there are no records less than
68779** the key and P2 is not zero, then jump to P2.
68780**
68781** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe
68782*/
68783/* Opcode: SeekLe P1 P2 P3 P4 *
68784**
68785** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
68786** use the value in register P3 as a key. If cursor P1 refers
68787** to an SQL index, then P3 is the first in an array of P4 registers
68788** that are used as an unpacked index key.
68789**
68790** Reposition cursor P1 so that it points to the largest entry that
68791** is less than or equal to the key value. If there are no records
68792** less than or equal to the key and P2 is not zero, then jump to P2.
68793**
68794** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt
68795*/
68796case OP_SeekLt:         /* jump, in3 */
68797case OP_SeekLe:         /* jump, in3 */
68798case OP_SeekGe:         /* jump, in3 */
68799case OP_SeekGt: {       /* jump, in3 */
68800#if 0  /* local variables moved into u.bc */
68801  int res;
68802  int oc;
68803  VdbeCursor *pC;
68804  UnpackedRecord r;
68805  int nField;
68806  i64 iKey;      /* The rowid we are to seek to */
68807#endif /* local variables moved into u.bc */
68808
68809  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68810  assert( pOp->p2!=0 );
68811  u.bc.pC = p->apCsr[pOp->p1];
68812  assert( u.bc.pC!=0 );
68813  assert( u.bc.pC->pseudoTableReg==0 );
68814  assert( OP_SeekLe == OP_SeekLt+1 );
68815  assert( OP_SeekGe == OP_SeekLt+2 );
68816  assert( OP_SeekGt == OP_SeekLt+3 );
68817  assert( u.bc.pC->isOrdered );
68818  if( ALWAYS(u.bc.pC->pCursor!=0) ){
68819    u.bc.oc = pOp->opcode;
68820    u.bc.pC->nullRow = 0;
68821    if( u.bc.pC->isTable ){
68822      /* The input value in P3 might be of any type: integer, real, string,
68823      ** blob, or NULL.  But it needs to be an integer before we can do
68824      ** the seek, so covert it. */
68825      pIn3 = &aMem[pOp->p3];
68826      applyNumericAffinity(pIn3);
68827      u.bc.iKey = sqlite3VdbeIntValue(pIn3);
68828      u.bc.pC->rowidIsValid = 0;
68829
68830      /* If the P3 value could not be converted into an integer without
68831      ** loss of information, then special processing is required... */
68832      if( (pIn3->flags & MEM_Int)==0 ){
68833        if( (pIn3->flags & MEM_Real)==0 ){
68834          /* If the P3 value cannot be converted into any kind of a number,
68835          ** then the seek is not possible, so jump to P2 */
68836          pc = pOp->p2 - 1;
68837          break;
68838        }
68839        /* If we reach this point, then the P3 value must be a floating
68840        ** point number. */
68841        assert( (pIn3->flags & MEM_Real)!=0 );
68842
68843        if( u.bc.iKey==SMALLEST_INT64 && (pIn3->r<(double)u.bc.iKey || pIn3->r>0) ){
68844          /* The P3 value is too large in magnitude to be expressed as an
68845          ** integer. */
68846          u.bc.res = 1;
68847          if( pIn3->r<0 ){
68848            if( u.bc.oc>=OP_SeekGe ){  assert( u.bc.oc==OP_SeekGe || u.bc.oc==OP_SeekGt );
68849              rc = sqlite3BtreeFirst(u.bc.pC->pCursor, &u.bc.res);
68850              if( rc!=SQLITE_OK ) goto abort_due_to_error;
68851            }
68852          }else{
68853            if( u.bc.oc<=OP_SeekLe ){  assert( u.bc.oc==OP_SeekLt || u.bc.oc==OP_SeekLe );
68854              rc = sqlite3BtreeLast(u.bc.pC->pCursor, &u.bc.res);
68855              if( rc!=SQLITE_OK ) goto abort_due_to_error;
68856            }
68857          }
68858          if( u.bc.res ){
68859            pc = pOp->p2 - 1;
68860          }
68861          break;
68862        }else if( u.bc.oc==OP_SeekLt || u.bc.oc==OP_SeekGe ){
68863          /* Use the ceiling() function to convert real->int */
68864          if( pIn3->r > (double)u.bc.iKey ) u.bc.iKey++;
68865        }else{
68866          /* Use the floor() function to convert real->int */
68867          assert( u.bc.oc==OP_SeekLe || u.bc.oc==OP_SeekGt );
68868          if( pIn3->r < (double)u.bc.iKey ) u.bc.iKey--;
68869        }
68870      }
68871      rc = sqlite3BtreeMovetoUnpacked(u.bc.pC->pCursor, 0, (u64)u.bc.iKey, 0, &u.bc.res);
68872      if( rc!=SQLITE_OK ){
68873        goto abort_due_to_error;
68874      }
68875      if( u.bc.res==0 ){
68876        u.bc.pC->rowidIsValid = 1;
68877        u.bc.pC->lastRowid = u.bc.iKey;
68878      }
68879    }else{
68880      u.bc.nField = pOp->p4.i;
68881      assert( pOp->p4type==P4_INT32 );
68882      assert( u.bc.nField>0 );
68883      u.bc.r.pKeyInfo = u.bc.pC->pKeyInfo;
68884      u.bc.r.nField = (u16)u.bc.nField;
68885
68886      /* The next line of code computes as follows, only faster:
68887      **   if( u.bc.oc==OP_SeekGt || u.bc.oc==OP_SeekLe ){
68888      **     u.bc.r.flags = UNPACKED_INCRKEY;
68889      **   }else{
68890      **     u.bc.r.flags = 0;
68891      **   }
68892      */
68893      u.bc.r.flags = (u8)(UNPACKED_INCRKEY * (1 & (u.bc.oc - OP_SeekLt)));
68894      assert( u.bc.oc!=OP_SeekGt || u.bc.r.flags==UNPACKED_INCRKEY );
68895      assert( u.bc.oc!=OP_SeekLe || u.bc.r.flags==UNPACKED_INCRKEY );
68896      assert( u.bc.oc!=OP_SeekGe || u.bc.r.flags==0 );
68897      assert( u.bc.oc!=OP_SeekLt || u.bc.r.flags==0 );
68898
68899      u.bc.r.aMem = &aMem[pOp->p3];
68900#ifdef SQLITE_DEBUG
68901      { int i; for(i=0; i<u.bc.r.nField; i++) assert( memIsValid(&u.bc.r.aMem[i]) ); }
68902#endif
68903      ExpandBlob(u.bc.r.aMem);
68904      rc = sqlite3BtreeMovetoUnpacked(u.bc.pC->pCursor, &u.bc.r, 0, 0, &u.bc.res);
68905      if( rc!=SQLITE_OK ){
68906        goto abort_due_to_error;
68907      }
68908      u.bc.pC->rowidIsValid = 0;
68909    }
68910    u.bc.pC->deferredMoveto = 0;
68911    u.bc.pC->cacheStatus = CACHE_STALE;
68912#ifdef SQLITE_TEST
68913    sqlite3_search_count++;
68914#endif
68915    if( u.bc.oc>=OP_SeekGe ){  assert( u.bc.oc==OP_SeekGe || u.bc.oc==OP_SeekGt );
68916      if( u.bc.res<0 || (u.bc.res==0 && u.bc.oc==OP_SeekGt) ){
68917        rc = sqlite3BtreeNext(u.bc.pC->pCursor, &u.bc.res);
68918        if( rc!=SQLITE_OK ) goto abort_due_to_error;
68919        u.bc.pC->rowidIsValid = 0;
68920      }else{
68921        u.bc.res = 0;
68922      }
68923    }else{
68924      assert( u.bc.oc==OP_SeekLt || u.bc.oc==OP_SeekLe );
68925      if( u.bc.res>0 || (u.bc.res==0 && u.bc.oc==OP_SeekLt) ){
68926        rc = sqlite3BtreePrevious(u.bc.pC->pCursor, &u.bc.res);
68927        if( rc!=SQLITE_OK ) goto abort_due_to_error;
68928        u.bc.pC->rowidIsValid = 0;
68929      }else{
68930        /* u.bc.res might be negative because the table is empty.  Check to
68931        ** see if this is the case.
68932        */
68933        u.bc.res = sqlite3BtreeEof(u.bc.pC->pCursor);
68934      }
68935    }
68936    assert( pOp->p2>0 );
68937    if( u.bc.res ){
68938      pc = pOp->p2 - 1;
68939    }
68940  }else{
68941    /* This happens when attempting to open the sqlite3_master table
68942    ** for read access returns SQLITE_EMPTY. In this case always
68943    ** take the jump (since there are no records in the table).
68944    */
68945    pc = pOp->p2 - 1;
68946  }
68947  break;
68948}
68949
68950/* Opcode: Seek P1 P2 * * *
68951**
68952** P1 is an open table cursor and P2 is a rowid integer.  Arrange
68953** for P1 to move so that it points to the rowid given by P2.
68954**
68955** This is actually a deferred seek.  Nothing actually happens until
68956** the cursor is used to read a record.  That way, if no reads
68957** occur, no unnecessary I/O happens.
68958*/
68959case OP_Seek: {    /* in2 */
68960#if 0  /* local variables moved into u.bd */
68961  VdbeCursor *pC;
68962#endif /* local variables moved into u.bd */
68963
68964  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68965  u.bd.pC = p->apCsr[pOp->p1];
68966  assert( u.bd.pC!=0 );
68967  if( ALWAYS(u.bd.pC->pCursor!=0) ){
68968    assert( u.bd.pC->isTable );
68969    u.bd.pC->nullRow = 0;
68970    pIn2 = &aMem[pOp->p2];
68971    u.bd.pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
68972    u.bd.pC->rowidIsValid = 0;
68973    u.bd.pC->deferredMoveto = 1;
68974  }
68975  break;
68976}
68977
68978
68979/* Opcode: Found P1 P2 P3 P4 *
68980**
68981** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
68982** P4>0 then register P3 is the first of P4 registers that form an unpacked
68983** record.
68984**
68985** Cursor P1 is on an index btree.  If the record identified by P3 and P4
68986** is a prefix of any entry in P1 then a jump is made to P2 and
68987** P1 is left pointing at the matching entry.
68988*/
68989/* Opcode: NotFound P1 P2 P3 P4 *
68990**
68991** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
68992** P4>0 then register P3 is the first of P4 registers that form an unpacked
68993** record.
68994**
68995** Cursor P1 is on an index btree.  If the record identified by P3 and P4
68996** is not the prefix of any entry in P1 then a jump is made to P2.  If P1
68997** does contain an entry whose prefix matches the P3/P4 record then control
68998** falls through to the next instruction and P1 is left pointing at the
68999** matching entry.
69000**
69001** See also: Found, NotExists, IsUnique
69002*/
69003case OP_NotFound:       /* jump, in3 */
69004case OP_Found: {        /* jump, in3 */
69005#if 0  /* local variables moved into u.be */
69006  int alreadyExists;
69007  VdbeCursor *pC;
69008  int res;
69009  char *pFree;
69010  UnpackedRecord *pIdxKey;
69011  UnpackedRecord r;
69012  char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
69013#endif /* local variables moved into u.be */
69014
69015#ifdef SQLITE_TEST
69016  sqlite3_found_count++;
69017#endif
69018
69019  u.be.alreadyExists = 0;
69020  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69021  assert( pOp->p4type==P4_INT32 );
69022  u.be.pC = p->apCsr[pOp->p1];
69023  assert( u.be.pC!=0 );
69024  pIn3 = &aMem[pOp->p3];
69025  if( ALWAYS(u.be.pC->pCursor!=0) ){
69026
69027    assert( u.be.pC->isTable==0 );
69028    if( pOp->p4.i>0 ){
69029      u.be.r.pKeyInfo = u.be.pC->pKeyInfo;
69030      u.be.r.nField = (u16)pOp->p4.i;
69031      u.be.r.aMem = pIn3;
69032#ifdef SQLITE_DEBUG
69033      { int i; for(i=0; i<u.be.r.nField; i++) assert( memIsValid(&u.be.r.aMem[i]) ); }
69034#endif
69035      u.be.r.flags = UNPACKED_PREFIX_MATCH;
69036      u.be.pIdxKey = &u.be.r;
69037    }else{
69038      u.be.pIdxKey = sqlite3VdbeAllocUnpackedRecord(
69039          u.be.pC->pKeyInfo, u.be.aTempRec, sizeof(u.be.aTempRec), &u.be.pFree
69040      );
69041      if( u.be.pIdxKey==0 ) goto no_mem;
69042      assert( pIn3->flags & MEM_Blob );
69043      assert( (pIn3->flags & MEM_Zero)==0 );  /* zeroblobs already expanded */
69044      sqlite3VdbeRecordUnpack(u.be.pC->pKeyInfo, pIn3->n, pIn3->z, u.be.pIdxKey);
69045      u.be.pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
69046    }
69047    rc = sqlite3BtreeMovetoUnpacked(u.be.pC->pCursor, u.be.pIdxKey, 0, 0, &u.be.res);
69048    if( pOp->p4.i==0 ){
69049      sqlite3DbFree(db, u.be.pFree);
69050    }
69051    if( rc!=SQLITE_OK ){
69052      break;
69053    }
69054    u.be.alreadyExists = (u.be.res==0);
69055    u.be.pC->deferredMoveto = 0;
69056    u.be.pC->cacheStatus = CACHE_STALE;
69057  }
69058  if( pOp->opcode==OP_Found ){
69059    if( u.be.alreadyExists ) pc = pOp->p2 - 1;
69060  }else{
69061    if( !u.be.alreadyExists ) pc = pOp->p2 - 1;
69062  }
69063  break;
69064}
69065
69066/* Opcode: IsUnique P1 P2 P3 P4 *
69067**
69068** Cursor P1 is open on an index b-tree - that is to say, a btree which
69069** no data and where the key are records generated by OP_MakeRecord with
69070** the list field being the integer ROWID of the entry that the index
69071** entry refers to.
69072**
69073** The P3 register contains an integer record number. Call this record
69074** number R. Register P4 is the first in a set of N contiguous registers
69075** that make up an unpacked index key that can be used with cursor P1.
69076** The value of N can be inferred from the cursor. N includes the rowid
69077** value appended to the end of the index record. This rowid value may
69078** or may not be the same as R.
69079**
69080** If any of the N registers beginning with register P4 contains a NULL
69081** value, jump immediately to P2.
69082**
69083** Otherwise, this instruction checks if cursor P1 contains an entry
69084** where the first (N-1) fields match but the rowid value at the end
69085** of the index entry is not R. If there is no such entry, control jumps
69086** to instruction P2. Otherwise, the rowid of the conflicting index
69087** entry is copied to register P3 and control falls through to the next
69088** instruction.
69089**
69090** See also: NotFound, NotExists, Found
69091*/
69092case OP_IsUnique: {        /* jump, in3 */
69093#if 0  /* local variables moved into u.bf */
69094  u16 ii;
69095  VdbeCursor *pCx;
69096  BtCursor *pCrsr;
69097  u16 nField;
69098  Mem *aMx;
69099  UnpackedRecord r;                  /* B-Tree index search key */
69100  i64 R;                             /* Rowid stored in register P3 */
69101#endif /* local variables moved into u.bf */
69102
69103  pIn3 = &aMem[pOp->p3];
69104  u.bf.aMx = &aMem[pOp->p4.i];
69105  /* Assert that the values of parameters P1 and P4 are in range. */
69106  assert( pOp->p4type==P4_INT32 );
69107  assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
69108  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69109
69110  /* Find the index cursor. */
69111  u.bf.pCx = p->apCsr[pOp->p1];
69112  assert( u.bf.pCx->deferredMoveto==0 );
69113  u.bf.pCx->seekResult = 0;
69114  u.bf.pCx->cacheStatus = CACHE_STALE;
69115  u.bf.pCrsr = u.bf.pCx->pCursor;
69116
69117  /* If any of the values are NULL, take the jump. */
69118  u.bf.nField = u.bf.pCx->pKeyInfo->nField;
69119  for(u.bf.ii=0; u.bf.ii<u.bf.nField; u.bf.ii++){
69120    if( u.bf.aMx[u.bf.ii].flags & MEM_Null ){
69121      pc = pOp->p2 - 1;
69122      u.bf.pCrsr = 0;
69123      break;
69124    }
69125  }
69126  assert( (u.bf.aMx[u.bf.nField].flags & MEM_Null)==0 );
69127
69128  if( u.bf.pCrsr!=0 ){
69129    /* Populate the index search key. */
69130    u.bf.r.pKeyInfo = u.bf.pCx->pKeyInfo;
69131    u.bf.r.nField = u.bf.nField + 1;
69132    u.bf.r.flags = UNPACKED_PREFIX_SEARCH;
69133    u.bf.r.aMem = u.bf.aMx;
69134#ifdef SQLITE_DEBUG
69135    { int i; for(i=0; i<u.bf.r.nField; i++) assert( memIsValid(&u.bf.r.aMem[i]) ); }
69136#endif
69137
69138    /* Extract the value of u.bf.R from register P3. */
69139    sqlite3VdbeMemIntegerify(pIn3);
69140    u.bf.R = pIn3->u.i;
69141
69142    /* Search the B-Tree index. If no conflicting record is found, jump
69143    ** to P2. Otherwise, copy the rowid of the conflicting record to
69144    ** register P3 and fall through to the next instruction.  */
69145    rc = sqlite3BtreeMovetoUnpacked(u.bf.pCrsr, &u.bf.r, 0, 0, &u.bf.pCx->seekResult);
69146    if( (u.bf.r.flags & UNPACKED_PREFIX_SEARCH) || u.bf.r.rowid==u.bf.R ){
69147      pc = pOp->p2 - 1;
69148    }else{
69149      pIn3->u.i = u.bf.r.rowid;
69150    }
69151  }
69152  break;
69153}
69154
69155/* Opcode: NotExists P1 P2 P3 * *
69156**
69157** Use the content of register P3 as an integer key.  If a record
69158** with that key does not exist in table of P1, then jump to P2.
69159** If the record does exist, then fall through.  The cursor is left
69160** pointing to the record if it exists.
69161**
69162** The difference between this operation and NotFound is that this
69163** operation assumes the key is an integer and that P1 is a table whereas
69164** NotFound assumes key is a blob constructed from MakeRecord and
69165** P1 is an index.
69166**
69167** See also: Found, NotFound, IsUnique
69168*/
69169case OP_NotExists: {        /* jump, in3 */
69170#if 0  /* local variables moved into u.bg */
69171  VdbeCursor *pC;
69172  BtCursor *pCrsr;
69173  int res;
69174  u64 iKey;
69175#endif /* local variables moved into u.bg */
69176
69177  pIn3 = &aMem[pOp->p3];
69178  assert( pIn3->flags & MEM_Int );
69179  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69180  u.bg.pC = p->apCsr[pOp->p1];
69181  assert( u.bg.pC!=0 );
69182  assert( u.bg.pC->isTable );
69183  assert( u.bg.pC->pseudoTableReg==0 );
69184  u.bg.pCrsr = u.bg.pC->pCursor;
69185  if( ALWAYS(u.bg.pCrsr!=0) ){
69186    u.bg.res = 0;
69187    u.bg.iKey = pIn3->u.i;
69188    rc = sqlite3BtreeMovetoUnpacked(u.bg.pCrsr, 0, u.bg.iKey, 0, &u.bg.res);
69189    u.bg.pC->lastRowid = pIn3->u.i;
69190    u.bg.pC->rowidIsValid = u.bg.res==0 ?1:0;
69191    u.bg.pC->nullRow = 0;
69192    u.bg.pC->cacheStatus = CACHE_STALE;
69193    u.bg.pC->deferredMoveto = 0;
69194    if( u.bg.res!=0 ){
69195      pc = pOp->p2 - 1;
69196      assert( u.bg.pC->rowidIsValid==0 );
69197    }
69198    u.bg.pC->seekResult = u.bg.res;
69199  }else{
69200    /* This happens when an attempt to open a read cursor on the
69201    ** sqlite_master table returns SQLITE_EMPTY.
69202    */
69203    pc = pOp->p2 - 1;
69204    assert( u.bg.pC->rowidIsValid==0 );
69205    u.bg.pC->seekResult = 0;
69206  }
69207  break;
69208}
69209
69210/* Opcode: Sequence P1 P2 * * *
69211**
69212** Find the next available sequence number for cursor P1.
69213** Write the sequence number into register P2.
69214** The sequence number on the cursor is incremented after this
69215** instruction.
69216*/
69217case OP_Sequence: {           /* out2-prerelease */
69218  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69219  assert( p->apCsr[pOp->p1]!=0 );
69220  pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
69221  break;
69222}
69223
69224
69225/* Opcode: NewRowid P1 P2 P3 * *
69226**
69227** Get a new integer record number (a.k.a "rowid") used as the key to a table.
69228** The record number is not previously used as a key in the database
69229** table that cursor P1 points to.  The new record number is written
69230** written to register P2.
69231**
69232** If P3>0 then P3 is a register in the root frame of this VDBE that holds
69233** the largest previously generated record number. No new record numbers are
69234** allowed to be less than this value. When this value reaches its maximum,
69235** an SQLITE_FULL error is generated. The P3 register is updated with the '
69236** generated record number. This P3 mechanism is used to help implement the
69237** AUTOINCREMENT feature.
69238*/
69239case OP_NewRowid: {           /* out2-prerelease */
69240#if 0  /* local variables moved into u.bh */
69241  i64 v;                 /* The new rowid */
69242  VdbeCursor *pC;        /* Cursor of table to get the new rowid */
69243  int res;               /* Result of an sqlite3BtreeLast() */
69244  int cnt;               /* Counter to limit the number of searches */
69245  Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
69246  VdbeFrame *pFrame;     /* Root frame of VDBE */
69247#endif /* local variables moved into u.bh */
69248
69249  u.bh.v = 0;
69250  u.bh.res = 0;
69251  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69252  u.bh.pC = p->apCsr[pOp->p1];
69253  assert( u.bh.pC!=0 );
69254  if( NEVER(u.bh.pC->pCursor==0) ){
69255    /* The zero initialization above is all that is needed */
69256  }else{
69257    /* The next rowid or record number (different terms for the same
69258    ** thing) is obtained in a two-step algorithm.
69259    **
69260    ** First we attempt to find the largest existing rowid and add one
69261    ** to that.  But if the largest existing rowid is already the maximum
69262    ** positive integer, we have to fall through to the second
69263    ** probabilistic algorithm
69264    **
69265    ** The second algorithm is to select a rowid at random and see if
69266    ** it already exists in the table.  If it does not exist, we have
69267    ** succeeded.  If the random rowid does exist, we select a new one
69268    ** and try again, up to 100 times.
69269    */
69270    assert( u.bh.pC->isTable );
69271
69272#ifdef SQLITE_32BIT_ROWID
69273#   define MAX_ROWID 0x7fffffff
69274#else
69275    /* Some compilers complain about constants of the form 0x7fffffffffffffff.
69276    ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
69277    ** to provide the constant while making all compilers happy.
69278    */
69279#   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
69280#endif
69281
69282    if( !u.bh.pC->useRandomRowid ){
69283      u.bh.v = sqlite3BtreeGetCachedRowid(u.bh.pC->pCursor);
69284      if( u.bh.v==0 ){
69285        rc = sqlite3BtreeLast(u.bh.pC->pCursor, &u.bh.res);
69286        if( rc!=SQLITE_OK ){
69287          goto abort_due_to_error;
69288        }
69289        if( u.bh.res ){
69290          u.bh.v = 1;   /* IMP: R-61914-48074 */
69291        }else{
69292          assert( sqlite3BtreeCursorIsValid(u.bh.pC->pCursor) );
69293          rc = sqlite3BtreeKeySize(u.bh.pC->pCursor, &u.bh.v);
69294          assert( rc==SQLITE_OK );   /* Cannot fail following BtreeLast() */
69295          if( u.bh.v>=MAX_ROWID ){
69296            u.bh.pC->useRandomRowid = 1;
69297          }else{
69298            u.bh.v++;   /* IMP: R-29538-34987 */
69299          }
69300        }
69301      }
69302
69303#ifndef SQLITE_OMIT_AUTOINCREMENT
69304      if( pOp->p3 ){
69305        /* Assert that P3 is a valid memory cell. */
69306        assert( pOp->p3>0 );
69307        if( p->pFrame ){
69308          for(u.bh.pFrame=p->pFrame; u.bh.pFrame->pParent; u.bh.pFrame=u.bh.pFrame->pParent);
69309          /* Assert that P3 is a valid memory cell. */
69310          assert( pOp->p3<=u.bh.pFrame->nMem );
69311          u.bh.pMem = &u.bh.pFrame->aMem[pOp->p3];
69312        }else{
69313          /* Assert that P3 is a valid memory cell. */
69314          assert( pOp->p3<=p->nMem );
69315          u.bh.pMem = &aMem[pOp->p3];
69316          memAboutToChange(p, u.bh.pMem);
69317        }
69318        assert( memIsValid(u.bh.pMem) );
69319
69320        REGISTER_TRACE(pOp->p3, u.bh.pMem);
69321        sqlite3VdbeMemIntegerify(u.bh.pMem);
69322        assert( (u.bh.pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
69323        if( u.bh.pMem->u.i==MAX_ROWID || u.bh.pC->useRandomRowid ){
69324          rc = SQLITE_FULL;   /* IMP: R-12275-61338 */
69325          goto abort_due_to_error;
69326        }
69327        if( u.bh.v<u.bh.pMem->u.i+1 ){
69328          u.bh.v = u.bh.pMem->u.i + 1;
69329        }
69330        u.bh.pMem->u.i = u.bh.v;
69331      }
69332#endif
69333
69334      sqlite3BtreeSetCachedRowid(u.bh.pC->pCursor, u.bh.v<MAX_ROWID ? u.bh.v+1 : 0);
69335    }
69336    if( u.bh.pC->useRandomRowid ){
69337      /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
69338      ** largest possible integer (9223372036854775807) then the database
69339      ** engine starts picking positive candidate ROWIDs at random until
69340      ** it finds one that is not previously used. */
69341      assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
69342                             ** an AUTOINCREMENT table. */
69343      /* on the first attempt, simply do one more than previous */
69344      u.bh.v = lastRowid;
69345      u.bh.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
69346      u.bh.v++; /* ensure non-zero */
69347      u.bh.cnt = 0;
69348      while(   ((rc = sqlite3BtreeMovetoUnpacked(u.bh.pC->pCursor, 0, (u64)u.bh.v,
69349                                                 0, &u.bh.res))==SQLITE_OK)
69350            && (u.bh.res==0)
69351            && (++u.bh.cnt<100)){
69352        /* collision - try another random rowid */
69353        sqlite3_randomness(sizeof(u.bh.v), &u.bh.v);
69354        if( u.bh.cnt<5 ){
69355          /* try "small" random rowids for the initial attempts */
69356          u.bh.v &= 0xffffff;
69357        }else{
69358          u.bh.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
69359        }
69360        u.bh.v++; /* ensure non-zero */
69361      }
69362      if( rc==SQLITE_OK && u.bh.res==0 ){
69363        rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
69364        goto abort_due_to_error;
69365      }
69366      assert( u.bh.v>0 );  /* EV: R-40812-03570 */
69367    }
69368    u.bh.pC->rowidIsValid = 0;
69369    u.bh.pC->deferredMoveto = 0;
69370    u.bh.pC->cacheStatus = CACHE_STALE;
69371  }
69372  pOut->u.i = u.bh.v;
69373  break;
69374}
69375
69376/* Opcode: Insert P1 P2 P3 P4 P5
69377**
69378** Write an entry into the table of cursor P1.  A new entry is
69379** created if it doesn't already exist or the data for an existing
69380** entry is overwritten.  The data is the value MEM_Blob stored in register
69381** number P2. The key is stored in register P3. The key must
69382** be a MEM_Int.
69383**
69384** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
69385** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
69386** then rowid is stored for subsequent return by the
69387** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
69388**
69389** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
69390** the last seek operation (OP_NotExists) was a success, then this
69391** operation will not attempt to find the appropriate row before doing
69392** the insert but will instead overwrite the row that the cursor is
69393** currently pointing to.  Presumably, the prior OP_NotExists opcode
69394** has already positioned the cursor correctly.  This is an optimization
69395** that boosts performance by avoiding redundant seeks.
69396**
69397** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
69398** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
69399** is part of an INSERT operation.  The difference is only important to
69400** the update hook.
69401**
69402** Parameter P4 may point to a string containing the table-name, or
69403** may be NULL. If it is not NULL, then the update-hook
69404** (sqlite3.xUpdateCallback) is invoked following a successful insert.
69405**
69406** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
69407** allocated, then ownership of P2 is transferred to the pseudo-cursor
69408** and register P2 becomes ephemeral.  If the cursor is changed, the
69409** value of register P2 will then change.  Make sure this does not
69410** cause any problems.)
69411**
69412** This instruction only works on tables.  The equivalent instruction
69413** for indices is OP_IdxInsert.
69414*/
69415/* Opcode: InsertInt P1 P2 P3 P4 P5
69416**
69417** This works exactly like OP_Insert except that the key is the
69418** integer value P3, not the value of the integer stored in register P3.
69419*/
69420case OP_Insert:
69421case OP_InsertInt: {
69422#if 0  /* local variables moved into u.bi */
69423  Mem *pData;       /* MEM cell holding data for the record to be inserted */
69424  Mem *pKey;        /* MEM cell holding key  for the record */
69425  i64 iKey;         /* The integer ROWID or key for the record to be inserted */
69426  VdbeCursor *pC;   /* Cursor to table into which insert is written */
69427  int nZero;        /* Number of zero-bytes to append */
69428  int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
69429  const char *zDb;  /* database name - used by the update hook */
69430  const char *zTbl; /* Table name - used by the opdate hook */
69431  int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
69432#endif /* local variables moved into u.bi */
69433
69434  u.bi.pData = &aMem[pOp->p2];
69435  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69436  assert( memIsValid(u.bi.pData) );
69437  u.bi.pC = p->apCsr[pOp->p1];
69438  assert( u.bi.pC!=0 );
69439  assert( u.bi.pC->pCursor!=0 );
69440  assert( u.bi.pC->pseudoTableReg==0 );
69441  assert( u.bi.pC->isTable );
69442  REGISTER_TRACE(pOp->p2, u.bi.pData);
69443
69444  if( pOp->opcode==OP_Insert ){
69445    u.bi.pKey = &aMem[pOp->p3];
69446    assert( u.bi.pKey->flags & MEM_Int );
69447    assert( memIsValid(u.bi.pKey) );
69448    REGISTER_TRACE(pOp->p3, u.bi.pKey);
69449    u.bi.iKey = u.bi.pKey->u.i;
69450  }else{
69451    assert( pOp->opcode==OP_InsertInt );
69452    u.bi.iKey = pOp->p3;
69453  }
69454
69455  if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
69456  if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = u.bi.iKey;
69457  if( u.bi.pData->flags & MEM_Null ){
69458    u.bi.pData->z = 0;
69459    u.bi.pData->n = 0;
69460  }else{
69461    assert( u.bi.pData->flags & (MEM_Blob|MEM_Str) );
69462  }
69463  u.bi.seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bi.pC->seekResult : 0);
69464  if( u.bi.pData->flags & MEM_Zero ){
69465    u.bi.nZero = u.bi.pData->u.nZero;
69466  }else{
69467    u.bi.nZero = 0;
69468  }
69469  sqlite3BtreeSetCachedRowid(u.bi.pC->pCursor, 0);
69470  rc = sqlite3BtreeInsert(u.bi.pC->pCursor, 0, u.bi.iKey,
69471                          u.bi.pData->z, u.bi.pData->n, u.bi.nZero,
69472                          pOp->p5 & OPFLAG_APPEND, u.bi.seekResult
69473  );
69474  u.bi.pC->rowidIsValid = 0;
69475  u.bi.pC->deferredMoveto = 0;
69476  u.bi.pC->cacheStatus = CACHE_STALE;
69477
69478  /* Invoke the update-hook if required. */
69479  if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
69480    u.bi.zDb = db->aDb[u.bi.pC->iDb].zName;
69481    u.bi.zTbl = pOp->p4.z;
69482    u.bi.op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
69483    assert( u.bi.pC->isTable );
69484    db->xUpdateCallback(db->pUpdateArg, u.bi.op, u.bi.zDb, u.bi.zTbl, u.bi.iKey);
69485    assert( u.bi.pC->iDb>=0 );
69486  }
69487  break;
69488}
69489
69490/* Opcode: Delete P1 P2 * P4 *
69491**
69492** Delete the record at which the P1 cursor is currently pointing.
69493**
69494** The cursor will be left pointing at either the next or the previous
69495** record in the table. If it is left pointing at the next record, then
69496** the next Next instruction will be a no-op.  Hence it is OK to delete
69497** a record from within an Next loop.
69498**
69499** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
69500** incremented (otherwise not).
69501**
69502** P1 must not be pseudo-table.  It has to be a real table with
69503** multiple rows.
69504**
69505** If P4 is not NULL, then it is the name of the table that P1 is
69506** pointing to.  The update hook will be invoked, if it exists.
69507** If P4 is not NULL then the P1 cursor must have been positioned
69508** using OP_NotFound prior to invoking this opcode.
69509*/
69510case OP_Delete: {
69511#if 0  /* local variables moved into u.bj */
69512  i64 iKey;
69513  VdbeCursor *pC;
69514#endif /* local variables moved into u.bj */
69515
69516  u.bj.iKey = 0;
69517  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69518  u.bj.pC = p->apCsr[pOp->p1];
69519  assert( u.bj.pC!=0 );
69520  assert( u.bj.pC->pCursor!=0 );  /* Only valid for real tables, no pseudotables */
69521
69522  /* If the update-hook will be invoked, set u.bj.iKey to the rowid of the
69523  ** row being deleted.
69524  */
69525  if( db->xUpdateCallback && pOp->p4.z ){
69526    assert( u.bj.pC->isTable );
69527    assert( u.bj.pC->rowidIsValid );  /* lastRowid set by previous OP_NotFound */
69528    u.bj.iKey = u.bj.pC->lastRowid;
69529  }
69530
69531  /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or
69532  ** OP_Column on the same table without any intervening operations that
69533  ** might move or invalidate the cursor.  Hence cursor u.bj.pC is always pointing
69534  ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation
69535  ** below is always a no-op and cannot fail.  We will run it anyhow, though,
69536  ** to guard against future changes to the code generator.
69537  **/
69538  assert( u.bj.pC->deferredMoveto==0 );
69539  rc = sqlite3VdbeCursorMoveto(u.bj.pC);
69540  if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
69541
69542  sqlite3BtreeSetCachedRowid(u.bj.pC->pCursor, 0);
69543  rc = sqlite3BtreeDelete(u.bj.pC->pCursor);
69544  u.bj.pC->cacheStatus = CACHE_STALE;
69545
69546  /* Invoke the update-hook if required. */
69547  if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
69548    const char *zDb = db->aDb[u.bj.pC->iDb].zName;
69549    const char *zTbl = pOp->p4.z;
69550    db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, u.bj.iKey);
69551    assert( u.bj.pC->iDb>=0 );
69552  }
69553  if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
69554  break;
69555}
69556/* Opcode: ResetCount * * * * *
69557**
69558** The value of the change counter is copied to the database handle
69559** change counter (returned by subsequent calls to sqlite3_changes()).
69560** Then the VMs internal change counter resets to 0.
69561** This is used by trigger programs.
69562*/
69563case OP_ResetCount: {
69564  sqlite3VdbeSetChanges(db, p->nChange);
69565  p->nChange = 0;
69566  break;
69567}
69568
69569/* Opcode: SorterCompare P1 P2 P3
69570**
69571** P1 is a sorter cursor. This instruction compares the record blob in
69572** register P3 with the entry that the sorter cursor currently points to.
69573** If, excluding the rowid fields at the end, the two records are a match,
69574** fall through to the next instruction. Otherwise, jump to instruction P2.
69575*/
69576case OP_SorterCompare: {
69577#if 0  /* local variables moved into u.bk */
69578  VdbeCursor *pC;
69579  int res;
69580#endif /* local variables moved into u.bk */
69581
69582  u.bk.pC = p->apCsr[pOp->p1];
69583  assert( isSorter(u.bk.pC) );
69584  pIn3 = &aMem[pOp->p3];
69585  rc = sqlite3VdbeSorterCompare(u.bk.pC, pIn3, &u.bk.res);
69586  if( u.bk.res ){
69587    pc = pOp->p2-1;
69588  }
69589  break;
69590};
69591
69592/* Opcode: SorterData P1 P2 * * *
69593**
69594** Write into register P2 the current sorter data for sorter cursor P1.
69595*/
69596case OP_SorterData: {
69597#if 0  /* local variables moved into u.bl */
69598  VdbeCursor *pC;
69599#endif /* local variables moved into u.bl */
69600
69601  pOut = &aMem[pOp->p2];
69602  u.bl.pC = p->apCsr[pOp->p1];
69603  assert( u.bl.pC->isSorter );
69604  rc = sqlite3VdbeSorterRowkey(u.bl.pC, pOut);
69605  break;
69606}
69607
69608/* Opcode: RowData P1 P2 * * *
69609**
69610** Write into register P2 the complete row data for cursor P1.
69611** There is no interpretation of the data.
69612** It is just copied onto the P2 register exactly as
69613** it is found in the database file.
69614**
69615** If the P1 cursor must be pointing to a valid row (not a NULL row)
69616** of a real table, not a pseudo-table.
69617*/
69618/* Opcode: RowKey P1 P2 * * *
69619**
69620** Write into register P2 the complete row key for cursor P1.
69621** There is no interpretation of the data.
69622** The key is copied onto the P3 register exactly as
69623** it is found in the database file.
69624**
69625** If the P1 cursor must be pointing to a valid row (not a NULL row)
69626** of a real table, not a pseudo-table.
69627*/
69628case OP_RowKey:
69629case OP_RowData: {
69630#if 0  /* local variables moved into u.bm */
69631  VdbeCursor *pC;
69632  BtCursor *pCrsr;
69633  u32 n;
69634  i64 n64;
69635#endif /* local variables moved into u.bm */
69636
69637  pOut = &aMem[pOp->p2];
69638  memAboutToChange(p, pOut);
69639
69640  /* Note that RowKey and RowData are really exactly the same instruction */
69641  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69642  u.bm.pC = p->apCsr[pOp->p1];
69643  assert( u.bm.pC->isSorter==0 );
69644  assert( u.bm.pC->isTable || pOp->opcode!=OP_RowData );
69645  assert( u.bm.pC->isIndex || pOp->opcode==OP_RowData );
69646  assert( u.bm.pC!=0 );
69647  assert( u.bm.pC->nullRow==0 );
69648  assert( u.bm.pC->pseudoTableReg==0 );
69649  assert( u.bm.pC->pCursor!=0 );
69650  u.bm.pCrsr = u.bm.pC->pCursor;
69651  assert( sqlite3BtreeCursorIsValid(u.bm.pCrsr) );
69652
69653  /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
69654  ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
69655  ** the cursor.  Hence the following sqlite3VdbeCursorMoveto() call is always
69656  ** a no-op and can never fail.  But we leave it in place as a safety.
69657  */
69658  assert( u.bm.pC->deferredMoveto==0 );
69659  rc = sqlite3VdbeCursorMoveto(u.bm.pC);
69660  if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
69661
69662  if( u.bm.pC->isIndex ){
69663    assert( !u.bm.pC->isTable );
69664    VVA_ONLY(rc =) sqlite3BtreeKeySize(u.bm.pCrsr, &u.bm.n64);
69665    assert( rc==SQLITE_OK );    /* True because of CursorMoveto() call above */
69666    if( u.bm.n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
69667      goto too_big;
69668    }
69669    u.bm.n = (u32)u.bm.n64;
69670  }else{
69671    VVA_ONLY(rc =) sqlite3BtreeDataSize(u.bm.pCrsr, &u.bm.n);
69672    assert( rc==SQLITE_OK );    /* DataSize() cannot fail */
69673    if( u.bm.n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
69674      goto too_big;
69675    }
69676  }
69677  if( sqlite3VdbeMemGrow(pOut, u.bm.n, 0) ){
69678    goto no_mem;
69679  }
69680  pOut->n = u.bm.n;
69681  MemSetTypeFlag(pOut, MEM_Blob);
69682  if( u.bm.pC->isIndex ){
69683    rc = sqlite3BtreeKey(u.bm.pCrsr, 0, u.bm.n, pOut->z);
69684  }else{
69685    rc = sqlite3BtreeData(u.bm.pCrsr, 0, u.bm.n, pOut->z);
69686  }
69687  pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
69688  UPDATE_MAX_BLOBSIZE(pOut);
69689  break;
69690}
69691
69692/* Opcode: Rowid P1 P2 * * *
69693**
69694** Store in register P2 an integer which is the key of the table entry that
69695** P1 is currently point to.
69696**
69697** P1 can be either an ordinary table or a virtual table.  There used to
69698** be a separate OP_VRowid opcode for use with virtual tables, but this
69699** one opcode now works for both table types.
69700*/
69701case OP_Rowid: {                 /* out2-prerelease */
69702#if 0  /* local variables moved into u.bn */
69703  VdbeCursor *pC;
69704  i64 v;
69705  sqlite3_vtab *pVtab;
69706  const sqlite3_module *pModule;
69707#endif /* local variables moved into u.bn */
69708
69709  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69710  u.bn.pC = p->apCsr[pOp->p1];
69711  assert( u.bn.pC!=0 );
69712  assert( u.bn.pC->pseudoTableReg==0 || u.bn.pC->nullRow );
69713  if( u.bn.pC->nullRow ){
69714    pOut->flags = MEM_Null;
69715    break;
69716  }else if( u.bn.pC->deferredMoveto ){
69717    u.bn.v = u.bn.pC->movetoTarget;
69718#ifndef SQLITE_OMIT_VIRTUALTABLE
69719  }else if( u.bn.pC->pVtabCursor ){
69720    u.bn.pVtab = u.bn.pC->pVtabCursor->pVtab;
69721    u.bn.pModule = u.bn.pVtab->pModule;
69722    assert( u.bn.pModule->xRowid );
69723    rc = u.bn.pModule->xRowid(u.bn.pC->pVtabCursor, &u.bn.v);
69724    importVtabErrMsg(p, u.bn.pVtab);
69725#endif /* SQLITE_OMIT_VIRTUALTABLE */
69726  }else{
69727    assert( u.bn.pC->pCursor!=0 );
69728    rc = sqlite3VdbeCursorMoveto(u.bn.pC);
69729    if( rc ) goto abort_due_to_error;
69730    if( u.bn.pC->rowidIsValid ){
69731      u.bn.v = u.bn.pC->lastRowid;
69732    }else{
69733      rc = sqlite3BtreeKeySize(u.bn.pC->pCursor, &u.bn.v);
69734      assert( rc==SQLITE_OK );  /* Always so because of CursorMoveto() above */
69735    }
69736  }
69737  pOut->u.i = u.bn.v;
69738  break;
69739}
69740
69741/* Opcode: NullRow P1 * * * *
69742**
69743** Move the cursor P1 to a null row.  Any OP_Column operations
69744** that occur while the cursor is on the null row will always
69745** write a NULL.
69746*/
69747case OP_NullRow: {
69748#if 0  /* local variables moved into u.bo */
69749  VdbeCursor *pC;
69750#endif /* local variables moved into u.bo */
69751
69752  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69753  u.bo.pC = p->apCsr[pOp->p1];
69754  assert( u.bo.pC!=0 );
69755  u.bo.pC->nullRow = 1;
69756  u.bo.pC->rowidIsValid = 0;
69757  assert( u.bo.pC->pCursor || u.bo.pC->pVtabCursor );
69758  if( u.bo.pC->pCursor ){
69759    sqlite3BtreeClearCursor(u.bo.pC->pCursor);
69760  }
69761  break;
69762}
69763
69764/* Opcode: Last P1 P2 * * *
69765**
69766** The next use of the Rowid or Column or Next instruction for P1
69767** will refer to the last entry in the database table or index.
69768** If the table or index is empty and P2>0, then jump immediately to P2.
69769** If P2 is 0 or if the table or index is not empty, fall through
69770** to the following instruction.
69771*/
69772case OP_Last: {        /* jump */
69773#if 0  /* local variables moved into u.bp */
69774  VdbeCursor *pC;
69775  BtCursor *pCrsr;
69776  int res;
69777#endif /* local variables moved into u.bp */
69778
69779  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69780  u.bp.pC = p->apCsr[pOp->p1];
69781  assert( u.bp.pC!=0 );
69782  u.bp.pCrsr = u.bp.pC->pCursor;
69783  u.bp.res = 0;
69784  if( ALWAYS(u.bp.pCrsr!=0) ){
69785    rc = sqlite3BtreeLast(u.bp.pCrsr, &u.bp.res);
69786  }
69787  u.bp.pC->nullRow = (u8)u.bp.res;
69788  u.bp.pC->deferredMoveto = 0;
69789  u.bp.pC->rowidIsValid = 0;
69790  u.bp.pC->cacheStatus = CACHE_STALE;
69791  if( pOp->p2>0 && u.bp.res ){
69792    pc = pOp->p2 - 1;
69793  }
69794  break;
69795}
69796
69797
69798/* Opcode: Sort P1 P2 * * *
69799**
69800** This opcode does exactly the same thing as OP_Rewind except that
69801** it increments an undocumented global variable used for testing.
69802**
69803** Sorting is accomplished by writing records into a sorting index,
69804** then rewinding that index and playing it back from beginning to
69805** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
69806** rewinding so that the global variable will be incremented and
69807** regression tests can determine whether or not the optimizer is
69808** correctly optimizing out sorts.
69809*/
69810case OP_SorterSort:    /* jump */
69811case OP_Sort: {        /* jump */
69812#ifdef SQLITE_TEST
69813  sqlite3_sort_count++;
69814  sqlite3_search_count--;
69815#endif
69816  p->aCounter[SQLITE_STMTSTATUS_SORT-1]++;
69817  /* Fall through into OP_Rewind */
69818}
69819/* Opcode: Rewind P1 P2 * * *
69820**
69821** The next use of the Rowid or Column or Next instruction for P1
69822** will refer to the first entry in the database table or index.
69823** If the table or index is empty and P2>0, then jump immediately to P2.
69824** If P2 is 0 or if the table or index is not empty, fall through
69825** to the following instruction.
69826*/
69827case OP_Rewind: {        /* jump */
69828#if 0  /* local variables moved into u.bq */
69829  VdbeCursor *pC;
69830  BtCursor *pCrsr;
69831  int res;
69832#endif /* local variables moved into u.bq */
69833
69834  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69835  u.bq.pC = p->apCsr[pOp->p1];
69836  assert( u.bq.pC!=0 );
69837  assert( u.bq.pC->isSorter==(pOp->opcode==OP_SorterSort) );
69838  u.bq.res = 1;
69839  if( isSorter(u.bq.pC) ){
69840    rc = sqlite3VdbeSorterRewind(db, u.bq.pC, &u.bq.res);
69841  }else{
69842    u.bq.pCrsr = u.bq.pC->pCursor;
69843    assert( u.bq.pCrsr );
69844    rc = sqlite3BtreeFirst(u.bq.pCrsr, &u.bq.res);
69845    u.bq.pC->atFirst = u.bq.res==0 ?1:0;
69846    u.bq.pC->deferredMoveto = 0;
69847    u.bq.pC->cacheStatus = CACHE_STALE;
69848    u.bq.pC->rowidIsValid = 0;
69849  }
69850  u.bq.pC->nullRow = (u8)u.bq.res;
69851  assert( pOp->p2>0 && pOp->p2<p->nOp );
69852  if( u.bq.res ){
69853    pc = pOp->p2 - 1;
69854  }
69855  break;
69856}
69857
69858/* Opcode: Next P1 P2 * P4 P5
69859**
69860** Advance cursor P1 so that it points to the next key/data pair in its
69861** table or index.  If there are no more key/value pairs then fall through
69862** to the following instruction.  But if the cursor advance was successful,
69863** jump immediately to P2.
69864**
69865** The P1 cursor must be for a real table, not a pseudo-table.
69866**
69867** P4 is always of type P4_ADVANCE. The function pointer points to
69868** sqlite3BtreeNext().
69869**
69870** If P5 is positive and the jump is taken, then event counter
69871** number P5-1 in the prepared statement is incremented.
69872**
69873** See also: Prev
69874*/
69875/* Opcode: Prev P1 P2 * * P5
69876**
69877** Back up cursor P1 so that it points to the previous key/data pair in its
69878** table or index.  If there is no previous key/value pairs then fall through
69879** to the following instruction.  But if the cursor backup was successful,
69880** jump immediately to P2.
69881**
69882** The P1 cursor must be for a real table, not a pseudo-table.
69883**
69884** P4 is always of type P4_ADVANCE. The function pointer points to
69885** sqlite3BtreePrevious().
69886**
69887** If P5 is positive and the jump is taken, then event counter
69888** number P5-1 in the prepared statement is incremented.
69889*/
69890case OP_SorterNext:    /* jump */
69891case OP_Prev:          /* jump */
69892case OP_Next: {        /* jump */
69893#if 0  /* local variables moved into u.br */
69894  VdbeCursor *pC;
69895  int res;
69896#endif /* local variables moved into u.br */
69897
69898  CHECK_FOR_INTERRUPT;
69899  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69900  assert( pOp->p5<=ArraySize(p->aCounter) );
69901  u.br.pC = p->apCsr[pOp->p1];
69902  if( u.br.pC==0 ){
69903    break;  /* See ticket #2273 */
69904  }
69905  assert( u.br.pC->isSorter==(pOp->opcode==OP_SorterNext) );
69906  if( isSorter(u.br.pC) ){
69907    assert( pOp->opcode==OP_SorterNext );
69908    rc = sqlite3VdbeSorterNext(db, u.br.pC, &u.br.res);
69909  }else{
69910    u.br.res = 1;
69911    assert( u.br.pC->deferredMoveto==0 );
69912    assert( u.br.pC->pCursor );
69913    assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
69914    assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
69915    rc = pOp->p4.xAdvance(u.br.pC->pCursor, &u.br.res);
69916  }
69917  u.br.pC->nullRow = (u8)u.br.res;
69918  u.br.pC->cacheStatus = CACHE_STALE;
69919  if( u.br.res==0 ){
69920    pc = pOp->p2 - 1;
69921    if( pOp->p5 ) p->aCounter[pOp->p5-1]++;
69922#ifdef SQLITE_TEST
69923    sqlite3_search_count++;
69924#endif
69925  }
69926  u.br.pC->rowidIsValid = 0;
69927  break;
69928}
69929
69930/* Opcode: IdxInsert P1 P2 P3 * P5
69931**
69932** Register P2 holds an SQL index key made using the
69933** MakeRecord instructions.  This opcode writes that key
69934** into the index P1.  Data for the entry is nil.
69935**
69936** P3 is a flag that provides a hint to the b-tree layer that this
69937** insert is likely to be an append.
69938**
69939** This instruction only works for indices.  The equivalent instruction
69940** for tables is OP_Insert.
69941*/
69942case OP_SorterInsert:       /* in2 */
69943case OP_IdxInsert: {        /* in2 */
69944#if 0  /* local variables moved into u.bs */
69945  VdbeCursor *pC;
69946  BtCursor *pCrsr;
69947  int nKey;
69948  const char *zKey;
69949#endif /* local variables moved into u.bs */
69950
69951  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69952  u.bs.pC = p->apCsr[pOp->p1];
69953  assert( u.bs.pC!=0 );
69954  assert( u.bs.pC->isSorter==(pOp->opcode==OP_SorterInsert) );
69955  pIn2 = &aMem[pOp->p2];
69956  assert( pIn2->flags & MEM_Blob );
69957  u.bs.pCrsr = u.bs.pC->pCursor;
69958  if( ALWAYS(u.bs.pCrsr!=0) ){
69959    assert( u.bs.pC->isTable==0 );
69960    rc = ExpandBlob(pIn2);
69961    if( rc==SQLITE_OK ){
69962      if( isSorter(u.bs.pC) ){
69963        rc = sqlite3VdbeSorterWrite(db, u.bs.pC, pIn2);
69964      }else{
69965        u.bs.nKey = pIn2->n;
69966        u.bs.zKey = pIn2->z;
69967        rc = sqlite3BtreeInsert(u.bs.pCrsr, u.bs.zKey, u.bs.nKey, "", 0, 0, pOp->p3,
69968            ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bs.pC->seekResult : 0)
69969            );
69970        assert( u.bs.pC->deferredMoveto==0 );
69971        u.bs.pC->cacheStatus = CACHE_STALE;
69972      }
69973    }
69974  }
69975  break;
69976}
69977
69978/* Opcode: IdxDelete P1 P2 P3 * *
69979**
69980** The content of P3 registers starting at register P2 form
69981** an unpacked index key. This opcode removes that entry from the
69982** index opened by cursor P1.
69983*/
69984case OP_IdxDelete: {
69985#if 0  /* local variables moved into u.bt */
69986  VdbeCursor *pC;
69987  BtCursor *pCrsr;
69988  int res;
69989  UnpackedRecord r;
69990#endif /* local variables moved into u.bt */
69991
69992  assert( pOp->p3>0 );
69993  assert( pOp->p2>0 && pOp->p2+pOp->p3<=p->nMem+1 );
69994  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69995  u.bt.pC = p->apCsr[pOp->p1];
69996  assert( u.bt.pC!=0 );
69997  u.bt.pCrsr = u.bt.pC->pCursor;
69998  if( ALWAYS(u.bt.pCrsr!=0) ){
69999    u.bt.r.pKeyInfo = u.bt.pC->pKeyInfo;
70000    u.bt.r.nField = (u16)pOp->p3;
70001    u.bt.r.flags = 0;
70002    u.bt.r.aMem = &aMem[pOp->p2];
70003#ifdef SQLITE_DEBUG
70004    { int i; for(i=0; i<u.bt.r.nField; i++) assert( memIsValid(&u.bt.r.aMem[i]) ); }
70005#endif
70006    rc = sqlite3BtreeMovetoUnpacked(u.bt.pCrsr, &u.bt.r, 0, 0, &u.bt.res);
70007    if( rc==SQLITE_OK && u.bt.res==0 ){
70008      rc = sqlite3BtreeDelete(u.bt.pCrsr);
70009    }
70010    assert( u.bt.pC->deferredMoveto==0 );
70011    u.bt.pC->cacheStatus = CACHE_STALE;
70012  }
70013  break;
70014}
70015
70016/* Opcode: IdxRowid P1 P2 * * *
70017**
70018** Write into register P2 an integer which is the last entry in the record at
70019** the end of the index key pointed to by cursor P1.  This integer should be
70020** the rowid of the table entry to which this index entry points.
70021**
70022** See also: Rowid, MakeRecord.
70023*/
70024case OP_IdxRowid: {              /* out2-prerelease */
70025#if 0  /* local variables moved into u.bu */
70026  BtCursor *pCrsr;
70027  VdbeCursor *pC;
70028  i64 rowid;
70029#endif /* local variables moved into u.bu */
70030
70031  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
70032  u.bu.pC = p->apCsr[pOp->p1];
70033  assert( u.bu.pC!=0 );
70034  u.bu.pCrsr = u.bu.pC->pCursor;
70035  pOut->flags = MEM_Null;
70036  if( ALWAYS(u.bu.pCrsr!=0) ){
70037    rc = sqlite3VdbeCursorMoveto(u.bu.pC);
70038    if( NEVER(rc) ) goto abort_due_to_error;
70039    assert( u.bu.pC->deferredMoveto==0 );
70040    assert( u.bu.pC->isTable==0 );
70041    if( !u.bu.pC->nullRow ){
70042      rc = sqlite3VdbeIdxRowid(db, u.bu.pCrsr, &u.bu.rowid);
70043      if( rc!=SQLITE_OK ){
70044        goto abort_due_to_error;
70045      }
70046      pOut->u.i = u.bu.rowid;
70047      pOut->flags = MEM_Int;
70048    }
70049  }
70050  break;
70051}
70052
70053/* Opcode: IdxGE P1 P2 P3 P4 P5
70054**
70055** The P4 register values beginning with P3 form an unpacked index
70056** key that omits the ROWID.  Compare this key value against the index
70057** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
70058**
70059** If the P1 index entry is greater than or equal to the key value
70060** then jump to P2.  Otherwise fall through to the next instruction.
70061**
70062** If P5 is non-zero then the key value is increased by an epsilon
70063** prior to the comparison.  This make the opcode work like IdxGT except
70064** that if the key from register P3 is a prefix of the key in the cursor,
70065** the result is false whereas it would be true with IdxGT.
70066*/
70067/* Opcode: IdxLT P1 P2 P3 P4 P5
70068**
70069** The P4 register values beginning with P3 form an unpacked index
70070** key that omits the ROWID.  Compare this key value against the index
70071** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
70072**
70073** If the P1 index entry is less than the key value then jump to P2.
70074** Otherwise fall through to the next instruction.
70075**
70076** If P5 is non-zero then the key value is increased by an epsilon prior
70077** to the comparison.  This makes the opcode work like IdxLE.
70078*/
70079case OP_IdxLT:          /* jump */
70080case OP_IdxGE: {        /* jump */
70081#if 0  /* local variables moved into u.bv */
70082  VdbeCursor *pC;
70083  int res;
70084  UnpackedRecord r;
70085#endif /* local variables moved into u.bv */
70086
70087  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
70088  u.bv.pC = p->apCsr[pOp->p1];
70089  assert( u.bv.pC!=0 );
70090  assert( u.bv.pC->isOrdered );
70091  if( ALWAYS(u.bv.pC->pCursor!=0) ){
70092    assert( u.bv.pC->deferredMoveto==0 );
70093    assert( pOp->p5==0 || pOp->p5==1 );
70094    assert( pOp->p4type==P4_INT32 );
70095    u.bv.r.pKeyInfo = u.bv.pC->pKeyInfo;
70096    u.bv.r.nField = (u16)pOp->p4.i;
70097    if( pOp->p5 ){
70098      u.bv.r.flags = UNPACKED_INCRKEY | UNPACKED_PREFIX_MATCH;
70099    }else{
70100      u.bv.r.flags = UNPACKED_PREFIX_MATCH;
70101    }
70102    u.bv.r.aMem = &aMem[pOp->p3];
70103#ifdef SQLITE_DEBUG
70104    { int i; for(i=0; i<u.bv.r.nField; i++) assert( memIsValid(&u.bv.r.aMem[i]) ); }
70105#endif
70106    rc = sqlite3VdbeIdxKeyCompare(u.bv.pC, &u.bv.r, &u.bv.res);
70107    if( pOp->opcode==OP_IdxLT ){
70108      u.bv.res = -u.bv.res;
70109    }else{
70110      assert( pOp->opcode==OP_IdxGE );
70111      u.bv.res++;
70112    }
70113    if( u.bv.res>0 ){
70114      pc = pOp->p2 - 1 ;
70115    }
70116  }
70117  break;
70118}
70119
70120/* Opcode: Destroy P1 P2 P3 * *
70121**
70122** Delete an entire database table or index whose root page in the database
70123** file is given by P1.
70124**
70125** The table being destroyed is in the main database file if P3==0.  If
70126** P3==1 then the table to be clear is in the auxiliary database file
70127** that is used to store tables create using CREATE TEMPORARY TABLE.
70128**
70129** If AUTOVACUUM is enabled then it is possible that another root page
70130** might be moved into the newly deleted root page in order to keep all
70131** root pages contiguous at the beginning of the database.  The former
70132** value of the root page that moved - its value before the move occurred -
70133** is stored in register P2.  If no page
70134** movement was required (because the table being dropped was already
70135** the last one in the database) then a zero is stored in register P2.
70136** If AUTOVACUUM is disabled then a zero is stored in register P2.
70137**
70138** See also: Clear
70139*/
70140case OP_Destroy: {     /* out2-prerelease */
70141#if 0  /* local variables moved into u.bw */
70142  int iMoved;
70143  int iCnt;
70144  Vdbe *pVdbe;
70145  int iDb;
70146#endif /* local variables moved into u.bw */
70147
70148#ifndef SQLITE_OMIT_VIRTUALTABLE
70149  u.bw.iCnt = 0;
70150  for(u.bw.pVdbe=db->pVdbe; u.bw.pVdbe; u.bw.pVdbe = u.bw.pVdbe->pNext){
70151    if( u.bw.pVdbe->magic==VDBE_MAGIC_RUN && u.bw.pVdbe->inVtabMethod<2 && u.bw.pVdbe->pc>=0 ){
70152      u.bw.iCnt++;
70153    }
70154  }
70155#else
70156  u.bw.iCnt = db->activeVdbeCnt;
70157#endif
70158  pOut->flags = MEM_Null;
70159  if( u.bw.iCnt>1 ){
70160    rc = SQLITE_LOCKED;
70161    p->errorAction = OE_Abort;
70162  }else{
70163    u.bw.iDb = pOp->p3;
70164    assert( u.bw.iCnt==1 );
70165    assert( (p->btreeMask & (((yDbMask)1)<<u.bw.iDb))!=0 );
70166    rc = sqlite3BtreeDropTable(db->aDb[u.bw.iDb].pBt, pOp->p1, &u.bw.iMoved);
70167    pOut->flags = MEM_Int;
70168    pOut->u.i = u.bw.iMoved;
70169#ifndef SQLITE_OMIT_AUTOVACUUM
70170    if( rc==SQLITE_OK && u.bw.iMoved!=0 ){
70171      sqlite3RootPageMoved(db, u.bw.iDb, u.bw.iMoved, pOp->p1);
70172      /* All OP_Destroy operations occur on the same btree */
70173      assert( resetSchemaOnFault==0 || resetSchemaOnFault==u.bw.iDb+1 );
70174      resetSchemaOnFault = u.bw.iDb+1;
70175    }
70176#endif
70177  }
70178  break;
70179}
70180
70181/* Opcode: Clear P1 P2 P3
70182**
70183** Delete all contents of the database table or index whose root page
70184** in the database file is given by P1.  But, unlike Destroy, do not
70185** remove the table or index from the database file.
70186**
70187** The table being clear is in the main database file if P2==0.  If
70188** P2==1 then the table to be clear is in the auxiliary database file
70189** that is used to store tables create using CREATE TEMPORARY TABLE.
70190**
70191** If the P3 value is non-zero, then the table referred to must be an
70192** intkey table (an SQL table, not an index). In this case the row change
70193** count is incremented by the number of rows in the table being cleared.
70194** If P3 is greater than zero, then the value stored in register P3 is
70195** also incremented by the number of rows in the table being cleared.
70196**
70197** See also: Destroy
70198*/
70199case OP_Clear: {
70200#if 0  /* local variables moved into u.bx */
70201  int nChange;
70202#endif /* local variables moved into u.bx */
70203
70204  u.bx.nChange = 0;
70205  assert( (p->btreeMask & (((yDbMask)1)<<pOp->p2))!=0 );
70206  rc = sqlite3BtreeClearTable(
70207      db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &u.bx.nChange : 0)
70208  );
70209  if( pOp->p3 ){
70210    p->nChange += u.bx.nChange;
70211    if( pOp->p3>0 ){
70212      assert( memIsValid(&aMem[pOp->p3]) );
70213      memAboutToChange(p, &aMem[pOp->p3]);
70214      aMem[pOp->p3].u.i += u.bx.nChange;
70215    }
70216  }
70217  break;
70218}
70219
70220/* Opcode: CreateTable P1 P2 * * *
70221**
70222** Allocate a new table in the main database file if P1==0 or in the
70223** auxiliary database file if P1==1 or in an attached database if
70224** P1>1.  Write the root page number of the new table into
70225** register P2
70226**
70227** The difference between a table and an index is this:  A table must
70228** have a 4-byte integer key and can have arbitrary data.  An index
70229** has an arbitrary key but no data.
70230**
70231** See also: CreateIndex
70232*/
70233/* Opcode: CreateIndex P1 P2 * * *
70234**
70235** Allocate a new index in the main database file if P1==0 or in the
70236** auxiliary database file if P1==1 or in an attached database if
70237** P1>1.  Write the root page number of the new table into
70238** register P2.
70239**
70240** See documentation on OP_CreateTable for additional information.
70241*/
70242case OP_CreateIndex:            /* out2-prerelease */
70243case OP_CreateTable: {          /* out2-prerelease */
70244#if 0  /* local variables moved into u.by */
70245  int pgno;
70246  int flags;
70247  Db *pDb;
70248#endif /* local variables moved into u.by */
70249
70250  u.by.pgno = 0;
70251  assert( pOp->p1>=0 && pOp->p1<db->nDb );
70252  assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
70253  u.by.pDb = &db->aDb[pOp->p1];
70254  assert( u.by.pDb->pBt!=0 );
70255  if( pOp->opcode==OP_CreateTable ){
70256    /* u.by.flags = BTREE_INTKEY; */
70257    u.by.flags = BTREE_INTKEY;
70258  }else{
70259    u.by.flags = BTREE_BLOBKEY;
70260  }
70261  rc = sqlite3BtreeCreateTable(u.by.pDb->pBt, &u.by.pgno, u.by.flags);
70262  pOut->u.i = u.by.pgno;
70263  break;
70264}
70265
70266/* Opcode: ParseSchema P1 * * P4 *
70267**
70268** Read and parse all entries from the SQLITE_MASTER table of database P1
70269** that match the WHERE clause P4.
70270**
70271** This opcode invokes the parser to create a new virtual machine,
70272** then runs the new virtual machine.  It is thus a re-entrant opcode.
70273*/
70274case OP_ParseSchema: {
70275#if 0  /* local variables moved into u.bz */
70276  int iDb;
70277  const char *zMaster;
70278  char *zSql;
70279  InitData initData;
70280#endif /* local variables moved into u.bz */
70281
70282  /* Any prepared statement that invokes this opcode will hold mutexes
70283  ** on every btree.  This is a prerequisite for invoking
70284  ** sqlite3InitCallback().
70285  */
70286#ifdef SQLITE_DEBUG
70287  for(u.bz.iDb=0; u.bz.iDb<db->nDb; u.bz.iDb++){
70288    assert( u.bz.iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[u.bz.iDb].pBt) );
70289  }
70290#endif
70291
70292  u.bz.iDb = pOp->p1;
70293  assert( u.bz.iDb>=0 && u.bz.iDb<db->nDb );
70294  assert( DbHasProperty(db, u.bz.iDb, DB_SchemaLoaded) );
70295  /* Used to be a conditional */ {
70296    u.bz.zMaster = SCHEMA_TABLE(u.bz.iDb);
70297    u.bz.initData.db = db;
70298    u.bz.initData.iDb = pOp->p1;
70299    u.bz.initData.pzErrMsg = &p->zErrMsg;
70300    u.bz.zSql = sqlite3MPrintf(db,
70301       "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
70302       db->aDb[u.bz.iDb].zName, u.bz.zMaster, pOp->p4.z);
70303    if( u.bz.zSql==0 ){
70304      rc = SQLITE_NOMEM;
70305    }else{
70306      assert( db->init.busy==0 );
70307      db->init.busy = 1;
70308      u.bz.initData.rc = SQLITE_OK;
70309      assert( !db->mallocFailed );
70310      rc = sqlite3_exec(db, u.bz.zSql, sqlite3InitCallback, &u.bz.initData, 0);
70311      if( rc==SQLITE_OK ) rc = u.bz.initData.rc;
70312      sqlite3DbFree(db, u.bz.zSql);
70313      db->init.busy = 0;
70314    }
70315  }
70316  if( rc ) sqlite3ResetAllSchemasOfConnection(db);
70317  if( rc==SQLITE_NOMEM ){
70318    goto no_mem;
70319  }
70320  break;
70321}
70322
70323#if !defined(SQLITE_OMIT_ANALYZE)
70324/* Opcode: LoadAnalysis P1 * * * *
70325**
70326** Read the sqlite_stat1 table for database P1 and load the content
70327** of that table into the internal index hash table.  This will cause
70328** the analysis to be used when preparing all subsequent queries.
70329*/
70330case OP_LoadAnalysis: {
70331  assert( pOp->p1>=0 && pOp->p1<db->nDb );
70332  rc = sqlite3AnalysisLoad(db, pOp->p1);
70333  break;
70334}
70335#endif /* !defined(SQLITE_OMIT_ANALYZE) */
70336
70337/* Opcode: DropTable P1 * * P4 *
70338**
70339** Remove the internal (in-memory) data structures that describe
70340** the table named P4 in database P1.  This is called after a table
70341** is dropped in order to keep the internal representation of the
70342** schema consistent with what is on disk.
70343*/
70344case OP_DropTable: {
70345  sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
70346  break;
70347}
70348
70349/* Opcode: DropIndex P1 * * P4 *
70350**
70351** Remove the internal (in-memory) data structures that describe
70352** the index named P4 in database P1.  This is called after an index
70353** is dropped in order to keep the internal representation of the
70354** schema consistent with what is on disk.
70355*/
70356case OP_DropIndex: {
70357  sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
70358  break;
70359}
70360
70361/* Opcode: DropTrigger P1 * * P4 *
70362**
70363** Remove the internal (in-memory) data structures that describe
70364** the trigger named P4 in database P1.  This is called after a trigger
70365** is dropped in order to keep the internal representation of the
70366** schema consistent with what is on disk.
70367*/
70368case OP_DropTrigger: {
70369  sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
70370  break;
70371}
70372
70373
70374#ifndef SQLITE_OMIT_INTEGRITY_CHECK
70375/* Opcode: IntegrityCk P1 P2 P3 * P5
70376**
70377** Do an analysis of the currently open database.  Store in
70378** register P1 the text of an error message describing any problems.
70379** If no problems are found, store a NULL in register P1.
70380**
70381** The register P3 contains the maximum number of allowed errors.
70382** At most reg(P3) errors will be reported.
70383** In other words, the analysis stops as soon as reg(P1) errors are
70384** seen.  Reg(P1) is updated with the number of errors remaining.
70385**
70386** The root page numbers of all tables in the database are integer
70387** stored in reg(P1), reg(P1+1), reg(P1+2), ....  There are P2 tables
70388** total.
70389**
70390** If P5 is not zero, the check is done on the auxiliary database
70391** file, not the main database file.
70392**
70393** This opcode is used to implement the integrity_check pragma.
70394*/
70395case OP_IntegrityCk: {
70396#if 0  /* local variables moved into u.ca */
70397  int nRoot;      /* Number of tables to check.  (Number of root pages.) */
70398  int *aRoot;     /* Array of rootpage numbers for tables to be checked */
70399  int j;          /* Loop counter */
70400  int nErr;       /* Number of errors reported */
70401  char *z;        /* Text of the error report */
70402  Mem *pnErr;     /* Register keeping track of errors remaining */
70403#endif /* local variables moved into u.ca */
70404
70405  u.ca.nRoot = pOp->p2;
70406  assert( u.ca.nRoot>0 );
70407  u.ca.aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(u.ca.nRoot+1) );
70408  if( u.ca.aRoot==0 ) goto no_mem;
70409  assert( pOp->p3>0 && pOp->p3<=p->nMem );
70410  u.ca.pnErr = &aMem[pOp->p3];
70411  assert( (u.ca.pnErr->flags & MEM_Int)!=0 );
70412  assert( (u.ca.pnErr->flags & (MEM_Str|MEM_Blob))==0 );
70413  pIn1 = &aMem[pOp->p1];
70414  for(u.ca.j=0; u.ca.j<u.ca.nRoot; u.ca.j++){
70415    u.ca.aRoot[u.ca.j] = (int)sqlite3VdbeIntValue(&pIn1[u.ca.j]);
70416  }
70417  u.ca.aRoot[u.ca.j] = 0;
70418  assert( pOp->p5<db->nDb );
70419  assert( (p->btreeMask & (((yDbMask)1)<<pOp->p5))!=0 );
70420  u.ca.z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, u.ca.aRoot, u.ca.nRoot,
70421                                 (int)u.ca.pnErr->u.i, &u.ca.nErr);
70422  sqlite3DbFree(db, u.ca.aRoot);
70423  u.ca.pnErr->u.i -= u.ca.nErr;
70424  sqlite3VdbeMemSetNull(pIn1);
70425  if( u.ca.nErr==0 ){
70426    assert( u.ca.z==0 );
70427  }else if( u.ca.z==0 ){
70428    goto no_mem;
70429  }else{
70430    sqlite3VdbeMemSetStr(pIn1, u.ca.z, -1, SQLITE_UTF8, sqlite3_free);
70431  }
70432  UPDATE_MAX_BLOBSIZE(pIn1);
70433  sqlite3VdbeChangeEncoding(pIn1, encoding);
70434  break;
70435}
70436#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
70437
70438/* Opcode: RowSetAdd P1 P2 * * *
70439**
70440** Insert the integer value held by register P2 into a boolean index
70441** held in register P1.
70442**
70443** An assertion fails if P2 is not an integer.
70444*/
70445case OP_RowSetAdd: {       /* in1, in2 */
70446  pIn1 = &aMem[pOp->p1];
70447  pIn2 = &aMem[pOp->p2];
70448  assert( (pIn2->flags & MEM_Int)!=0 );
70449  if( (pIn1->flags & MEM_RowSet)==0 ){
70450    sqlite3VdbeMemSetRowSet(pIn1);
70451    if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
70452  }
70453  sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
70454  break;
70455}
70456
70457/* Opcode: RowSetRead P1 P2 P3 * *
70458**
70459** Extract the smallest value from boolean index P1 and put that value into
70460** register P3.  Or, if boolean index P1 is initially empty, leave P3
70461** unchanged and jump to instruction P2.
70462*/
70463case OP_RowSetRead: {       /* jump, in1, out3 */
70464#if 0  /* local variables moved into u.cb */
70465  i64 val;
70466#endif /* local variables moved into u.cb */
70467  CHECK_FOR_INTERRUPT;
70468  pIn1 = &aMem[pOp->p1];
70469  if( (pIn1->flags & MEM_RowSet)==0
70470   || sqlite3RowSetNext(pIn1->u.pRowSet, &u.cb.val)==0
70471  ){
70472    /* The boolean index is empty */
70473    sqlite3VdbeMemSetNull(pIn1);
70474    pc = pOp->p2 - 1;
70475  }else{
70476    /* A value was pulled from the index */
70477    sqlite3VdbeMemSetInt64(&aMem[pOp->p3], u.cb.val);
70478  }
70479  break;
70480}
70481
70482/* Opcode: RowSetTest P1 P2 P3 P4
70483**
70484** Register P3 is assumed to hold a 64-bit integer value. If register P1
70485** contains a RowSet object and that RowSet object contains
70486** the value held in P3, jump to register P2. Otherwise, insert the
70487** integer in P3 into the RowSet and continue on to the
70488** next opcode.
70489**
70490** The RowSet object is optimized for the case where successive sets
70491** of integers, where each set contains no duplicates. Each set
70492** of values is identified by a unique P4 value. The first set
70493** must have P4==0, the final set P4=-1.  P4 must be either -1 or
70494** non-negative.  For non-negative values of P4 only the lower 4
70495** bits are significant.
70496**
70497** This allows optimizations: (a) when P4==0 there is no need to test
70498** the rowset object for P3, as it is guaranteed not to contain it,
70499** (b) when P4==-1 there is no need to insert the value, as it will
70500** never be tested for, and (c) when a value that is part of set X is
70501** inserted, there is no need to search to see if the same value was
70502** previously inserted as part of set X (only if it was previously
70503** inserted as part of some other set).
70504*/
70505case OP_RowSetTest: {                     /* jump, in1, in3 */
70506#if 0  /* local variables moved into u.cc */
70507  int iSet;
70508  int exists;
70509#endif /* local variables moved into u.cc */
70510
70511  pIn1 = &aMem[pOp->p1];
70512  pIn3 = &aMem[pOp->p3];
70513  u.cc.iSet = pOp->p4.i;
70514  assert( pIn3->flags&MEM_Int );
70515
70516  /* If there is anything other than a rowset object in memory cell P1,
70517  ** delete it now and initialize P1 with an empty rowset
70518  */
70519  if( (pIn1->flags & MEM_RowSet)==0 ){
70520    sqlite3VdbeMemSetRowSet(pIn1);
70521    if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
70522  }
70523
70524  assert( pOp->p4type==P4_INT32 );
70525  assert( u.cc.iSet==-1 || u.cc.iSet>=0 );
70526  if( u.cc.iSet ){
70527    u.cc.exists = sqlite3RowSetTest(pIn1->u.pRowSet,
70528                               (u8)(u.cc.iSet>=0 ? u.cc.iSet & 0xf : 0xff),
70529                               pIn3->u.i);
70530    if( u.cc.exists ){
70531      pc = pOp->p2 - 1;
70532      break;
70533    }
70534  }
70535  if( u.cc.iSet>=0 ){
70536    sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
70537  }
70538  break;
70539}
70540
70541
70542#ifndef SQLITE_OMIT_TRIGGER
70543
70544/* Opcode: Program P1 P2 P3 P4 *
70545**
70546** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
70547**
70548** P1 contains the address of the memory cell that contains the first memory
70549** cell in an array of values used as arguments to the sub-program. P2
70550** contains the address to jump to if the sub-program throws an IGNORE
70551** exception using the RAISE() function. Register P3 contains the address
70552** of a memory cell in this (the parent) VM that is used to allocate the
70553** memory required by the sub-vdbe at runtime.
70554**
70555** P4 is a pointer to the VM containing the trigger program.
70556*/
70557case OP_Program: {        /* jump */
70558#if 0  /* local variables moved into u.cd */
70559  int nMem;               /* Number of memory registers for sub-program */
70560  int nByte;              /* Bytes of runtime space required for sub-program */
70561  Mem *pRt;               /* Register to allocate runtime space */
70562  Mem *pMem;              /* Used to iterate through memory cells */
70563  Mem *pEnd;              /* Last memory cell in new array */
70564  VdbeFrame *pFrame;      /* New vdbe frame to execute in */
70565  SubProgram *pProgram;   /* Sub-program to execute */
70566  void *t;                /* Token identifying trigger */
70567#endif /* local variables moved into u.cd */
70568
70569  u.cd.pProgram = pOp->p4.pProgram;
70570  u.cd.pRt = &aMem[pOp->p3];
70571  assert( u.cd.pProgram->nOp>0 );
70572
70573  /* If the p5 flag is clear, then recursive invocation of triggers is
70574  ** disabled for backwards compatibility (p5 is set if this sub-program
70575  ** is really a trigger, not a foreign key action, and the flag set
70576  ** and cleared by the "PRAGMA recursive_triggers" command is clear).
70577  **
70578  ** It is recursive invocation of triggers, at the SQL level, that is
70579  ** disabled. In some cases a single trigger may generate more than one
70580  ** SubProgram (if the trigger may be executed with more than one different
70581  ** ON CONFLICT algorithm). SubProgram structures associated with a
70582  ** single trigger all have the same value for the SubProgram.token
70583  ** variable.  */
70584  if( pOp->p5 ){
70585    u.cd.t = u.cd.pProgram->token;
70586    for(u.cd.pFrame=p->pFrame; u.cd.pFrame && u.cd.pFrame->token!=u.cd.t; u.cd.pFrame=u.cd.pFrame->pParent);
70587    if( u.cd.pFrame ) break;
70588  }
70589
70590  if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
70591    rc = SQLITE_ERROR;
70592    sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
70593    break;
70594  }
70595
70596  /* Register u.cd.pRt is used to store the memory required to save the state
70597  ** of the current program, and the memory required at runtime to execute
70598  ** the trigger program. If this trigger has been fired before, then u.cd.pRt
70599  ** is already allocated. Otherwise, it must be initialized.  */
70600  if( (u.cd.pRt->flags&MEM_Frame)==0 ){
70601    /* SubProgram.nMem is set to the number of memory cells used by the
70602    ** program stored in SubProgram.aOp. As well as these, one memory
70603    ** cell is required for each cursor used by the program. Set local
70604    ** variable u.cd.nMem (and later, VdbeFrame.nChildMem) to this value.
70605    */
70606    u.cd.nMem = u.cd.pProgram->nMem + u.cd.pProgram->nCsr;
70607    u.cd.nByte = ROUND8(sizeof(VdbeFrame))
70608              + u.cd.nMem * sizeof(Mem)
70609              + u.cd.pProgram->nCsr * sizeof(VdbeCursor *)
70610              + u.cd.pProgram->nOnce * sizeof(u8);
70611    u.cd.pFrame = sqlite3DbMallocZero(db, u.cd.nByte);
70612    if( !u.cd.pFrame ){
70613      goto no_mem;
70614    }
70615    sqlite3VdbeMemRelease(u.cd.pRt);
70616    u.cd.pRt->flags = MEM_Frame;
70617    u.cd.pRt->u.pFrame = u.cd.pFrame;
70618
70619    u.cd.pFrame->v = p;
70620    u.cd.pFrame->nChildMem = u.cd.nMem;
70621    u.cd.pFrame->nChildCsr = u.cd.pProgram->nCsr;
70622    u.cd.pFrame->pc = pc;
70623    u.cd.pFrame->aMem = p->aMem;
70624    u.cd.pFrame->nMem = p->nMem;
70625    u.cd.pFrame->apCsr = p->apCsr;
70626    u.cd.pFrame->nCursor = p->nCursor;
70627    u.cd.pFrame->aOp = p->aOp;
70628    u.cd.pFrame->nOp = p->nOp;
70629    u.cd.pFrame->token = u.cd.pProgram->token;
70630    u.cd.pFrame->aOnceFlag = p->aOnceFlag;
70631    u.cd.pFrame->nOnceFlag = p->nOnceFlag;
70632
70633    u.cd.pEnd = &VdbeFrameMem(u.cd.pFrame)[u.cd.pFrame->nChildMem];
70634    for(u.cd.pMem=VdbeFrameMem(u.cd.pFrame); u.cd.pMem!=u.cd.pEnd; u.cd.pMem++){
70635      u.cd.pMem->flags = MEM_Invalid;
70636      u.cd.pMem->db = db;
70637    }
70638  }else{
70639    u.cd.pFrame = u.cd.pRt->u.pFrame;
70640    assert( u.cd.pProgram->nMem+u.cd.pProgram->nCsr==u.cd.pFrame->nChildMem );
70641    assert( u.cd.pProgram->nCsr==u.cd.pFrame->nChildCsr );
70642    assert( pc==u.cd.pFrame->pc );
70643  }
70644
70645  p->nFrame++;
70646  u.cd.pFrame->pParent = p->pFrame;
70647  u.cd.pFrame->lastRowid = lastRowid;
70648  u.cd.pFrame->nChange = p->nChange;
70649  p->nChange = 0;
70650  p->pFrame = u.cd.pFrame;
70651  p->aMem = aMem = &VdbeFrameMem(u.cd.pFrame)[-1];
70652  p->nMem = u.cd.pFrame->nChildMem;
70653  p->nCursor = (u16)u.cd.pFrame->nChildCsr;
70654  p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
70655  p->aOp = aOp = u.cd.pProgram->aOp;
70656  p->nOp = u.cd.pProgram->nOp;
70657  p->aOnceFlag = (u8 *)&p->apCsr[p->nCursor];
70658  p->nOnceFlag = u.cd.pProgram->nOnce;
70659  pc = -1;
70660  memset(p->aOnceFlag, 0, p->nOnceFlag);
70661
70662  break;
70663}
70664
70665/* Opcode: Param P1 P2 * * *
70666**
70667** This opcode is only ever present in sub-programs called via the
70668** OP_Program instruction. Copy a value currently stored in a memory
70669** cell of the calling (parent) frame to cell P2 in the current frames
70670** address space. This is used by trigger programs to access the new.*
70671** and old.* values.
70672**
70673** The address of the cell in the parent frame is determined by adding
70674** the value of the P1 argument to the value of the P1 argument to the
70675** calling OP_Program instruction.
70676*/
70677case OP_Param: {           /* out2-prerelease */
70678#if 0  /* local variables moved into u.ce */
70679  VdbeFrame *pFrame;
70680  Mem *pIn;
70681#endif /* local variables moved into u.ce */
70682  u.ce.pFrame = p->pFrame;
70683  u.ce.pIn = &u.ce.pFrame->aMem[pOp->p1 + u.ce.pFrame->aOp[u.ce.pFrame->pc].p1];
70684  sqlite3VdbeMemShallowCopy(pOut, u.ce.pIn, MEM_Ephem);
70685  break;
70686}
70687
70688#endif /* #ifndef SQLITE_OMIT_TRIGGER */
70689
70690#ifndef SQLITE_OMIT_FOREIGN_KEY
70691/* Opcode: FkCounter P1 P2 * * *
70692**
70693** Increment a "constraint counter" by P2 (P2 may be negative or positive).
70694** If P1 is non-zero, the database constraint counter is incremented
70695** (deferred foreign key constraints). Otherwise, if P1 is zero, the
70696** statement counter is incremented (immediate foreign key constraints).
70697*/
70698case OP_FkCounter: {
70699  if( pOp->p1 ){
70700    db->nDeferredCons += pOp->p2;
70701  }else{
70702    p->nFkConstraint += pOp->p2;
70703  }
70704  break;
70705}
70706
70707/* Opcode: FkIfZero P1 P2 * * *
70708**
70709** This opcode tests if a foreign key constraint-counter is currently zero.
70710** If so, jump to instruction P2. Otherwise, fall through to the next
70711** instruction.
70712**
70713** If P1 is non-zero, then the jump is taken if the database constraint-counter
70714** is zero (the one that counts deferred constraint violations). If P1 is
70715** zero, the jump is taken if the statement constraint-counter is zero
70716** (immediate foreign key constraint violations).
70717*/
70718case OP_FkIfZero: {         /* jump */
70719  if( pOp->p1 ){
70720    if( db->nDeferredCons==0 ) pc = pOp->p2-1;
70721  }else{
70722    if( p->nFkConstraint==0 ) pc = pOp->p2-1;
70723  }
70724  break;
70725}
70726#endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
70727
70728#ifndef SQLITE_OMIT_AUTOINCREMENT
70729/* Opcode: MemMax P1 P2 * * *
70730**
70731** P1 is a register in the root frame of this VM (the root frame is
70732** different from the current frame if this instruction is being executed
70733** within a sub-program). Set the value of register P1 to the maximum of
70734** its current value and the value in register P2.
70735**
70736** This instruction throws an error if the memory cell is not initially
70737** an integer.
70738*/
70739case OP_MemMax: {        /* in2 */
70740#if 0  /* local variables moved into u.cf */
70741  Mem *pIn1;
70742  VdbeFrame *pFrame;
70743#endif /* local variables moved into u.cf */
70744  if( p->pFrame ){
70745    for(u.cf.pFrame=p->pFrame; u.cf.pFrame->pParent; u.cf.pFrame=u.cf.pFrame->pParent);
70746    u.cf.pIn1 = &u.cf.pFrame->aMem[pOp->p1];
70747  }else{
70748    u.cf.pIn1 = &aMem[pOp->p1];
70749  }
70750  assert( memIsValid(u.cf.pIn1) );
70751  sqlite3VdbeMemIntegerify(u.cf.pIn1);
70752  pIn2 = &aMem[pOp->p2];
70753  sqlite3VdbeMemIntegerify(pIn2);
70754  if( u.cf.pIn1->u.i<pIn2->u.i){
70755    u.cf.pIn1->u.i = pIn2->u.i;
70756  }
70757  break;
70758}
70759#endif /* SQLITE_OMIT_AUTOINCREMENT */
70760
70761/* Opcode: IfPos P1 P2 * * *
70762**
70763** If the value of register P1 is 1 or greater, jump to P2.
70764**
70765** It is illegal to use this instruction on a register that does
70766** not contain an integer.  An assertion fault will result if you try.
70767*/
70768case OP_IfPos: {        /* jump, in1 */
70769  pIn1 = &aMem[pOp->p1];
70770  assert( pIn1->flags&MEM_Int );
70771  if( pIn1->u.i>0 ){
70772     pc = pOp->p2 - 1;
70773  }
70774  break;
70775}
70776
70777/* Opcode: IfNeg P1 P2 * * *
70778**
70779** If the value of register P1 is less than zero, jump to P2.
70780**
70781** It is illegal to use this instruction on a register that does
70782** not contain an integer.  An assertion fault will result if you try.
70783*/
70784case OP_IfNeg: {        /* jump, in1 */
70785  pIn1 = &aMem[pOp->p1];
70786  assert( pIn1->flags&MEM_Int );
70787  if( pIn1->u.i<0 ){
70788     pc = pOp->p2 - 1;
70789  }
70790  break;
70791}
70792
70793/* Opcode: IfZero P1 P2 P3 * *
70794**
70795** The register P1 must contain an integer.  Add literal P3 to the
70796** value in register P1.  If the result is exactly 0, jump to P2.
70797**
70798** It is illegal to use this instruction on a register that does
70799** not contain an integer.  An assertion fault will result if you try.
70800*/
70801case OP_IfZero: {        /* jump, in1 */
70802  pIn1 = &aMem[pOp->p1];
70803  assert( pIn1->flags&MEM_Int );
70804  pIn1->u.i += pOp->p3;
70805  if( pIn1->u.i==0 ){
70806     pc = pOp->p2 - 1;
70807  }
70808  break;
70809}
70810
70811/* Opcode: AggStep * P2 P3 P4 P5
70812**
70813** Execute the step function for an aggregate.  The
70814** function has P5 arguments.   P4 is a pointer to the FuncDef
70815** structure that specifies the function.  Use register
70816** P3 as the accumulator.
70817**
70818** The P5 arguments are taken from register P2 and its
70819** successors.
70820*/
70821case OP_AggStep: {
70822#if 0  /* local variables moved into u.cg */
70823  int n;
70824  int i;
70825  Mem *pMem;
70826  Mem *pRec;
70827  sqlite3_context ctx;
70828  sqlite3_value **apVal;
70829#endif /* local variables moved into u.cg */
70830
70831  u.cg.n = pOp->p5;
70832  assert( u.cg.n>=0 );
70833  u.cg.pRec = &aMem[pOp->p2];
70834  u.cg.apVal = p->apArg;
70835  assert( u.cg.apVal || u.cg.n==0 );
70836  for(u.cg.i=0; u.cg.i<u.cg.n; u.cg.i++, u.cg.pRec++){
70837    assert( memIsValid(u.cg.pRec) );
70838    u.cg.apVal[u.cg.i] = u.cg.pRec;
70839    memAboutToChange(p, u.cg.pRec);
70840    sqlite3VdbeMemStoreType(u.cg.pRec);
70841  }
70842  u.cg.ctx.pFunc = pOp->p4.pFunc;
70843  assert( pOp->p3>0 && pOp->p3<=p->nMem );
70844  u.cg.ctx.pMem = u.cg.pMem = &aMem[pOp->p3];
70845  u.cg.pMem->n++;
70846  u.cg.ctx.s.flags = MEM_Null;
70847  u.cg.ctx.s.z = 0;
70848  u.cg.ctx.s.zMalloc = 0;
70849  u.cg.ctx.s.xDel = 0;
70850  u.cg.ctx.s.db = db;
70851  u.cg.ctx.isError = 0;
70852  u.cg.ctx.pColl = 0;
70853  u.cg.ctx.skipFlag = 0;
70854  if( u.cg.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
70855    assert( pOp>p->aOp );
70856    assert( pOp[-1].p4type==P4_COLLSEQ );
70857    assert( pOp[-1].opcode==OP_CollSeq );
70858    u.cg.ctx.pColl = pOp[-1].p4.pColl;
70859  }
70860  (u.cg.ctx.pFunc->xStep)(&u.cg.ctx, u.cg.n, u.cg.apVal); /* IMP: R-24505-23230 */
70861  if( u.cg.ctx.isError ){
70862    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.cg.ctx.s));
70863    rc = u.cg.ctx.isError;
70864  }
70865  if( u.cg.ctx.skipFlag ){
70866    assert( pOp[-1].opcode==OP_CollSeq );
70867    u.cg.i = pOp[-1].p1;
70868    if( u.cg.i ) sqlite3VdbeMemSetInt64(&aMem[u.cg.i], 1);
70869  }
70870
70871  sqlite3VdbeMemRelease(&u.cg.ctx.s);
70872
70873  break;
70874}
70875
70876/* Opcode: AggFinal P1 P2 * P4 *
70877**
70878** Execute the finalizer function for an aggregate.  P1 is
70879** the memory location that is the accumulator for the aggregate.
70880**
70881** P2 is the number of arguments that the step function takes and
70882** P4 is a pointer to the FuncDef for this function.  The P2
70883** argument is not used by this opcode.  It is only there to disambiguate
70884** functions that can take varying numbers of arguments.  The
70885** P4 argument is only needed for the degenerate case where
70886** the step function was not previously called.
70887*/
70888case OP_AggFinal: {
70889#if 0  /* local variables moved into u.ch */
70890  Mem *pMem;
70891#endif /* local variables moved into u.ch */
70892  assert( pOp->p1>0 && pOp->p1<=p->nMem );
70893  u.ch.pMem = &aMem[pOp->p1];
70894  assert( (u.ch.pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
70895  rc = sqlite3VdbeMemFinalize(u.ch.pMem, pOp->p4.pFunc);
70896  if( rc ){
70897    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(u.ch.pMem));
70898  }
70899  sqlite3VdbeChangeEncoding(u.ch.pMem, encoding);
70900  UPDATE_MAX_BLOBSIZE(u.ch.pMem);
70901  if( sqlite3VdbeMemTooBig(u.ch.pMem) ){
70902    goto too_big;
70903  }
70904  break;
70905}
70906
70907#ifndef SQLITE_OMIT_WAL
70908/* Opcode: Checkpoint P1 P2 P3 * *
70909**
70910** Checkpoint database P1. This is a no-op if P1 is not currently in
70911** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL
70912** or RESTART.  Write 1 or 0 into mem[P3] if the checkpoint returns
70913** SQLITE_BUSY or not, respectively.  Write the number of pages in the
70914** WAL after the checkpoint into mem[P3+1] and the number of pages
70915** in the WAL that have been checkpointed after the checkpoint
70916** completes into mem[P3+2].  However on an error, mem[P3+1] and
70917** mem[P3+2] are initialized to -1.
70918*/
70919case OP_Checkpoint: {
70920#if 0  /* local variables moved into u.ci */
70921  int i;                          /* Loop counter */
70922  int aRes[3];                    /* Results */
70923  Mem *pMem;                      /* Write results here */
70924#endif /* local variables moved into u.ci */
70925
70926  u.ci.aRes[0] = 0;
70927  u.ci.aRes[1] = u.ci.aRes[2] = -1;
70928  assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
70929       || pOp->p2==SQLITE_CHECKPOINT_FULL
70930       || pOp->p2==SQLITE_CHECKPOINT_RESTART
70931  );
70932  rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &u.ci.aRes[1], &u.ci.aRes[2]);
70933  if( rc==SQLITE_BUSY ){
70934    rc = SQLITE_OK;
70935    u.ci.aRes[0] = 1;
70936  }
70937  for(u.ci.i=0, u.ci.pMem = &aMem[pOp->p3]; u.ci.i<3; u.ci.i++, u.ci.pMem++){
70938    sqlite3VdbeMemSetInt64(u.ci.pMem, (i64)u.ci.aRes[u.ci.i]);
70939  }
70940  break;
70941};
70942#endif
70943
70944#ifndef SQLITE_OMIT_PRAGMA
70945/* Opcode: JournalMode P1 P2 P3 * P5
70946**
70947** Change the journal mode of database P1 to P3. P3 must be one of the
70948** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
70949** modes (delete, truncate, persist, off and memory), this is a simple
70950** operation. No IO is required.
70951**
70952** If changing into or out of WAL mode the procedure is more complicated.
70953**
70954** Write a string containing the final journal-mode to register P2.
70955*/
70956case OP_JournalMode: {    /* out2-prerelease */
70957#if 0  /* local variables moved into u.cj */
70958  Btree *pBt;                     /* Btree to change journal mode of */
70959  Pager *pPager;                  /* Pager associated with pBt */
70960  int eNew;                       /* New journal mode */
70961  int eOld;                       /* The old journal mode */
70962#ifndef SQLITE_OMIT_WAL
70963  const char *zFilename;          /* Name of database file for pPager */
70964#endif
70965#endif /* local variables moved into u.cj */
70966
70967  u.cj.eNew = pOp->p3;
70968  assert( u.cj.eNew==PAGER_JOURNALMODE_DELETE
70969       || u.cj.eNew==PAGER_JOURNALMODE_TRUNCATE
70970       || u.cj.eNew==PAGER_JOURNALMODE_PERSIST
70971       || u.cj.eNew==PAGER_JOURNALMODE_OFF
70972       || u.cj.eNew==PAGER_JOURNALMODE_MEMORY
70973       || u.cj.eNew==PAGER_JOURNALMODE_WAL
70974       || u.cj.eNew==PAGER_JOURNALMODE_QUERY
70975  );
70976  assert( pOp->p1>=0 && pOp->p1<db->nDb );
70977
70978  u.cj.pBt = db->aDb[pOp->p1].pBt;
70979  u.cj.pPager = sqlite3BtreePager(u.cj.pBt);
70980  u.cj.eOld = sqlite3PagerGetJournalMode(u.cj.pPager);
70981  if( u.cj.eNew==PAGER_JOURNALMODE_QUERY ) u.cj.eNew = u.cj.eOld;
70982  if( !sqlite3PagerOkToChangeJournalMode(u.cj.pPager) ) u.cj.eNew = u.cj.eOld;
70983
70984#ifndef SQLITE_OMIT_WAL
70985  u.cj.zFilename = sqlite3PagerFilename(u.cj.pPager, 1);
70986
70987  /* Do not allow a transition to journal_mode=WAL for a database
70988  ** in temporary storage or if the VFS does not support shared memory
70989  */
70990  if( u.cj.eNew==PAGER_JOURNALMODE_WAL
70991   && (sqlite3Strlen30(u.cj.zFilename)==0           /* Temp file */
70992       || !sqlite3PagerWalSupported(u.cj.pPager))   /* No shared-memory support */
70993  ){
70994    u.cj.eNew = u.cj.eOld;
70995  }
70996
70997  if( (u.cj.eNew!=u.cj.eOld)
70998   && (u.cj.eOld==PAGER_JOURNALMODE_WAL || u.cj.eNew==PAGER_JOURNALMODE_WAL)
70999  ){
71000    if( !db->autoCommit || db->activeVdbeCnt>1 ){
71001      rc = SQLITE_ERROR;
71002      sqlite3SetString(&p->zErrMsg, db,
71003          "cannot change %s wal mode from within a transaction",
71004          (u.cj.eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
71005      );
71006      break;
71007    }else{
71008
71009      if( u.cj.eOld==PAGER_JOURNALMODE_WAL ){
71010        /* If leaving WAL mode, close the log file. If successful, the call
71011        ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
71012        ** file. An EXCLUSIVE lock may still be held on the database file
71013        ** after a successful return.
71014        */
71015        rc = sqlite3PagerCloseWal(u.cj.pPager);
71016        if( rc==SQLITE_OK ){
71017          sqlite3PagerSetJournalMode(u.cj.pPager, u.cj.eNew);
71018        }
71019      }else if( u.cj.eOld==PAGER_JOURNALMODE_MEMORY ){
71020        /* Cannot transition directly from MEMORY to WAL.  Use mode OFF
71021        ** as an intermediate */
71022        sqlite3PagerSetJournalMode(u.cj.pPager, PAGER_JOURNALMODE_OFF);
71023      }
71024
71025      /* Open a transaction on the database file. Regardless of the journal
71026      ** mode, this transaction always uses a rollback journal.
71027      */
71028      assert( sqlite3BtreeIsInTrans(u.cj.pBt)==0 );
71029      if( rc==SQLITE_OK ){
71030        rc = sqlite3BtreeSetVersion(u.cj.pBt, (u.cj.eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
71031      }
71032    }
71033  }
71034#endif /* ifndef SQLITE_OMIT_WAL */
71035
71036  if( rc ){
71037    u.cj.eNew = u.cj.eOld;
71038  }
71039  u.cj.eNew = sqlite3PagerSetJournalMode(u.cj.pPager, u.cj.eNew);
71040
71041  pOut = &aMem[pOp->p2];
71042  pOut->flags = MEM_Str|MEM_Static|MEM_Term;
71043  pOut->z = (char *)sqlite3JournalModename(u.cj.eNew);
71044  pOut->n = sqlite3Strlen30(pOut->z);
71045  pOut->enc = SQLITE_UTF8;
71046  sqlite3VdbeChangeEncoding(pOut, encoding);
71047  break;
71048};
71049#endif /* SQLITE_OMIT_PRAGMA */
71050
71051#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
71052/* Opcode: Vacuum * * * * *
71053**
71054** Vacuum the entire database.  This opcode will cause other virtual
71055** machines to be created and run.  It may not be called from within
71056** a transaction.
71057*/
71058case OP_Vacuum: {
71059  rc = sqlite3RunVacuum(&p->zErrMsg, db);
71060  break;
71061}
71062#endif
71063
71064#if !defined(SQLITE_OMIT_AUTOVACUUM)
71065/* Opcode: IncrVacuum P1 P2 * * *
71066**
71067** Perform a single step of the incremental vacuum procedure on
71068** the P1 database. If the vacuum has finished, jump to instruction
71069** P2. Otherwise, fall through to the next instruction.
71070*/
71071case OP_IncrVacuum: {        /* jump */
71072#if 0  /* local variables moved into u.ck */
71073  Btree *pBt;
71074#endif /* local variables moved into u.ck */
71075
71076  assert( pOp->p1>=0 && pOp->p1<db->nDb );
71077  assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
71078  u.ck.pBt = db->aDb[pOp->p1].pBt;
71079  rc = sqlite3BtreeIncrVacuum(u.ck.pBt);
71080  if( rc==SQLITE_DONE ){
71081    pc = pOp->p2 - 1;
71082    rc = SQLITE_OK;
71083  }
71084  break;
71085}
71086#endif
71087
71088/* Opcode: Expire P1 * * * *
71089**
71090** Cause precompiled statements to become expired. An expired statement
71091** fails with an error code of SQLITE_SCHEMA if it is ever executed
71092** (via sqlite3_step()).
71093**
71094** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
71095** then only the currently executing statement is affected.
71096*/
71097case OP_Expire: {
71098  if( !pOp->p1 ){
71099    sqlite3ExpirePreparedStatements(db);
71100  }else{
71101    p->expired = 1;
71102  }
71103  break;
71104}
71105
71106#ifndef SQLITE_OMIT_SHARED_CACHE
71107/* Opcode: TableLock P1 P2 P3 P4 *
71108**
71109** Obtain a lock on a particular table. This instruction is only used when
71110** the shared-cache feature is enabled.
71111**
71112** P1 is the index of the database in sqlite3.aDb[] of the database
71113** on which the lock is acquired.  A readlock is obtained if P3==0 or
71114** a write lock if P3==1.
71115**
71116** P2 contains the root-page of the table to lock.
71117**
71118** P4 contains a pointer to the name of the table being locked. This is only
71119** used to generate an error message if the lock cannot be obtained.
71120*/
71121case OP_TableLock: {
71122  u8 isWriteLock = (u8)pOp->p3;
71123  if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
71124    int p1 = pOp->p1;
71125    assert( p1>=0 && p1<db->nDb );
71126    assert( (p->btreeMask & (((yDbMask)1)<<p1))!=0 );
71127    assert( isWriteLock==0 || isWriteLock==1 );
71128    rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
71129    if( (rc&0xFF)==SQLITE_LOCKED ){
71130      const char *z = pOp->p4.z;
71131      sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
71132    }
71133  }
71134  break;
71135}
71136#endif /* SQLITE_OMIT_SHARED_CACHE */
71137
71138#ifndef SQLITE_OMIT_VIRTUALTABLE
71139/* Opcode: VBegin * * * P4 *
71140**
71141** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
71142** xBegin method for that table.
71143**
71144** Also, whether or not P4 is set, check that this is not being called from
71145** within a callback to a virtual table xSync() method. If it is, the error
71146** code will be set to SQLITE_LOCKED.
71147*/
71148case OP_VBegin: {
71149#if 0  /* local variables moved into u.cl */
71150  VTable *pVTab;
71151#endif /* local variables moved into u.cl */
71152  u.cl.pVTab = pOp->p4.pVtab;
71153  rc = sqlite3VtabBegin(db, u.cl.pVTab);
71154  if( u.cl.pVTab ) importVtabErrMsg(p, u.cl.pVTab->pVtab);
71155  break;
71156}
71157#endif /* SQLITE_OMIT_VIRTUALTABLE */
71158
71159#ifndef SQLITE_OMIT_VIRTUALTABLE
71160/* Opcode: VCreate P1 * * P4 *
71161**
71162** P4 is the name of a virtual table in database P1. Call the xCreate method
71163** for that table.
71164*/
71165case OP_VCreate: {
71166  rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
71167  break;
71168}
71169#endif /* SQLITE_OMIT_VIRTUALTABLE */
71170
71171#ifndef SQLITE_OMIT_VIRTUALTABLE
71172/* Opcode: VDestroy P1 * * P4 *
71173**
71174** P4 is the name of a virtual table in database P1.  Call the xDestroy method
71175** of that table.
71176*/
71177case OP_VDestroy: {
71178  p->inVtabMethod = 2;
71179  rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
71180  p->inVtabMethod = 0;
71181  break;
71182}
71183#endif /* SQLITE_OMIT_VIRTUALTABLE */
71184
71185#ifndef SQLITE_OMIT_VIRTUALTABLE
71186/* Opcode: VOpen P1 * * P4 *
71187**
71188** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
71189** P1 is a cursor number.  This opcode opens a cursor to the virtual
71190** table and stores that cursor in P1.
71191*/
71192case OP_VOpen: {
71193#if 0  /* local variables moved into u.cm */
71194  VdbeCursor *pCur;
71195  sqlite3_vtab_cursor *pVtabCursor;
71196  sqlite3_vtab *pVtab;
71197  sqlite3_module *pModule;
71198#endif /* local variables moved into u.cm */
71199
71200  u.cm.pCur = 0;
71201  u.cm.pVtabCursor = 0;
71202  u.cm.pVtab = pOp->p4.pVtab->pVtab;
71203  u.cm.pModule = (sqlite3_module *)u.cm.pVtab->pModule;
71204  assert(u.cm.pVtab && u.cm.pModule);
71205  rc = u.cm.pModule->xOpen(u.cm.pVtab, &u.cm.pVtabCursor);
71206  importVtabErrMsg(p, u.cm.pVtab);
71207  if( SQLITE_OK==rc ){
71208    /* Initialize sqlite3_vtab_cursor base class */
71209    u.cm.pVtabCursor->pVtab = u.cm.pVtab;
71210
71211    /* Initialize vdbe cursor object */
71212    u.cm.pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
71213    if( u.cm.pCur ){
71214      u.cm.pCur->pVtabCursor = u.cm.pVtabCursor;
71215      u.cm.pCur->pModule = u.cm.pVtabCursor->pVtab->pModule;
71216    }else{
71217      db->mallocFailed = 1;
71218      u.cm.pModule->xClose(u.cm.pVtabCursor);
71219    }
71220  }
71221  break;
71222}
71223#endif /* SQLITE_OMIT_VIRTUALTABLE */
71224
71225#ifndef SQLITE_OMIT_VIRTUALTABLE
71226/* Opcode: VFilter P1 P2 P3 P4 *
71227**
71228** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
71229** the filtered result set is empty.
71230**
71231** P4 is either NULL or a string that was generated by the xBestIndex
71232** method of the module.  The interpretation of the P4 string is left
71233** to the module implementation.
71234**
71235** This opcode invokes the xFilter method on the virtual table specified
71236** by P1.  The integer query plan parameter to xFilter is stored in register
71237** P3. Register P3+1 stores the argc parameter to be passed to the
71238** xFilter method. Registers P3+2..P3+1+argc are the argc
71239** additional parameters which are passed to
71240** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
71241**
71242** A jump is made to P2 if the result set after filtering would be empty.
71243*/
71244case OP_VFilter: {   /* jump */
71245#if 0  /* local variables moved into u.cn */
71246  int nArg;
71247  int iQuery;
71248  const sqlite3_module *pModule;
71249  Mem *pQuery;
71250  Mem *pArgc;
71251  sqlite3_vtab_cursor *pVtabCursor;
71252  sqlite3_vtab *pVtab;
71253  VdbeCursor *pCur;
71254  int res;
71255  int i;
71256  Mem **apArg;
71257#endif /* local variables moved into u.cn */
71258
71259  u.cn.pQuery = &aMem[pOp->p3];
71260  u.cn.pArgc = &u.cn.pQuery[1];
71261  u.cn.pCur = p->apCsr[pOp->p1];
71262  assert( memIsValid(u.cn.pQuery) );
71263  REGISTER_TRACE(pOp->p3, u.cn.pQuery);
71264  assert( u.cn.pCur->pVtabCursor );
71265  u.cn.pVtabCursor = u.cn.pCur->pVtabCursor;
71266  u.cn.pVtab = u.cn.pVtabCursor->pVtab;
71267  u.cn.pModule = u.cn.pVtab->pModule;
71268
71269  /* Grab the index number and argc parameters */
71270  assert( (u.cn.pQuery->flags&MEM_Int)!=0 && u.cn.pArgc->flags==MEM_Int );
71271  u.cn.nArg = (int)u.cn.pArgc->u.i;
71272  u.cn.iQuery = (int)u.cn.pQuery->u.i;
71273
71274  /* Invoke the xFilter method */
71275  {
71276    u.cn.res = 0;
71277    u.cn.apArg = p->apArg;
71278    for(u.cn.i = 0; u.cn.i<u.cn.nArg; u.cn.i++){
71279      u.cn.apArg[u.cn.i] = &u.cn.pArgc[u.cn.i+1];
71280      sqlite3VdbeMemStoreType(u.cn.apArg[u.cn.i]);
71281    }
71282
71283    p->inVtabMethod = 1;
71284    rc = u.cn.pModule->xFilter(u.cn.pVtabCursor, u.cn.iQuery, pOp->p4.z, u.cn.nArg, u.cn.apArg);
71285    p->inVtabMethod = 0;
71286    importVtabErrMsg(p, u.cn.pVtab);
71287    if( rc==SQLITE_OK ){
71288      u.cn.res = u.cn.pModule->xEof(u.cn.pVtabCursor);
71289    }
71290
71291    if( u.cn.res ){
71292      pc = pOp->p2 - 1;
71293    }
71294  }
71295  u.cn.pCur->nullRow = 0;
71296
71297  break;
71298}
71299#endif /* SQLITE_OMIT_VIRTUALTABLE */
71300
71301#ifndef SQLITE_OMIT_VIRTUALTABLE
71302/* Opcode: VColumn P1 P2 P3 * *
71303**
71304** Store the value of the P2-th column of
71305** the row of the virtual-table that the
71306** P1 cursor is pointing to into register P3.
71307*/
71308case OP_VColumn: {
71309#if 0  /* local variables moved into u.co */
71310  sqlite3_vtab *pVtab;
71311  const sqlite3_module *pModule;
71312  Mem *pDest;
71313  sqlite3_context sContext;
71314#endif /* local variables moved into u.co */
71315
71316  VdbeCursor *pCur = p->apCsr[pOp->p1];
71317  assert( pCur->pVtabCursor );
71318  assert( pOp->p3>0 && pOp->p3<=p->nMem );
71319  u.co.pDest = &aMem[pOp->p3];
71320  memAboutToChange(p, u.co.pDest);
71321  if( pCur->nullRow ){
71322    sqlite3VdbeMemSetNull(u.co.pDest);
71323    break;
71324  }
71325  u.co.pVtab = pCur->pVtabCursor->pVtab;
71326  u.co.pModule = u.co.pVtab->pModule;
71327  assert( u.co.pModule->xColumn );
71328  memset(&u.co.sContext, 0, sizeof(u.co.sContext));
71329
71330  /* The output cell may already have a buffer allocated. Move
71331  ** the current contents to u.co.sContext.s so in case the user-function
71332  ** can use the already allocated buffer instead of allocating a
71333  ** new one.
71334  */
71335  sqlite3VdbeMemMove(&u.co.sContext.s, u.co.pDest);
71336  MemSetTypeFlag(&u.co.sContext.s, MEM_Null);
71337
71338  rc = u.co.pModule->xColumn(pCur->pVtabCursor, &u.co.sContext, pOp->p2);
71339  importVtabErrMsg(p, u.co.pVtab);
71340  if( u.co.sContext.isError ){
71341    rc = u.co.sContext.isError;
71342  }
71343
71344  /* Copy the result of the function to the P3 register. We
71345  ** do this regardless of whether or not an error occurred to ensure any
71346  ** dynamic allocation in u.co.sContext.s (a Mem struct) is  released.
71347  */
71348  sqlite3VdbeChangeEncoding(&u.co.sContext.s, encoding);
71349  sqlite3VdbeMemMove(u.co.pDest, &u.co.sContext.s);
71350  REGISTER_TRACE(pOp->p3, u.co.pDest);
71351  UPDATE_MAX_BLOBSIZE(u.co.pDest);
71352
71353  if( sqlite3VdbeMemTooBig(u.co.pDest) ){
71354    goto too_big;
71355  }
71356  break;
71357}
71358#endif /* SQLITE_OMIT_VIRTUALTABLE */
71359
71360#ifndef SQLITE_OMIT_VIRTUALTABLE
71361/* Opcode: VNext P1 P2 * * *
71362**
71363** Advance virtual table P1 to the next row in its result set and
71364** jump to instruction P2.  Or, if the virtual table has reached
71365** the end of its result set, then fall through to the next instruction.
71366*/
71367case OP_VNext: {   /* jump */
71368#if 0  /* local variables moved into u.cp */
71369  sqlite3_vtab *pVtab;
71370  const sqlite3_module *pModule;
71371  int res;
71372  VdbeCursor *pCur;
71373#endif /* local variables moved into u.cp */
71374
71375  u.cp.res = 0;
71376  u.cp.pCur = p->apCsr[pOp->p1];
71377  assert( u.cp.pCur->pVtabCursor );
71378  if( u.cp.pCur->nullRow ){
71379    break;
71380  }
71381  u.cp.pVtab = u.cp.pCur->pVtabCursor->pVtab;
71382  u.cp.pModule = u.cp.pVtab->pModule;
71383  assert( u.cp.pModule->xNext );
71384
71385  /* Invoke the xNext() method of the module. There is no way for the
71386  ** underlying implementation to return an error if one occurs during
71387  ** xNext(). Instead, if an error occurs, true is returned (indicating that
71388  ** data is available) and the error code returned when xColumn or
71389  ** some other method is next invoked on the save virtual table cursor.
71390  */
71391  p->inVtabMethod = 1;
71392  rc = u.cp.pModule->xNext(u.cp.pCur->pVtabCursor);
71393  p->inVtabMethod = 0;
71394  importVtabErrMsg(p, u.cp.pVtab);
71395  if( rc==SQLITE_OK ){
71396    u.cp.res = u.cp.pModule->xEof(u.cp.pCur->pVtabCursor);
71397  }
71398
71399  if( !u.cp.res ){
71400    /* If there is data, jump to P2 */
71401    pc = pOp->p2 - 1;
71402  }
71403  break;
71404}
71405#endif /* SQLITE_OMIT_VIRTUALTABLE */
71406
71407#ifndef SQLITE_OMIT_VIRTUALTABLE
71408/* Opcode: VRename P1 * * P4 *
71409**
71410** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
71411** This opcode invokes the corresponding xRename method. The value
71412** in register P1 is passed as the zName argument to the xRename method.
71413*/
71414case OP_VRename: {
71415#if 0  /* local variables moved into u.cq */
71416  sqlite3_vtab *pVtab;
71417  Mem *pName;
71418#endif /* local variables moved into u.cq */
71419
71420  u.cq.pVtab = pOp->p4.pVtab->pVtab;
71421  u.cq.pName = &aMem[pOp->p1];
71422  assert( u.cq.pVtab->pModule->xRename );
71423  assert( memIsValid(u.cq.pName) );
71424  REGISTER_TRACE(pOp->p1, u.cq.pName);
71425  assert( u.cq.pName->flags & MEM_Str );
71426  testcase( u.cq.pName->enc==SQLITE_UTF8 );
71427  testcase( u.cq.pName->enc==SQLITE_UTF16BE );
71428  testcase( u.cq.pName->enc==SQLITE_UTF16LE );
71429  rc = sqlite3VdbeChangeEncoding(u.cq.pName, SQLITE_UTF8);
71430  if( rc==SQLITE_OK ){
71431    rc = u.cq.pVtab->pModule->xRename(u.cq.pVtab, u.cq.pName->z);
71432    importVtabErrMsg(p, u.cq.pVtab);
71433    p->expired = 0;
71434  }
71435  break;
71436}
71437#endif
71438
71439#ifndef SQLITE_OMIT_VIRTUALTABLE
71440/* Opcode: VUpdate P1 P2 P3 P4 *
71441**
71442** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
71443** This opcode invokes the corresponding xUpdate method. P2 values
71444** are contiguous memory cells starting at P3 to pass to the xUpdate
71445** invocation. The value in register (P3+P2-1) corresponds to the
71446** p2th element of the argv array passed to xUpdate.
71447**
71448** The xUpdate method will do a DELETE or an INSERT or both.
71449** The argv[0] element (which corresponds to memory cell P3)
71450** is the rowid of a row to delete.  If argv[0] is NULL then no
71451** deletion occurs.  The argv[1] element is the rowid of the new
71452** row.  This can be NULL to have the virtual table select the new
71453** rowid for itself.  The subsequent elements in the array are
71454** the values of columns in the new row.
71455**
71456** If P2==1 then no insert is performed.  argv[0] is the rowid of
71457** a row to delete.
71458**
71459** P1 is a boolean flag. If it is set to true and the xUpdate call
71460** is successful, then the value returned by sqlite3_last_insert_rowid()
71461** is set to the value of the rowid for the row just inserted.
71462*/
71463case OP_VUpdate: {
71464#if 0  /* local variables moved into u.cr */
71465  sqlite3_vtab *pVtab;
71466  sqlite3_module *pModule;
71467  int nArg;
71468  int i;
71469  sqlite_int64 rowid;
71470  Mem **apArg;
71471  Mem *pX;
71472#endif /* local variables moved into u.cr */
71473
71474  assert( pOp->p2==1        || pOp->p5==OE_Fail   || pOp->p5==OE_Rollback
71475       || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
71476  );
71477  u.cr.pVtab = pOp->p4.pVtab->pVtab;
71478  u.cr.pModule = (sqlite3_module *)u.cr.pVtab->pModule;
71479  u.cr.nArg = pOp->p2;
71480  assert( pOp->p4type==P4_VTAB );
71481  if( ALWAYS(u.cr.pModule->xUpdate) ){
71482    u8 vtabOnConflict = db->vtabOnConflict;
71483    u.cr.apArg = p->apArg;
71484    u.cr.pX = &aMem[pOp->p3];
71485    for(u.cr.i=0; u.cr.i<u.cr.nArg; u.cr.i++){
71486      assert( memIsValid(u.cr.pX) );
71487      memAboutToChange(p, u.cr.pX);
71488      sqlite3VdbeMemStoreType(u.cr.pX);
71489      u.cr.apArg[u.cr.i] = u.cr.pX;
71490      u.cr.pX++;
71491    }
71492    db->vtabOnConflict = pOp->p5;
71493    rc = u.cr.pModule->xUpdate(u.cr.pVtab, u.cr.nArg, u.cr.apArg, &u.cr.rowid);
71494    db->vtabOnConflict = vtabOnConflict;
71495    importVtabErrMsg(p, u.cr.pVtab);
71496    if( rc==SQLITE_OK && pOp->p1 ){
71497      assert( u.cr.nArg>1 && u.cr.apArg[0] && (u.cr.apArg[0]->flags&MEM_Null) );
71498      db->lastRowid = lastRowid = u.cr.rowid;
71499    }
71500    if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
71501      if( pOp->p5==OE_Ignore ){
71502        rc = SQLITE_OK;
71503      }else{
71504        p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
71505      }
71506    }else{
71507      p->nChange++;
71508    }
71509  }
71510  break;
71511}
71512#endif /* SQLITE_OMIT_VIRTUALTABLE */
71513
71514#ifndef  SQLITE_OMIT_PAGER_PRAGMAS
71515/* Opcode: Pagecount P1 P2 * * *
71516**
71517** Write the current number of pages in database P1 to memory cell P2.
71518*/
71519case OP_Pagecount: {            /* out2-prerelease */
71520  pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
71521  break;
71522}
71523#endif
71524
71525
71526#ifndef  SQLITE_OMIT_PAGER_PRAGMAS
71527/* Opcode: MaxPgcnt P1 P2 P3 * *
71528**
71529** Try to set the maximum page count for database P1 to the value in P3.
71530** Do not let the maximum page count fall below the current page count and
71531** do not change the maximum page count value if P3==0.
71532**
71533** Store the maximum page count after the change in register P2.
71534*/
71535case OP_MaxPgcnt: {            /* out2-prerelease */
71536  unsigned int newMax;
71537  Btree *pBt;
71538
71539  pBt = db->aDb[pOp->p1].pBt;
71540  newMax = 0;
71541  if( pOp->p3 ){
71542    newMax = sqlite3BtreeLastPage(pBt);
71543    if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
71544  }
71545  pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
71546  break;
71547}
71548#endif
71549
71550
71551#ifndef SQLITE_OMIT_TRACE
71552/* Opcode: Trace * * * P4 *
71553**
71554** If tracing is enabled (by the sqlite3_trace()) interface, then
71555** the UTF-8 string contained in P4 is emitted on the trace callback.
71556*/
71557case OP_Trace: {
71558#if 0  /* local variables moved into u.cs */
71559  char *zTrace;
71560  char *z;
71561#endif /* local variables moved into u.cs */
71562
71563  if( db->xTrace
71564   && !p->doingRerun
71565   && (u.cs.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
71566  ){
71567    u.cs.z = sqlite3VdbeExpandSql(p, u.cs.zTrace);
71568    db->xTrace(db->pTraceArg, u.cs.z);
71569    sqlite3DbFree(db, u.cs.z);
71570  }
71571#ifdef SQLITE_DEBUG
71572  if( (db->flags & SQLITE_SqlTrace)!=0
71573   && (u.cs.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
71574  ){
71575    sqlite3DebugPrintf("SQL-trace: %s\n", u.cs.zTrace);
71576  }
71577#endif /* SQLITE_DEBUG */
71578  break;
71579}
71580#endif
71581
71582
71583/* Opcode: Noop * * * * *
71584**
71585** Do nothing.  This instruction is often useful as a jump
71586** destination.
71587*/
71588/*
71589** The magic Explain opcode are only inserted when explain==2 (which
71590** is to say when the EXPLAIN QUERY PLAN syntax is used.)
71591** This opcode records information from the optimizer.  It is the
71592** the same as a no-op.  This opcodesnever appears in a real VM program.
71593*/
71594default: {          /* This is really OP_Noop and OP_Explain */
71595  assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
71596  break;
71597}
71598
71599/*****************************************************************************
71600** The cases of the switch statement above this line should all be indented
71601** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
71602** readability.  From this point on down, the normal indentation rules are
71603** restored.
71604*****************************************************************************/
71605    }
71606
71607#ifdef VDBE_PROFILE
71608    {
71609      u64 elapsed = sqlite3Hwtime() - start;
71610      pOp->cycles += elapsed;
71611      pOp->cnt++;
71612#if 0
71613        fprintf(stdout, "%10llu ", elapsed);
71614        sqlite3VdbePrintOp(stdout, origPc, &aOp[origPc]);
71615#endif
71616    }
71617#endif
71618
71619    /* The following code adds nothing to the actual functionality
71620    ** of the program.  It is only here for testing and debugging.
71621    ** On the other hand, it does burn CPU cycles every time through
71622    ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
71623    */
71624#ifndef NDEBUG
71625    assert( pc>=-1 && pc<p->nOp );
71626
71627#ifdef SQLITE_DEBUG
71628    if( p->trace ){
71629      if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
71630      if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
71631        registerTrace(p->trace, pOp->p2, &aMem[pOp->p2]);
71632      }
71633      if( pOp->opflags & OPFLG_OUT3 ){
71634        registerTrace(p->trace, pOp->p3, &aMem[pOp->p3]);
71635      }
71636    }
71637#endif  /* SQLITE_DEBUG */
71638#endif  /* NDEBUG */
71639  }  /* The end of the for(;;) loop the loops through opcodes */
71640
71641  /* If we reach this point, it means that execution is finished with
71642  ** an error of some kind.
71643  */
71644vdbe_error_halt:
71645  assert( rc );
71646  p->rc = rc;
71647  testcase( sqlite3GlobalConfig.xLog!=0 );
71648  sqlite3_log(rc, "statement aborts at %d: [%s] %s",
71649                   pc, p->zSql, p->zErrMsg);
71650  sqlite3VdbeHalt(p);
71651  if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
71652  rc = SQLITE_ERROR;
71653  if( resetSchemaOnFault>0 ){
71654    sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
71655  }
71656
71657  /* This is the only way out of this procedure.  We have to
71658  ** release the mutexes on btrees that were acquired at the
71659  ** top. */
71660vdbe_return:
71661  db->lastRowid = lastRowid;
71662  sqlite3VdbeLeave(p);
71663  return rc;
71664
71665  /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
71666  ** is encountered.
71667  */
71668too_big:
71669  sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
71670  rc = SQLITE_TOOBIG;
71671  goto vdbe_error_halt;
71672
71673  /* Jump to here if a malloc() fails.
71674  */
71675no_mem:
71676  db->mallocFailed = 1;
71677  sqlite3SetString(&p->zErrMsg, db, "out of memory");
71678  rc = SQLITE_NOMEM;
71679  goto vdbe_error_halt;
71680
71681  /* Jump to here for any other kind of fatal error.  The "rc" variable
71682  ** should hold the error number.
71683  */
71684abort_due_to_error:
71685  assert( p->zErrMsg==0 );
71686  if( db->mallocFailed ) rc = SQLITE_NOMEM;
71687  if( rc!=SQLITE_IOERR_NOMEM ){
71688    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
71689  }
71690  goto vdbe_error_halt;
71691
71692  /* Jump to here if the sqlite3_interrupt() API sets the interrupt
71693  ** flag.
71694  */
71695abort_due_to_interrupt:
71696  assert( db->u1.isInterrupted );
71697  rc = SQLITE_INTERRUPT;
71698  p->rc = rc;
71699  sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
71700  goto vdbe_error_halt;
71701}
71702
71703/************** End of vdbe.c ************************************************/
71704/************** Begin file vdbeblob.c ****************************************/
71705/*
71706** 2007 May 1
71707**
71708** The author disclaims copyright to this source code.  In place of
71709** a legal notice, here is a blessing:
71710**
71711**    May you do good and not evil.
71712**    May you find forgiveness for yourself and forgive others.
71713**    May you share freely, never taking more than you give.
71714**
71715*************************************************************************
71716**
71717** This file contains code used to implement incremental BLOB I/O.
71718*/
71719
71720
71721#ifndef SQLITE_OMIT_INCRBLOB
71722
71723/*
71724** Valid sqlite3_blob* handles point to Incrblob structures.
71725*/
71726typedef struct Incrblob Incrblob;
71727struct Incrblob {
71728  int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
71729  int nByte;              /* Size of open blob, in bytes */
71730  int iOffset;            /* Byte offset of blob in cursor data */
71731  int iCol;               /* Table column this handle is open on */
71732  BtCursor *pCsr;         /* Cursor pointing at blob row */
71733  sqlite3_stmt *pStmt;    /* Statement holding cursor open */
71734  sqlite3 *db;            /* The associated database */
71735};
71736
71737
71738/*
71739** This function is used by both blob_open() and blob_reopen(). It seeks
71740** the b-tree cursor associated with blob handle p to point to row iRow.
71741** If successful, SQLITE_OK is returned and subsequent calls to
71742** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
71743**
71744** If an error occurs, or if the specified row does not exist or does not
71745** contain a value of type TEXT or BLOB in the column nominated when the
71746** blob handle was opened, then an error code is returned and *pzErr may
71747** be set to point to a buffer containing an error message. It is the
71748** responsibility of the caller to free the error message buffer using
71749** sqlite3DbFree().
71750**
71751** If an error does occur, then the b-tree cursor is closed. All subsequent
71752** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
71753** immediately return SQLITE_ABORT.
71754*/
71755static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
71756  int rc;                         /* Error code */
71757  char *zErr = 0;                 /* Error message */
71758  Vdbe *v = (Vdbe *)p->pStmt;
71759
71760  /* Set the value of the SQL statements only variable to integer iRow.
71761  ** This is done directly instead of using sqlite3_bind_int64() to avoid
71762  ** triggering asserts related to mutexes.
71763  */
71764  assert( v->aVar[0].flags&MEM_Int );
71765  v->aVar[0].u.i = iRow;
71766
71767  rc = sqlite3_step(p->pStmt);
71768  if( rc==SQLITE_ROW ){
71769    u32 type = v->apCsr[0]->aType[p->iCol];
71770    if( type<12 ){
71771      zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
71772          type==0?"null": type==7?"real": "integer"
71773      );
71774      rc = SQLITE_ERROR;
71775      sqlite3_finalize(p->pStmt);
71776      p->pStmt = 0;
71777    }else{
71778      p->iOffset = v->apCsr[0]->aOffset[p->iCol];
71779      p->nByte = sqlite3VdbeSerialTypeLen(type);
71780      p->pCsr =  v->apCsr[0]->pCursor;
71781      sqlite3BtreeEnterCursor(p->pCsr);
71782      sqlite3BtreeCacheOverflow(p->pCsr);
71783      sqlite3BtreeLeaveCursor(p->pCsr);
71784    }
71785  }
71786
71787  if( rc==SQLITE_ROW ){
71788    rc = SQLITE_OK;
71789  }else if( p->pStmt ){
71790    rc = sqlite3_finalize(p->pStmt);
71791    p->pStmt = 0;
71792    if( rc==SQLITE_OK ){
71793      zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
71794      rc = SQLITE_ERROR;
71795    }else{
71796      zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
71797    }
71798  }
71799
71800  assert( rc!=SQLITE_OK || zErr==0 );
71801  assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
71802
71803  *pzErr = zErr;
71804  return rc;
71805}
71806
71807/*
71808** Open a blob handle.
71809*/
71810SQLITE_API int sqlite3_blob_open(
71811  sqlite3* db,            /* The database connection */
71812  const char *zDb,        /* The attached database containing the blob */
71813  const char *zTable,     /* The table containing the blob */
71814  const char *zColumn,    /* The column containing the blob */
71815  sqlite_int64 iRow,      /* The row containing the glob */
71816  int flags,              /* True -> read/write access, false -> read-only */
71817  sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
71818){
71819  int nAttempt = 0;
71820  int iCol;               /* Index of zColumn in row-record */
71821
71822  /* This VDBE program seeks a btree cursor to the identified
71823  ** db/table/row entry. The reason for using a vdbe program instead
71824  ** of writing code to use the b-tree layer directly is that the
71825  ** vdbe program will take advantage of the various transaction,
71826  ** locking and error handling infrastructure built into the vdbe.
71827  **
71828  ** After seeking the cursor, the vdbe executes an OP_ResultRow.
71829  ** Code external to the Vdbe then "borrows" the b-tree cursor and
71830  ** uses it to implement the blob_read(), blob_write() and
71831  ** blob_bytes() functions.
71832  **
71833  ** The sqlite3_blob_close() function finalizes the vdbe program,
71834  ** which closes the b-tree cursor and (possibly) commits the
71835  ** transaction.
71836  */
71837  static const VdbeOpList openBlob[] = {
71838    {OP_Transaction, 0, 0, 0},     /* 0: Start a transaction */
71839    {OP_VerifyCookie, 0, 0, 0},    /* 1: Check the schema cookie */
71840    {OP_TableLock, 0, 0, 0},       /* 2: Acquire a read or write lock */
71841
71842    /* One of the following two instructions is replaced by an OP_Noop. */
71843    {OP_OpenRead, 0, 0, 0},        /* 3: Open cursor 0 for reading */
71844    {OP_OpenWrite, 0, 0, 0},       /* 4: Open cursor 0 for read/write */
71845
71846    {OP_Variable, 1, 1, 1},        /* 5: Push the rowid to the stack */
71847    {OP_NotExists, 0, 10, 1},      /* 6: Seek the cursor */
71848    {OP_Column, 0, 0, 1},          /* 7  */
71849    {OP_ResultRow, 1, 0, 0},       /* 8  */
71850    {OP_Goto, 0, 5, 0},            /* 9  */
71851    {OP_Close, 0, 0, 0},           /* 10 */
71852    {OP_Halt, 0, 0, 0},            /* 11 */
71853  };
71854
71855  int rc = SQLITE_OK;
71856  char *zErr = 0;
71857  Table *pTab;
71858  Parse *pParse = 0;
71859  Incrblob *pBlob = 0;
71860
71861  flags = !!flags;                /* flags = (flags ? 1 : 0); */
71862  *ppBlob = 0;
71863
71864  sqlite3_mutex_enter(db->mutex);
71865
71866  pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
71867  if( !pBlob ) goto blob_open_out;
71868  pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
71869  if( !pParse ) goto blob_open_out;
71870
71871  do {
71872    memset(pParse, 0, sizeof(Parse));
71873    pParse->db = db;
71874    sqlite3DbFree(db, zErr);
71875    zErr = 0;
71876
71877    sqlite3BtreeEnterAll(db);
71878    pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
71879    if( pTab && IsVirtual(pTab) ){
71880      pTab = 0;
71881      sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
71882    }
71883#ifndef SQLITE_OMIT_VIEW
71884    if( pTab && pTab->pSelect ){
71885      pTab = 0;
71886      sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
71887    }
71888#endif
71889    if( !pTab ){
71890      if( pParse->zErrMsg ){
71891        sqlite3DbFree(db, zErr);
71892        zErr = pParse->zErrMsg;
71893        pParse->zErrMsg = 0;
71894      }
71895      rc = SQLITE_ERROR;
71896      sqlite3BtreeLeaveAll(db);
71897      goto blob_open_out;
71898    }
71899
71900    /* Now search pTab for the exact column. */
71901    for(iCol=0; iCol<pTab->nCol; iCol++) {
71902      if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
71903        break;
71904      }
71905    }
71906    if( iCol==pTab->nCol ){
71907      sqlite3DbFree(db, zErr);
71908      zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
71909      rc = SQLITE_ERROR;
71910      sqlite3BtreeLeaveAll(db);
71911      goto blob_open_out;
71912    }
71913
71914    /* If the value is being opened for writing, check that the
71915    ** column is not indexed, and that it is not part of a foreign key.
71916    ** It is against the rules to open a column to which either of these
71917    ** descriptions applies for writing.  */
71918    if( flags ){
71919      const char *zFault = 0;
71920      Index *pIdx;
71921#ifndef SQLITE_OMIT_FOREIGN_KEY
71922      if( db->flags&SQLITE_ForeignKeys ){
71923        /* Check that the column is not part of an FK child key definition. It
71924        ** is not necessary to check if it is part of a parent key, as parent
71925        ** key columns must be indexed. The check below will pick up this
71926        ** case.  */
71927        FKey *pFKey;
71928        for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
71929          int j;
71930          for(j=0; j<pFKey->nCol; j++){
71931            if( pFKey->aCol[j].iFrom==iCol ){
71932              zFault = "foreign key";
71933            }
71934          }
71935        }
71936      }
71937#endif
71938      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
71939        int j;
71940        for(j=0; j<pIdx->nColumn; j++){
71941          if( pIdx->aiColumn[j]==iCol ){
71942            zFault = "indexed";
71943          }
71944        }
71945      }
71946      if( zFault ){
71947        sqlite3DbFree(db, zErr);
71948        zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
71949        rc = SQLITE_ERROR;
71950        sqlite3BtreeLeaveAll(db);
71951        goto blob_open_out;
71952      }
71953    }
71954
71955    pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(db);
71956    assert( pBlob->pStmt || db->mallocFailed );
71957    if( pBlob->pStmt ){
71958      Vdbe *v = (Vdbe *)pBlob->pStmt;
71959      int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
71960
71961      sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
71962
71963
71964      /* Configure the OP_Transaction */
71965      sqlite3VdbeChangeP1(v, 0, iDb);
71966      sqlite3VdbeChangeP2(v, 0, flags);
71967
71968      /* Configure the OP_VerifyCookie */
71969      sqlite3VdbeChangeP1(v, 1, iDb);
71970      sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
71971      sqlite3VdbeChangeP3(v, 1, pTab->pSchema->iGeneration);
71972
71973      /* Make sure a mutex is held on the table to be accessed */
71974      sqlite3VdbeUsesBtree(v, iDb);
71975
71976      /* Configure the OP_TableLock instruction */
71977#ifdef SQLITE_OMIT_SHARED_CACHE
71978      sqlite3VdbeChangeToNoop(v, 2);
71979#else
71980      sqlite3VdbeChangeP1(v, 2, iDb);
71981      sqlite3VdbeChangeP2(v, 2, pTab->tnum);
71982      sqlite3VdbeChangeP3(v, 2, flags);
71983      sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
71984#endif
71985
71986      /* Remove either the OP_OpenWrite or OpenRead. Set the P2
71987      ** parameter of the other to pTab->tnum.  */
71988      sqlite3VdbeChangeToNoop(v, 4 - flags);
71989      sqlite3VdbeChangeP2(v, 3 + flags, pTab->tnum);
71990      sqlite3VdbeChangeP3(v, 3 + flags, iDb);
71991
71992      /* Configure the number of columns. Configure the cursor to
71993      ** think that the table has one more column than it really
71994      ** does. An OP_Column to retrieve this imaginary column will
71995      ** always return an SQL NULL. This is useful because it means
71996      ** we can invoke OP_Column to fill in the vdbe cursors type
71997      ** and offset cache without causing any IO.
71998      */
71999      sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
72000      sqlite3VdbeChangeP2(v, 7, pTab->nCol);
72001      if( !db->mallocFailed ){
72002        pParse->nVar = 1;
72003        pParse->nMem = 1;
72004        pParse->nTab = 1;
72005        sqlite3VdbeMakeReady(v, pParse);
72006      }
72007    }
72008
72009    pBlob->flags = flags;
72010    pBlob->iCol = iCol;
72011    pBlob->db = db;
72012    sqlite3BtreeLeaveAll(db);
72013    if( db->mallocFailed ){
72014      goto blob_open_out;
72015    }
72016    sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
72017    rc = blobSeekToRow(pBlob, iRow, &zErr);
72018  } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );
72019
72020blob_open_out:
72021  if( rc==SQLITE_OK && db->mallocFailed==0 ){
72022    *ppBlob = (sqlite3_blob *)pBlob;
72023  }else{
72024    if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
72025    sqlite3DbFree(db, pBlob);
72026  }
72027  sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
72028  sqlite3DbFree(db, zErr);
72029  sqlite3StackFree(db, pParse);
72030  rc = sqlite3ApiExit(db, rc);
72031  sqlite3_mutex_leave(db->mutex);
72032  return rc;
72033}
72034
72035/*
72036** Close a blob handle that was previously created using
72037** sqlite3_blob_open().
72038*/
72039SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
72040  Incrblob *p = (Incrblob *)pBlob;
72041  int rc;
72042  sqlite3 *db;
72043
72044  if( p ){
72045    db = p->db;
72046    sqlite3_mutex_enter(db->mutex);
72047    rc = sqlite3_finalize(p->pStmt);
72048    sqlite3DbFree(db, p);
72049    sqlite3_mutex_leave(db->mutex);
72050  }else{
72051    rc = SQLITE_OK;
72052  }
72053  return rc;
72054}
72055
72056/*
72057** Perform a read or write operation on a blob
72058*/
72059static int blobReadWrite(
72060  sqlite3_blob *pBlob,
72061  void *z,
72062  int n,
72063  int iOffset,
72064  int (*xCall)(BtCursor*, u32, u32, void*)
72065){
72066  int rc;
72067  Incrblob *p = (Incrblob *)pBlob;
72068  Vdbe *v;
72069  sqlite3 *db;
72070
72071  if( p==0 ) return SQLITE_MISUSE_BKPT;
72072  db = p->db;
72073  sqlite3_mutex_enter(db->mutex);
72074  v = (Vdbe*)p->pStmt;
72075
72076  if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
72077    /* Request is out of range. Return a transient error. */
72078    rc = SQLITE_ERROR;
72079    sqlite3Error(db, SQLITE_ERROR, 0);
72080  }else if( v==0 ){
72081    /* If there is no statement handle, then the blob-handle has
72082    ** already been invalidated. Return SQLITE_ABORT in this case.
72083    */
72084    rc = SQLITE_ABORT;
72085  }else{
72086    /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
72087    ** returned, clean-up the statement handle.
72088    */
72089    assert( db == v->db );
72090    sqlite3BtreeEnterCursor(p->pCsr);
72091    rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
72092    sqlite3BtreeLeaveCursor(p->pCsr);
72093    if( rc==SQLITE_ABORT ){
72094      sqlite3VdbeFinalize(v);
72095      p->pStmt = 0;
72096    }else{
72097      db->errCode = rc;
72098      v->rc = rc;
72099    }
72100  }
72101  rc = sqlite3ApiExit(db, rc);
72102  sqlite3_mutex_leave(db->mutex);
72103  return rc;
72104}
72105
72106/*
72107** Read data from a blob handle.
72108*/
72109SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
72110  return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
72111}
72112
72113/*
72114** Write data to a blob handle.
72115*/
72116SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
72117  return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
72118}
72119
72120/*
72121** Query a blob handle for the size of the data.
72122**
72123** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
72124** so no mutex is required for access.
72125*/
72126SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
72127  Incrblob *p = (Incrblob *)pBlob;
72128  return (p && p->pStmt) ? p->nByte : 0;
72129}
72130
72131/*
72132** Move an existing blob handle to point to a different row of the same
72133** database table.
72134**
72135** If an error occurs, or if the specified row does not exist or does not
72136** contain a blob or text value, then an error code is returned and the
72137** database handle error code and message set. If this happens, then all
72138** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
72139** immediately return SQLITE_ABORT.
72140*/
72141SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
72142  int rc;
72143  Incrblob *p = (Incrblob *)pBlob;
72144  sqlite3 *db;
72145
72146  if( p==0 ) return SQLITE_MISUSE_BKPT;
72147  db = p->db;
72148  sqlite3_mutex_enter(db->mutex);
72149
72150  if( p->pStmt==0 ){
72151    /* If there is no statement handle, then the blob-handle has
72152    ** already been invalidated. Return SQLITE_ABORT in this case.
72153    */
72154    rc = SQLITE_ABORT;
72155  }else{
72156    char *zErr;
72157    rc = blobSeekToRow(p, iRow, &zErr);
72158    if( rc!=SQLITE_OK ){
72159      sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
72160      sqlite3DbFree(db, zErr);
72161    }
72162    assert( rc!=SQLITE_SCHEMA );
72163  }
72164
72165  rc = sqlite3ApiExit(db, rc);
72166  assert( rc==SQLITE_OK || p->pStmt==0 );
72167  sqlite3_mutex_leave(db->mutex);
72168  return rc;
72169}
72170
72171#endif /* #ifndef SQLITE_OMIT_INCRBLOB */
72172
72173/************** End of vdbeblob.c ********************************************/
72174/************** Begin file vdbesort.c ****************************************/
72175/*
72176** 2011 July 9
72177**
72178** The author disclaims copyright to this source code.  In place of
72179** a legal notice, here is a blessing:
72180**
72181**    May you do good and not evil.
72182**    May you find forgiveness for yourself and forgive others.
72183**    May you share freely, never taking more than you give.
72184**
72185*************************************************************************
72186** This file contains code for the VdbeSorter object, used in concert with
72187** a VdbeCursor to sort large numbers of keys (as may be required, for
72188** example, by CREATE INDEX statements on tables too large to fit in main
72189** memory).
72190*/
72191
72192
72193
72194typedef struct VdbeSorterIter VdbeSorterIter;
72195typedef struct SorterRecord SorterRecord;
72196typedef struct FileWriter FileWriter;
72197
72198/*
72199** NOTES ON DATA STRUCTURE USED FOR N-WAY MERGES:
72200**
72201** As keys are added to the sorter, they are written to disk in a series
72202** of sorted packed-memory-arrays (PMAs). The size of each PMA is roughly
72203** the same as the cache-size allowed for temporary databases. In order
72204** to allow the caller to extract keys from the sorter in sorted order,
72205** all PMAs currently stored on disk must be merged together. This comment
72206** describes the data structure used to do so. The structure supports
72207** merging any number of arrays in a single pass with no redundant comparison
72208** operations.
72209**
72210** The aIter[] array contains an iterator for each of the PMAs being merged.
72211** An aIter[] iterator either points to a valid key or else is at EOF. For
72212** the purposes of the paragraphs below, we assume that the array is actually
72213** N elements in size, where N is the smallest power of 2 greater to or equal
72214** to the number of iterators being merged. The extra aIter[] elements are
72215** treated as if they are empty (always at EOF).
72216**
72217** The aTree[] array is also N elements in size. The value of N is stored in
72218** the VdbeSorter.nTree variable.
72219**
72220** The final (N/2) elements of aTree[] contain the results of comparing
72221** pairs of iterator keys together. Element i contains the result of
72222** comparing aIter[2*i-N] and aIter[2*i-N+1]. Whichever key is smaller, the
72223** aTree element is set to the index of it.
72224**
72225** For the purposes of this comparison, EOF is considered greater than any
72226** other key value. If the keys are equal (only possible with two EOF
72227** values), it doesn't matter which index is stored.
72228**
72229** The (N/4) elements of aTree[] that preceed the final (N/2) described
72230** above contains the index of the smallest of each block of 4 iterators.
72231** And so on. So that aTree[1] contains the index of the iterator that
72232** currently points to the smallest key value. aTree[0] is unused.
72233**
72234** Example:
72235**
72236**     aIter[0] -> Banana
72237**     aIter[1] -> Feijoa
72238**     aIter[2] -> Elderberry
72239**     aIter[3] -> Currant
72240**     aIter[4] -> Grapefruit
72241**     aIter[5] -> Apple
72242**     aIter[6] -> Durian
72243**     aIter[7] -> EOF
72244**
72245**     aTree[] = { X, 5   0, 5    0, 3, 5, 6 }
72246**
72247** The current element is "Apple" (the value of the key indicated by
72248** iterator 5). When the Next() operation is invoked, iterator 5 will
72249** be advanced to the next key in its segment. Say the next key is
72250** "Eggplant":
72251**
72252**     aIter[5] -> Eggplant
72253**
72254** The contents of aTree[] are updated first by comparing the new iterator
72255** 5 key to the current key of iterator 4 (still "Grapefruit"). The iterator
72256** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
72257** The value of iterator 6 - "Durian" - is now smaller than that of iterator
72258** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
72259** so the value written into element 1 of the array is 0. As follows:
72260**
72261**     aTree[] = { X, 0   0, 6    0, 3, 5, 6 }
72262**
72263** In other words, each time we advance to the next sorter element, log2(N)
72264** key comparison operations are required, where N is the number of segments
72265** being merged (rounded up to the next power of 2).
72266*/
72267struct VdbeSorter {
72268  i64 iWriteOff;                  /* Current write offset within file pTemp1 */
72269  i64 iReadOff;                   /* Current read offset within file pTemp1 */
72270  int nInMemory;                  /* Current size of pRecord list as PMA */
72271  int nTree;                      /* Used size of aTree/aIter (power of 2) */
72272  int nPMA;                       /* Number of PMAs stored in pTemp1 */
72273  int mnPmaSize;                  /* Minimum PMA size, in bytes */
72274  int mxPmaSize;                  /* Maximum PMA size, in bytes.  0==no limit */
72275  VdbeSorterIter *aIter;          /* Array of iterators to merge */
72276  int *aTree;                     /* Current state of incremental merge */
72277  sqlite3_file *pTemp1;           /* PMA file 1 */
72278  SorterRecord *pRecord;          /* Head of in-memory record list */
72279  UnpackedRecord *pUnpacked;      /* Used to unpack keys */
72280};
72281
72282/*
72283** The following type is an iterator for a PMA. It caches the current key in
72284** variables nKey/aKey. If the iterator is at EOF, pFile==0.
72285*/
72286struct VdbeSorterIter {
72287  i64 iReadOff;                   /* Current read offset */
72288  i64 iEof;                       /* 1 byte past EOF for this iterator */
72289  int nAlloc;                     /* Bytes of space at aAlloc */
72290  int nKey;                       /* Number of bytes in key */
72291  sqlite3_file *pFile;            /* File iterator is reading from */
72292  u8 *aAlloc;                     /* Allocated space */
72293  u8 *aKey;                       /* Pointer to current key */
72294  u8 *aBuffer;                    /* Current read buffer */
72295  int nBuffer;                    /* Size of read buffer in bytes */
72296};
72297
72298/*
72299** An instance of this structure is used to organize the stream of records
72300** being written to files by the merge-sort code into aligned, page-sized
72301** blocks.  Doing all I/O in aligned page-sized blocks helps I/O to go
72302** faster on many operating systems.
72303*/
72304struct FileWriter {
72305  int eFWErr;                     /* Non-zero if in an error state */
72306  u8 *aBuffer;                    /* Pointer to write buffer */
72307  int nBuffer;                    /* Size of write buffer in bytes */
72308  int iBufStart;                  /* First byte of buffer to write */
72309  int iBufEnd;                    /* Last byte of buffer to write */
72310  i64 iWriteOff;                  /* Offset of start of buffer in file */
72311  sqlite3_file *pFile;            /* File to write to */
72312};
72313
72314/*
72315** A structure to store a single record. All in-memory records are connected
72316** together into a linked list headed at VdbeSorter.pRecord using the
72317** SorterRecord.pNext pointer.
72318*/
72319struct SorterRecord {
72320  void *pVal;
72321  int nVal;
72322  SorterRecord *pNext;
72323};
72324
72325/* Minimum allowable value for the VdbeSorter.nWorking variable */
72326#define SORTER_MIN_WORKING 10
72327
72328/* Maximum number of segments to merge in a single pass. */
72329#define SORTER_MAX_MERGE_COUNT 16
72330
72331/*
72332** Free all memory belonging to the VdbeSorterIter object passed as the second
72333** argument. All structure fields are set to zero before returning.
72334*/
72335static void vdbeSorterIterZero(sqlite3 *db, VdbeSorterIter *pIter){
72336  sqlite3DbFree(db, pIter->aAlloc);
72337  sqlite3DbFree(db, pIter->aBuffer);
72338  memset(pIter, 0, sizeof(VdbeSorterIter));
72339}
72340
72341/*
72342** Read nByte bytes of data from the stream of data iterated by object p.
72343** If successful, set *ppOut to point to a buffer containing the data
72344** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
72345** error code.
72346**
72347** The buffer indicated by *ppOut may only be considered valid until the
72348** next call to this function.
72349*/
72350static int vdbeSorterIterRead(
72351  sqlite3 *db,                    /* Database handle (for malloc) */
72352  VdbeSorterIter *p,              /* Iterator */
72353  int nByte,                      /* Bytes of data to read */
72354  u8 **ppOut                      /* OUT: Pointer to buffer containing data */
72355){
72356  int iBuf;                       /* Offset within buffer to read from */
72357  int nAvail;                     /* Bytes of data available in buffer */
72358  assert( p->aBuffer );
72359
72360  /* If there is no more data to be read from the buffer, read the next
72361  ** p->nBuffer bytes of data from the file into it. Or, if there are less
72362  ** than p->nBuffer bytes remaining in the PMA, read all remaining data.  */
72363  iBuf = p->iReadOff % p->nBuffer;
72364  if( iBuf==0 ){
72365    int nRead;                    /* Bytes to read from disk */
72366    int rc;                       /* sqlite3OsRead() return code */
72367
72368    /* Determine how many bytes of data to read. */
72369    if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
72370      nRead = p->nBuffer;
72371    }else{
72372      nRead = (int)(p->iEof - p->iReadOff);
72373    }
72374    assert( nRead>0 );
72375
72376    /* Read data from the file. Return early if an error occurs. */
72377    rc = sqlite3OsRead(p->pFile, p->aBuffer, nRead, p->iReadOff);
72378    assert( rc!=SQLITE_IOERR_SHORT_READ );
72379    if( rc!=SQLITE_OK ) return rc;
72380  }
72381  nAvail = p->nBuffer - iBuf;
72382
72383  if( nByte<=nAvail ){
72384    /* The requested data is available in the in-memory buffer. In this
72385    ** case there is no need to make a copy of the data, just return a
72386    ** pointer into the buffer to the caller.  */
72387    *ppOut = &p->aBuffer[iBuf];
72388    p->iReadOff += nByte;
72389  }else{
72390    /* The requested data is not all available in the in-memory buffer.
72391    ** In this case, allocate space at p->aAlloc[] to copy the requested
72392    ** range into. Then return a copy of pointer p->aAlloc to the caller.  */
72393    int nRem;                     /* Bytes remaining to copy */
72394
72395    /* Extend the p->aAlloc[] allocation if required. */
72396    if( p->nAlloc<nByte ){
72397      int nNew = p->nAlloc*2;
72398      while( nByte>nNew ) nNew = nNew*2;
72399      p->aAlloc = sqlite3DbReallocOrFree(db, p->aAlloc, nNew);
72400      if( !p->aAlloc ) return SQLITE_NOMEM;
72401      p->nAlloc = nNew;
72402    }
72403
72404    /* Copy as much data as is available in the buffer into the start of
72405    ** p->aAlloc[].  */
72406    memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
72407    p->iReadOff += nAvail;
72408    nRem = nByte - nAvail;
72409
72410    /* The following loop copies up to p->nBuffer bytes per iteration into
72411    ** the p->aAlloc[] buffer.  */
72412    while( nRem>0 ){
72413      int rc;                     /* vdbeSorterIterRead() return code */
72414      int nCopy;                  /* Number of bytes to copy */
72415      u8 *aNext;                  /* Pointer to buffer to copy data from */
72416
72417      nCopy = nRem;
72418      if( nRem>p->nBuffer ) nCopy = p->nBuffer;
72419      rc = vdbeSorterIterRead(db, p, nCopy, &aNext);
72420      if( rc!=SQLITE_OK ) return rc;
72421      assert( aNext!=p->aAlloc );
72422      memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
72423      nRem -= nCopy;
72424    }
72425
72426    *ppOut = p->aAlloc;
72427  }
72428
72429  return SQLITE_OK;
72430}
72431
72432/*
72433** Read a varint from the stream of data accessed by p. Set *pnOut to
72434** the value read.
72435*/
72436static int vdbeSorterIterVarint(sqlite3 *db, VdbeSorterIter *p, u64 *pnOut){
72437  int iBuf;
72438
72439  iBuf = p->iReadOff % p->nBuffer;
72440  if( iBuf && (p->nBuffer-iBuf)>=9 ){
72441    p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
72442  }else{
72443    u8 aVarint[16], *a;
72444    int i = 0, rc;
72445    do{
72446      rc = vdbeSorterIterRead(db, p, 1, &a);
72447      if( rc ) return rc;
72448      aVarint[(i++)&0xf] = a[0];
72449    }while( (a[0]&0x80)!=0 );
72450    sqlite3GetVarint(aVarint, pnOut);
72451  }
72452
72453  return SQLITE_OK;
72454}
72455
72456
72457/*
72458** Advance iterator pIter to the next key in its PMA. Return SQLITE_OK if
72459** no error occurs, or an SQLite error code if one does.
72460*/
72461static int vdbeSorterIterNext(
72462  sqlite3 *db,                    /* Database handle (for sqlite3DbMalloc() ) */
72463  VdbeSorterIter *pIter           /* Iterator to advance */
72464){
72465  int rc;                         /* Return Code */
72466  u64 nRec = 0;                   /* Size of record in bytes */
72467
72468  if( pIter->iReadOff>=pIter->iEof ){
72469    /* This is an EOF condition */
72470    vdbeSorterIterZero(db, pIter);
72471    return SQLITE_OK;
72472  }
72473
72474  rc = vdbeSorterIterVarint(db, pIter, &nRec);
72475  if( rc==SQLITE_OK ){
72476    pIter->nKey = (int)nRec;
72477    rc = vdbeSorterIterRead(db, pIter, (int)nRec, &pIter->aKey);
72478  }
72479
72480  return rc;
72481}
72482
72483/*
72484** Initialize iterator pIter to scan through the PMA stored in file pFile
72485** starting at offset iStart and ending at offset iEof-1. This function
72486** leaves the iterator pointing to the first key in the PMA (or EOF if the
72487** PMA is empty).
72488*/
72489static int vdbeSorterIterInit(
72490  sqlite3 *db,                    /* Database handle */
72491  const VdbeSorter *pSorter,      /* Sorter object */
72492  i64 iStart,                     /* Start offset in pFile */
72493  VdbeSorterIter *pIter,          /* Iterator to populate */
72494  i64 *pnByte                     /* IN/OUT: Increment this value by PMA size */
72495){
72496  int rc = SQLITE_OK;
72497  int nBuf;
72498
72499  nBuf = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
72500
72501  assert( pSorter->iWriteOff>iStart );
72502  assert( pIter->aAlloc==0 );
72503  assert( pIter->aBuffer==0 );
72504  pIter->pFile = pSorter->pTemp1;
72505  pIter->iReadOff = iStart;
72506  pIter->nAlloc = 128;
72507  pIter->aAlloc = (u8 *)sqlite3DbMallocRaw(db, pIter->nAlloc);
72508  pIter->nBuffer = nBuf;
72509  pIter->aBuffer = (u8 *)sqlite3DbMallocRaw(db, nBuf);
72510
72511  if( !pIter->aBuffer ){
72512    rc = SQLITE_NOMEM;
72513  }else{
72514    int iBuf;
72515
72516    iBuf = iStart % nBuf;
72517    if( iBuf ){
72518      int nRead = nBuf - iBuf;
72519      if( (iStart + nRead) > pSorter->iWriteOff ){
72520        nRead = (int)(pSorter->iWriteOff - iStart);
72521      }
72522      rc = sqlite3OsRead(
72523          pSorter->pTemp1, &pIter->aBuffer[iBuf], nRead, iStart
72524      );
72525      assert( rc!=SQLITE_IOERR_SHORT_READ );
72526    }
72527
72528    if( rc==SQLITE_OK ){
72529      u64 nByte;                       /* Size of PMA in bytes */
72530      pIter->iEof = pSorter->iWriteOff;
72531      rc = vdbeSorterIterVarint(db, pIter, &nByte);
72532      pIter->iEof = pIter->iReadOff + nByte;
72533      *pnByte += nByte;
72534    }
72535  }
72536
72537  if( rc==SQLITE_OK ){
72538    rc = vdbeSorterIterNext(db, pIter);
72539  }
72540  return rc;
72541}
72542
72543
72544/*
72545** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
72546** size nKey2 bytes).  Argument pKeyInfo supplies the collation functions
72547** used by the comparison. If an error occurs, return an SQLite error code.
72548** Otherwise, return SQLITE_OK and set *pRes to a negative, zero or positive
72549** value, depending on whether key1 is smaller, equal to or larger than key2.
72550**
72551** If the bOmitRowid argument is non-zero, assume both keys end in a rowid
72552** field. For the purposes of the comparison, ignore it. Also, if bOmitRowid
72553** is true and key1 contains even a single NULL value, it is considered to
72554** be less than key2. Even if key2 also contains NULL values.
72555**
72556** If pKey2 is passed a NULL pointer, then it is assumed that the pCsr->aSpace
72557** has been allocated and contains an unpacked record that is used as key2.
72558*/
72559static void vdbeSorterCompare(
72560  const VdbeCursor *pCsr,         /* Cursor object (for pKeyInfo) */
72561  int bOmitRowid,                 /* Ignore rowid field at end of keys */
72562  const void *pKey1, int nKey1,   /* Left side of comparison */
72563  const void *pKey2, int nKey2,   /* Right side of comparison */
72564  int *pRes                       /* OUT: Result of comparison */
72565){
72566  KeyInfo *pKeyInfo = pCsr->pKeyInfo;
72567  VdbeSorter *pSorter = pCsr->pSorter;
72568  UnpackedRecord *r2 = pSorter->pUnpacked;
72569  int i;
72570
72571  if( pKey2 ){
72572    sqlite3VdbeRecordUnpack(pKeyInfo, nKey2, pKey2, r2);
72573  }
72574
72575  if( bOmitRowid ){
72576    r2->nField = pKeyInfo->nField;
72577    assert( r2->nField>0 );
72578    for(i=0; i<r2->nField; i++){
72579      if( r2->aMem[i].flags & MEM_Null ){
72580        *pRes = -1;
72581        return;
72582      }
72583    }
72584    r2->flags |= UNPACKED_PREFIX_MATCH;
72585  }
72586
72587  *pRes = sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
72588}
72589
72590/*
72591** This function is called to compare two iterator keys when merging
72592** multiple b-tree segments. Parameter iOut is the index of the aTree[]
72593** value to recalculate.
72594*/
72595static int vdbeSorterDoCompare(const VdbeCursor *pCsr, int iOut){
72596  VdbeSorter *pSorter = pCsr->pSorter;
72597  int i1;
72598  int i2;
72599  int iRes;
72600  VdbeSorterIter *p1;
72601  VdbeSorterIter *p2;
72602
72603  assert( iOut<pSorter->nTree && iOut>0 );
72604
72605  if( iOut>=(pSorter->nTree/2) ){
72606    i1 = (iOut - pSorter->nTree/2) * 2;
72607    i2 = i1 + 1;
72608  }else{
72609    i1 = pSorter->aTree[iOut*2];
72610    i2 = pSorter->aTree[iOut*2+1];
72611  }
72612
72613  p1 = &pSorter->aIter[i1];
72614  p2 = &pSorter->aIter[i2];
72615
72616  if( p1->pFile==0 ){
72617    iRes = i2;
72618  }else if( p2->pFile==0 ){
72619    iRes = i1;
72620  }else{
72621    int res;
72622    assert( pCsr->pSorter->pUnpacked!=0 );  /* allocated in vdbeSorterMerge() */
72623    vdbeSorterCompare(
72624        pCsr, 0, p1->aKey, p1->nKey, p2->aKey, p2->nKey, &res
72625    );
72626    if( res<=0 ){
72627      iRes = i1;
72628    }else{
72629      iRes = i2;
72630    }
72631  }
72632
72633  pSorter->aTree[iOut] = iRes;
72634  return SQLITE_OK;
72635}
72636
72637/*
72638** Initialize the temporary index cursor just opened as a sorter cursor.
72639*/
72640SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *db, VdbeCursor *pCsr){
72641  int pgsz;                       /* Page size of main database */
72642  int mxCache;                    /* Cache size */
72643  VdbeSorter *pSorter;            /* The new sorter */
72644  char *d;                        /* Dummy */
72645
72646  assert( pCsr->pKeyInfo && pCsr->pBt==0 );
72647  pCsr->pSorter = pSorter = sqlite3DbMallocZero(db, sizeof(VdbeSorter));
72648  if( pSorter==0 ){
72649    return SQLITE_NOMEM;
72650  }
72651
72652  pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pCsr->pKeyInfo, 0, 0, &d);
72653  if( pSorter->pUnpacked==0 ) return SQLITE_NOMEM;
72654  assert( pSorter->pUnpacked==(UnpackedRecord *)d );
72655
72656  if( !sqlite3TempInMemory(db) ){
72657    pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
72658    pSorter->mnPmaSize = SORTER_MIN_WORKING * pgsz;
72659    mxCache = db->aDb[0].pSchema->cache_size;
72660    if( mxCache<SORTER_MIN_WORKING ) mxCache = SORTER_MIN_WORKING;
72661    pSorter->mxPmaSize = mxCache * pgsz;
72662  }
72663
72664  return SQLITE_OK;
72665}
72666
72667/*
72668** Free the list of sorted records starting at pRecord.
72669*/
72670static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
72671  SorterRecord *p;
72672  SorterRecord *pNext;
72673  for(p=pRecord; p; p=pNext){
72674    pNext = p->pNext;
72675    sqlite3DbFree(db, p);
72676  }
72677}
72678
72679/*
72680** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
72681*/
72682SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
72683  VdbeSorter *pSorter = pCsr->pSorter;
72684  if( pSorter ){
72685    if( pSorter->aIter ){
72686      int i;
72687      for(i=0; i<pSorter->nTree; i++){
72688        vdbeSorterIterZero(db, &pSorter->aIter[i]);
72689      }
72690      sqlite3DbFree(db, pSorter->aIter);
72691    }
72692    if( pSorter->pTemp1 ){
72693      sqlite3OsCloseFree(pSorter->pTemp1);
72694    }
72695    vdbeSorterRecordFree(db, pSorter->pRecord);
72696    sqlite3DbFree(db, pSorter->pUnpacked);
72697    sqlite3DbFree(db, pSorter);
72698    pCsr->pSorter = 0;
72699  }
72700}
72701
72702/*
72703** Allocate space for a file-handle and open a temporary file. If successful,
72704** set *ppFile to point to the malloc'd file-handle and return SQLITE_OK.
72705** Otherwise, set *ppFile to 0 and return an SQLite error code.
72706*/
72707static int vdbeSorterOpenTempFile(sqlite3 *db, sqlite3_file **ppFile){
72708  int dummy;
72709  return sqlite3OsOpenMalloc(db->pVfs, 0, ppFile,
72710      SQLITE_OPEN_TEMP_JOURNAL |
72711      SQLITE_OPEN_READWRITE    | SQLITE_OPEN_CREATE |
72712      SQLITE_OPEN_EXCLUSIVE    | SQLITE_OPEN_DELETEONCLOSE, &dummy
72713  );
72714}
72715
72716/*
72717** Merge the two sorted lists p1 and p2 into a single list.
72718** Set *ppOut to the head of the new list.
72719*/
72720static void vdbeSorterMerge(
72721  const VdbeCursor *pCsr,         /* For pKeyInfo */
72722  SorterRecord *p1,               /* First list to merge */
72723  SorterRecord *p2,               /* Second list to merge */
72724  SorterRecord **ppOut            /* OUT: Head of merged list */
72725){
72726  SorterRecord *pFinal = 0;
72727  SorterRecord **pp = &pFinal;
72728  void *pVal2 = p2 ? p2->pVal : 0;
72729
72730  while( p1 && p2 ){
72731    int res;
72732    vdbeSorterCompare(pCsr, 0, p1->pVal, p1->nVal, pVal2, p2->nVal, &res);
72733    if( res<=0 ){
72734      *pp = p1;
72735      pp = &p1->pNext;
72736      p1 = p1->pNext;
72737      pVal2 = 0;
72738    }else{
72739      *pp = p2;
72740       pp = &p2->pNext;
72741      p2 = p2->pNext;
72742      if( p2==0 ) break;
72743      pVal2 = p2->pVal;
72744    }
72745  }
72746  *pp = p1 ? p1 : p2;
72747  *ppOut = pFinal;
72748}
72749
72750/*
72751** Sort the linked list of records headed at pCsr->pRecord. Return SQLITE_OK
72752** if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if an error
72753** occurs.
72754*/
72755static int vdbeSorterSort(const VdbeCursor *pCsr){
72756  int i;
72757  SorterRecord **aSlot;
72758  SorterRecord *p;
72759  VdbeSorter *pSorter = pCsr->pSorter;
72760
72761  aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
72762  if( !aSlot ){
72763    return SQLITE_NOMEM;
72764  }
72765
72766  p = pSorter->pRecord;
72767  while( p ){
72768    SorterRecord *pNext = p->pNext;
72769    p->pNext = 0;
72770    for(i=0; aSlot[i]; i++){
72771      vdbeSorterMerge(pCsr, p, aSlot[i], &p);
72772      aSlot[i] = 0;
72773    }
72774    aSlot[i] = p;
72775    p = pNext;
72776  }
72777
72778  p = 0;
72779  for(i=0; i<64; i++){
72780    vdbeSorterMerge(pCsr, p, aSlot[i], &p);
72781  }
72782  pSorter->pRecord = p;
72783
72784  sqlite3_free(aSlot);
72785  return SQLITE_OK;
72786}
72787
72788/*
72789** Initialize a file-writer object.
72790*/
72791static void fileWriterInit(
72792  sqlite3 *db,                    /* Database (for malloc) */
72793  sqlite3_file *pFile,            /* File to write to */
72794  FileWriter *p,                  /* Object to populate */
72795  i64 iStart                      /* Offset of pFile to begin writing at */
72796){
72797  int nBuf = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
72798
72799  memset(p, 0, sizeof(FileWriter));
72800  p->aBuffer = (u8 *)sqlite3DbMallocRaw(db, nBuf);
72801  if( !p->aBuffer ){
72802    p->eFWErr = SQLITE_NOMEM;
72803  }else{
72804    p->iBufEnd = p->iBufStart = (iStart % nBuf);
72805    p->iWriteOff = iStart - p->iBufStart;
72806    p->nBuffer = nBuf;
72807    p->pFile = pFile;
72808  }
72809}
72810
72811/*
72812** Write nData bytes of data to the file-write object. Return SQLITE_OK
72813** if successful, or an SQLite error code if an error occurs.
72814*/
72815static void fileWriterWrite(FileWriter *p, u8 *pData, int nData){
72816  int nRem = nData;
72817  while( nRem>0 && p->eFWErr==0 ){
72818    int nCopy = nRem;
72819    if( nCopy>(p->nBuffer - p->iBufEnd) ){
72820      nCopy = p->nBuffer - p->iBufEnd;
72821    }
72822
72823    memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
72824    p->iBufEnd += nCopy;
72825    if( p->iBufEnd==p->nBuffer ){
72826      p->eFWErr = sqlite3OsWrite(p->pFile,
72827          &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
72828          p->iWriteOff + p->iBufStart
72829      );
72830      p->iBufStart = p->iBufEnd = 0;
72831      p->iWriteOff += p->nBuffer;
72832    }
72833    assert( p->iBufEnd<p->nBuffer );
72834
72835    nRem -= nCopy;
72836  }
72837}
72838
72839/*
72840** Flush any buffered data to disk and clean up the file-writer object.
72841** The results of using the file-writer after this call are undefined.
72842** Return SQLITE_OK if flushing the buffered data succeeds or is not
72843** required. Otherwise, return an SQLite error code.
72844**
72845** Before returning, set *piEof to the offset immediately following the
72846** last byte written to the file.
72847*/
72848static int fileWriterFinish(sqlite3 *db, FileWriter *p, i64 *piEof){
72849  int rc;
72850  if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
72851    p->eFWErr = sqlite3OsWrite(p->pFile,
72852        &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
72853        p->iWriteOff + p->iBufStart
72854    );
72855  }
72856  *piEof = (p->iWriteOff + p->iBufEnd);
72857  sqlite3DbFree(db, p->aBuffer);
72858  rc = p->eFWErr;
72859  memset(p, 0, sizeof(FileWriter));
72860  return rc;
72861}
72862
72863/*
72864** Write value iVal encoded as a varint to the file-write object. Return
72865** SQLITE_OK if successful, or an SQLite error code if an error occurs.
72866*/
72867static void fileWriterWriteVarint(FileWriter *p, u64 iVal){
72868  int nByte;
72869  u8 aByte[10];
72870  nByte = sqlite3PutVarint(aByte, iVal);
72871  fileWriterWrite(p, aByte, nByte);
72872}
72873
72874/*
72875** Write the current contents of the in-memory linked-list to a PMA. Return
72876** SQLITE_OK if successful, or an SQLite error code otherwise.
72877**
72878** The format of a PMA is:
72879**
72880**     * A varint. This varint contains the total number of bytes of content
72881**       in the PMA (not including the varint itself).
72882**
72883**     * One or more records packed end-to-end in order of ascending keys.
72884**       Each record consists of a varint followed by a blob of data (the
72885**       key). The varint is the number of bytes in the blob of data.
72886*/
72887static int vdbeSorterListToPMA(sqlite3 *db, const VdbeCursor *pCsr){
72888  int rc = SQLITE_OK;             /* Return code */
72889  VdbeSorter *pSorter = pCsr->pSorter;
72890  FileWriter writer;
72891
72892  memset(&writer, 0, sizeof(FileWriter));
72893
72894  if( pSorter->nInMemory==0 ){
72895    assert( pSorter->pRecord==0 );
72896    return rc;
72897  }
72898
72899  rc = vdbeSorterSort(pCsr);
72900
72901  /* If the first temporary PMA file has not been opened, open it now. */
72902  if( rc==SQLITE_OK && pSorter->pTemp1==0 ){
72903    rc = vdbeSorterOpenTempFile(db, &pSorter->pTemp1);
72904    assert( rc!=SQLITE_OK || pSorter->pTemp1 );
72905    assert( pSorter->iWriteOff==0 );
72906    assert( pSorter->nPMA==0 );
72907  }
72908
72909  if( rc==SQLITE_OK ){
72910    SorterRecord *p;
72911    SorterRecord *pNext = 0;
72912
72913    fileWriterInit(db, pSorter->pTemp1, &writer, pSorter->iWriteOff);
72914    pSorter->nPMA++;
72915    fileWriterWriteVarint(&writer, pSorter->nInMemory);
72916    for(p=pSorter->pRecord; p; p=pNext){
72917      pNext = p->pNext;
72918      fileWriterWriteVarint(&writer, p->nVal);
72919      fileWriterWrite(&writer, p->pVal, p->nVal);
72920      sqlite3DbFree(db, p);
72921    }
72922    pSorter->pRecord = p;
72923    rc = fileWriterFinish(db, &writer, &pSorter->iWriteOff);
72924  }
72925
72926  return rc;
72927}
72928
72929/*
72930** Add a record to the sorter.
72931*/
72932SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
72933  sqlite3 *db,                    /* Database handle */
72934  const VdbeCursor *pCsr,               /* Sorter cursor */
72935  Mem *pVal                       /* Memory cell containing record */
72936){
72937  VdbeSorter *pSorter = pCsr->pSorter;
72938  int rc = SQLITE_OK;             /* Return Code */
72939  SorterRecord *pNew;             /* New list element */
72940
72941  assert( pSorter );
72942  pSorter->nInMemory += sqlite3VarintLen(pVal->n) + pVal->n;
72943
72944  pNew = (SorterRecord *)sqlite3DbMallocRaw(db, pVal->n + sizeof(SorterRecord));
72945  if( pNew==0 ){
72946    rc = SQLITE_NOMEM;
72947  }else{
72948    pNew->pVal = (void *)&pNew[1];
72949    memcpy(pNew->pVal, pVal->z, pVal->n);
72950    pNew->nVal = pVal->n;
72951    pNew->pNext = pSorter->pRecord;
72952    pSorter->pRecord = pNew;
72953  }
72954
72955  /* See if the contents of the sorter should now be written out. They
72956  ** are written out when either of the following are true:
72957  **
72958  **   * The total memory allocated for the in-memory list is greater
72959  **     than (page-size * cache-size), or
72960  **
72961  **   * The total memory allocated for the in-memory list is greater
72962  **     than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
72963  */
72964  if( rc==SQLITE_OK && pSorter->mxPmaSize>0 && (
72965        (pSorter->nInMemory>pSorter->mxPmaSize)
72966     || (pSorter->nInMemory>pSorter->mnPmaSize && sqlite3HeapNearlyFull())
72967  )){
72968#ifdef SQLITE_DEBUG
72969    i64 nExpect = pSorter->iWriteOff
72970                + sqlite3VarintLen(pSorter->nInMemory)
72971                + pSorter->nInMemory;
72972#endif
72973    rc = vdbeSorterListToPMA(db, pCsr);
72974    pSorter->nInMemory = 0;
72975    assert( rc!=SQLITE_OK || (nExpect==pSorter->iWriteOff) );
72976  }
72977
72978  return rc;
72979}
72980
72981/*
72982** Helper function for sqlite3VdbeSorterRewind().
72983*/
72984static int vdbeSorterInitMerge(
72985  sqlite3 *db,                    /* Database handle */
72986  const VdbeCursor *pCsr,         /* Cursor handle for this sorter */
72987  i64 *pnByte                     /* Sum of bytes in all opened PMAs */
72988){
72989  VdbeSorter *pSorter = pCsr->pSorter;
72990  int rc = SQLITE_OK;             /* Return code */
72991  int i;                          /* Used to iterator through aIter[] */
72992  i64 nByte = 0;                  /* Total bytes in all opened PMAs */
72993
72994  /* Initialize the iterators. */
72995  for(i=0; i<SORTER_MAX_MERGE_COUNT; i++){
72996    VdbeSorterIter *pIter = &pSorter->aIter[i];
72997    rc = vdbeSorterIterInit(db, pSorter, pSorter->iReadOff, pIter, &nByte);
72998    pSorter->iReadOff = pIter->iEof;
72999    assert( rc!=SQLITE_OK || pSorter->iReadOff<=pSorter->iWriteOff );
73000    if( rc!=SQLITE_OK || pSorter->iReadOff>=pSorter->iWriteOff ) break;
73001  }
73002
73003  /* Initialize the aTree[] array. */
73004  for(i=pSorter->nTree-1; rc==SQLITE_OK && i>0; i--){
73005    rc = vdbeSorterDoCompare(pCsr, i);
73006  }
73007
73008  *pnByte = nByte;
73009  return rc;
73010}
73011
73012/*
73013** Once the sorter has been populated, this function is called to prepare
73014** for iterating through its contents in sorted order.
73015*/
73016SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
73017  VdbeSorter *pSorter = pCsr->pSorter;
73018  int rc;                         /* Return code */
73019  sqlite3_file *pTemp2 = 0;       /* Second temp file to use */
73020  i64 iWrite2 = 0;                /* Write offset for pTemp2 */
73021  int nIter;                      /* Number of iterators used */
73022  int nByte;                      /* Bytes of space required for aIter/aTree */
73023  int N = 2;                      /* Power of 2 >= nIter */
73024
73025  assert( pSorter );
73026
73027  /* If no data has been written to disk, then do not do so now. Instead,
73028  ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
73029  ** from the in-memory list.  */
73030  if( pSorter->nPMA==0 ){
73031    *pbEof = !pSorter->pRecord;
73032    assert( pSorter->aTree==0 );
73033    return vdbeSorterSort(pCsr);
73034  }
73035
73036  /* Write the current in-memory list to a PMA. */
73037  rc = vdbeSorterListToPMA(db, pCsr);
73038  if( rc!=SQLITE_OK ) return rc;
73039
73040  /* Allocate space for aIter[] and aTree[]. */
73041  nIter = pSorter->nPMA;
73042  if( nIter>SORTER_MAX_MERGE_COUNT ) nIter = SORTER_MAX_MERGE_COUNT;
73043  assert( nIter>0 );
73044  while( N<nIter ) N += N;
73045  nByte = N * (sizeof(int) + sizeof(VdbeSorterIter));
73046  pSorter->aIter = (VdbeSorterIter *)sqlite3DbMallocZero(db, nByte);
73047  if( !pSorter->aIter ) return SQLITE_NOMEM;
73048  pSorter->aTree = (int *)&pSorter->aIter[N];
73049  pSorter->nTree = N;
73050
73051  do {
73052    int iNew;                     /* Index of new, merged, PMA */
73053
73054    for(iNew=0;
73055        rc==SQLITE_OK && iNew*SORTER_MAX_MERGE_COUNT<pSorter->nPMA;
73056        iNew++
73057    ){
73058      int rc2;                    /* Return code from fileWriterFinish() */
73059      FileWriter writer;          /* Object used to write to disk */
73060      i64 nWrite;                 /* Number of bytes in new PMA */
73061
73062      memset(&writer, 0, sizeof(FileWriter));
73063
73064      /* If there are SORTER_MAX_MERGE_COUNT or less PMAs in file pTemp1,
73065      ** initialize an iterator for each of them and break out of the loop.
73066      ** These iterators will be incrementally merged as the VDBE layer calls
73067      ** sqlite3VdbeSorterNext().
73068      **
73069      ** Otherwise, if pTemp1 contains more than SORTER_MAX_MERGE_COUNT PMAs,
73070      ** initialize interators for SORTER_MAX_MERGE_COUNT of them. These PMAs
73071      ** are merged into a single PMA that is written to file pTemp2.
73072      */
73073      rc = vdbeSorterInitMerge(db, pCsr, &nWrite);
73074      assert( rc!=SQLITE_OK || pSorter->aIter[ pSorter->aTree[1] ].pFile );
73075      if( rc!=SQLITE_OK || pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
73076        break;
73077      }
73078
73079      /* Open the second temp file, if it is not already open. */
73080      if( pTemp2==0 ){
73081        assert( iWrite2==0 );
73082        rc = vdbeSorterOpenTempFile(db, &pTemp2);
73083      }
73084
73085      if( rc==SQLITE_OK ){
73086        int bEof = 0;
73087        fileWriterInit(db, pTemp2, &writer, iWrite2);
73088        fileWriterWriteVarint(&writer, nWrite);
73089        while( rc==SQLITE_OK && bEof==0 ){
73090          VdbeSorterIter *pIter = &pSorter->aIter[ pSorter->aTree[1] ];
73091          assert( pIter->pFile );
73092
73093          fileWriterWriteVarint(&writer, pIter->nKey);
73094          fileWriterWrite(&writer, pIter->aKey, pIter->nKey);
73095          rc = sqlite3VdbeSorterNext(db, pCsr, &bEof);
73096        }
73097        rc2 = fileWriterFinish(db, &writer, &iWrite2);
73098        if( rc==SQLITE_OK ) rc = rc2;
73099      }
73100    }
73101
73102    if( pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
73103      break;
73104    }else{
73105      sqlite3_file *pTmp = pSorter->pTemp1;
73106      pSorter->nPMA = iNew;
73107      pSorter->pTemp1 = pTemp2;
73108      pTemp2 = pTmp;
73109      pSorter->iWriteOff = iWrite2;
73110      pSorter->iReadOff = 0;
73111      iWrite2 = 0;
73112    }
73113  }while( rc==SQLITE_OK );
73114
73115  if( pTemp2 ){
73116    sqlite3OsCloseFree(pTemp2);
73117  }
73118  *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
73119  return rc;
73120}
73121
73122/*
73123** Advance to the next element in the sorter.
73124*/
73125SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
73126  VdbeSorter *pSorter = pCsr->pSorter;
73127  int rc;                         /* Return code */
73128
73129  if( pSorter->aTree ){
73130    int iPrev = pSorter->aTree[1];/* Index of iterator to advance */
73131    int i;                        /* Index of aTree[] to recalculate */
73132
73133    rc = vdbeSorterIterNext(db, &pSorter->aIter[iPrev]);
73134    for(i=(pSorter->nTree+iPrev)/2; rc==SQLITE_OK && i>0; i=i/2){
73135      rc = vdbeSorterDoCompare(pCsr, i);
73136    }
73137
73138    *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
73139  }else{
73140    SorterRecord *pFree = pSorter->pRecord;
73141    pSorter->pRecord = pFree->pNext;
73142    pFree->pNext = 0;
73143    vdbeSorterRecordFree(db, pFree);
73144    *pbEof = !pSorter->pRecord;
73145    rc = SQLITE_OK;
73146  }
73147  return rc;
73148}
73149
73150/*
73151** Return a pointer to a buffer owned by the sorter that contains the
73152** current key.
73153*/
73154static void *vdbeSorterRowkey(
73155  const VdbeSorter *pSorter,      /* Sorter object */
73156  int *pnKey                      /* OUT: Size of current key in bytes */
73157){
73158  void *pKey;
73159  if( pSorter->aTree ){
73160    VdbeSorterIter *pIter;
73161    pIter = &pSorter->aIter[ pSorter->aTree[1] ];
73162    *pnKey = pIter->nKey;
73163    pKey = pIter->aKey;
73164  }else{
73165    *pnKey = pSorter->pRecord->nVal;
73166    pKey = pSorter->pRecord->pVal;
73167  }
73168  return pKey;
73169}
73170
73171/*
73172** Copy the current sorter key into the memory cell pOut.
73173*/
73174SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
73175  VdbeSorter *pSorter = pCsr->pSorter;
73176  void *pKey; int nKey;           /* Sorter key to copy into pOut */
73177
73178  pKey = vdbeSorterRowkey(pSorter, &nKey);
73179  if( sqlite3VdbeMemGrow(pOut, nKey, 0) ){
73180    return SQLITE_NOMEM;
73181  }
73182  pOut->n = nKey;
73183  MemSetTypeFlag(pOut, MEM_Blob);
73184  memcpy(pOut->z, pKey, nKey);
73185
73186  return SQLITE_OK;
73187}
73188
73189/*
73190** Compare the key in memory cell pVal with the key that the sorter cursor
73191** passed as the first argument currently points to. For the purposes of
73192** the comparison, ignore the rowid field at the end of each record.
73193**
73194** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
73195** Otherwise, set *pRes to a negative, zero or positive value if the
73196** key in pVal is smaller than, equal to or larger than the current sorter
73197** key.
73198*/
73199SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
73200  const VdbeCursor *pCsr,         /* Sorter cursor */
73201  Mem *pVal,                      /* Value to compare to current sorter key */
73202  int *pRes                       /* OUT: Result of comparison */
73203){
73204  VdbeSorter *pSorter = pCsr->pSorter;
73205  void *pKey; int nKey;           /* Sorter key to compare pVal with */
73206
73207  pKey = vdbeSorterRowkey(pSorter, &nKey);
73208  vdbeSorterCompare(pCsr, 1, pVal->z, pVal->n, pKey, nKey, pRes);
73209  return SQLITE_OK;
73210}
73211
73212/************** End of vdbesort.c ********************************************/
73213/************** Begin file journal.c *****************************************/
73214/*
73215** 2007 August 22
73216**
73217** The author disclaims copyright to this source code.  In place of
73218** a legal notice, here is a blessing:
73219**
73220**    May you do good and not evil.
73221**    May you find forgiveness for yourself and forgive others.
73222**    May you share freely, never taking more than you give.
73223**
73224*************************************************************************
73225**
73226** This file implements a special kind of sqlite3_file object used
73227** by SQLite to create journal files if the atomic-write optimization
73228** is enabled.
73229**
73230** The distinctive characteristic of this sqlite3_file is that the
73231** actual on disk file is created lazily. When the file is created,
73232** the caller specifies a buffer size for an in-memory buffer to
73233** be used to service read() and write() requests. The actual file
73234** on disk is not created or populated until either:
73235**
73236**   1) The in-memory representation grows too large for the allocated
73237**      buffer, or
73238**   2) The sqlite3JournalCreate() function is called.
73239*/
73240#ifdef SQLITE_ENABLE_ATOMIC_WRITE
73241
73242
73243/*
73244** A JournalFile object is a subclass of sqlite3_file used by
73245** as an open file handle for journal files.
73246*/
73247struct JournalFile {
73248  sqlite3_io_methods *pMethod;    /* I/O methods on journal files */
73249  int nBuf;                       /* Size of zBuf[] in bytes */
73250  char *zBuf;                     /* Space to buffer journal writes */
73251  int iSize;                      /* Amount of zBuf[] currently used */
73252  int flags;                      /* xOpen flags */
73253  sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
73254  sqlite3_file *pReal;            /* The "real" underlying file descriptor */
73255  const char *zJournal;           /* Name of the journal file */
73256};
73257typedef struct JournalFile JournalFile;
73258
73259/*
73260** If it does not already exists, create and populate the on-disk file
73261** for JournalFile p.
73262*/
73263static int createFile(JournalFile *p){
73264  int rc = SQLITE_OK;
73265  if( !p->pReal ){
73266    sqlite3_file *pReal = (sqlite3_file *)&p[1];
73267    rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
73268    if( rc==SQLITE_OK ){
73269      p->pReal = pReal;
73270      if( p->iSize>0 ){
73271        assert(p->iSize<=p->nBuf);
73272        rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
73273      }
73274      if( rc!=SQLITE_OK ){
73275        /* If an error occurred while writing to the file, close it before
73276        ** returning. This way, SQLite uses the in-memory journal data to
73277        ** roll back changes made to the internal page-cache before this
73278        ** function was called.  */
73279        sqlite3OsClose(pReal);
73280        p->pReal = 0;
73281      }
73282    }
73283  }
73284  return rc;
73285}
73286
73287/*
73288** Close the file.
73289*/
73290static int jrnlClose(sqlite3_file *pJfd){
73291  JournalFile *p = (JournalFile *)pJfd;
73292  if( p->pReal ){
73293    sqlite3OsClose(p->pReal);
73294  }
73295  sqlite3_free(p->zBuf);
73296  return SQLITE_OK;
73297}
73298
73299/*
73300** Read data from the file.
73301*/
73302static int jrnlRead(
73303  sqlite3_file *pJfd,    /* The journal file from which to read */
73304  void *zBuf,            /* Put the results here */
73305  int iAmt,              /* Number of bytes to read */
73306  sqlite_int64 iOfst     /* Begin reading at this offset */
73307){
73308  int rc = SQLITE_OK;
73309  JournalFile *p = (JournalFile *)pJfd;
73310  if( p->pReal ){
73311    rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
73312  }else if( (iAmt+iOfst)>p->iSize ){
73313    rc = SQLITE_IOERR_SHORT_READ;
73314  }else{
73315    memcpy(zBuf, &p->zBuf[iOfst], iAmt);
73316  }
73317  return rc;
73318}
73319
73320/*
73321** Write data to the file.
73322*/
73323static int jrnlWrite(
73324  sqlite3_file *pJfd,    /* The journal file into which to write */
73325  const void *zBuf,      /* Take data to be written from here */
73326  int iAmt,              /* Number of bytes to write */
73327  sqlite_int64 iOfst     /* Begin writing at this offset into the file */
73328){
73329  int rc = SQLITE_OK;
73330  JournalFile *p = (JournalFile *)pJfd;
73331  if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
73332    rc = createFile(p);
73333  }
73334  if( rc==SQLITE_OK ){
73335    if( p->pReal ){
73336      rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
73337    }else{
73338      memcpy(&p->zBuf[iOfst], zBuf, iAmt);
73339      if( p->iSize<(iOfst+iAmt) ){
73340        p->iSize = (iOfst+iAmt);
73341      }
73342    }
73343  }
73344  return rc;
73345}
73346
73347/*
73348** Truncate the file.
73349*/
73350static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
73351  int rc = SQLITE_OK;
73352  JournalFile *p = (JournalFile *)pJfd;
73353  if( p->pReal ){
73354    rc = sqlite3OsTruncate(p->pReal, size);
73355  }else if( size<p->iSize ){
73356    p->iSize = size;
73357  }
73358  return rc;
73359}
73360
73361/*
73362** Sync the file.
73363*/
73364static int jrnlSync(sqlite3_file *pJfd, int flags){
73365  int rc;
73366  JournalFile *p = (JournalFile *)pJfd;
73367  if( p->pReal ){
73368    rc = sqlite3OsSync(p->pReal, flags);
73369  }else{
73370    rc = SQLITE_OK;
73371  }
73372  return rc;
73373}
73374
73375/*
73376** Query the size of the file in bytes.
73377*/
73378static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
73379  int rc = SQLITE_OK;
73380  JournalFile *p = (JournalFile *)pJfd;
73381  if( p->pReal ){
73382    rc = sqlite3OsFileSize(p->pReal, pSize);
73383  }else{
73384    *pSize = (sqlite_int64) p->iSize;
73385  }
73386  return rc;
73387}
73388
73389/*
73390** Table of methods for JournalFile sqlite3_file object.
73391*/
73392static struct sqlite3_io_methods JournalFileMethods = {
73393  1,             /* iVersion */
73394  jrnlClose,     /* xClose */
73395  jrnlRead,      /* xRead */
73396  jrnlWrite,     /* xWrite */
73397  jrnlTruncate,  /* xTruncate */
73398  jrnlSync,      /* xSync */
73399  jrnlFileSize,  /* xFileSize */
73400  0,             /* xLock */
73401  0,             /* xUnlock */
73402  0,             /* xCheckReservedLock */
73403  0,             /* xFileControl */
73404  0,             /* xSectorSize */
73405  0,             /* xDeviceCharacteristics */
73406  0,             /* xShmMap */
73407  0,             /* xShmLock */
73408  0,             /* xShmBarrier */
73409  0              /* xShmUnmap */
73410};
73411
73412/*
73413** Open a journal file.
73414*/
73415SQLITE_PRIVATE int sqlite3JournalOpen(
73416  sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
73417  const char *zName,         /* Name of the journal file */
73418  sqlite3_file *pJfd,        /* Preallocated, blank file handle */
73419  int flags,                 /* Opening flags */
73420  int nBuf                   /* Bytes buffered before opening the file */
73421){
73422  JournalFile *p = (JournalFile *)pJfd;
73423  memset(p, 0, sqlite3JournalSize(pVfs));
73424  if( nBuf>0 ){
73425    p->zBuf = sqlite3MallocZero(nBuf);
73426    if( !p->zBuf ){
73427      return SQLITE_NOMEM;
73428    }
73429  }else{
73430    return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
73431  }
73432  p->pMethod = &JournalFileMethods;
73433  p->nBuf = nBuf;
73434  p->flags = flags;
73435  p->zJournal = zName;
73436  p->pVfs = pVfs;
73437  return SQLITE_OK;
73438}
73439
73440/*
73441** If the argument p points to a JournalFile structure, and the underlying
73442** file has not yet been created, create it now.
73443*/
73444SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
73445  if( p->pMethods!=&JournalFileMethods ){
73446    return SQLITE_OK;
73447  }
73448  return createFile((JournalFile *)p);
73449}
73450
73451/*
73452** The file-handle passed as the only argument is guaranteed to be an open
73453** file. It may or may not be of class JournalFile. If the file is a
73454** JournalFile, and the underlying file on disk has not yet been opened,
73455** return 0. Otherwise, return 1.
73456*/
73457SQLITE_PRIVATE int sqlite3JournalExists(sqlite3_file *p){
73458  return (p->pMethods!=&JournalFileMethods || ((JournalFile *)p)->pReal!=0);
73459}
73460
73461/*
73462** Return the number of bytes required to store a JournalFile that uses vfs
73463** pVfs to create the underlying on-disk files.
73464*/
73465SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
73466  return (pVfs->szOsFile+sizeof(JournalFile));
73467}
73468#endif
73469
73470/************** End of journal.c *********************************************/
73471/************** Begin file memjournal.c **************************************/
73472/*
73473** 2008 October 7
73474**
73475** The author disclaims copyright to this source code.  In place of
73476** a legal notice, here is a blessing:
73477**
73478**    May you do good and not evil.
73479**    May you find forgiveness for yourself and forgive others.
73480**    May you share freely, never taking more than you give.
73481**
73482*************************************************************************
73483**
73484** This file contains code use to implement an in-memory rollback journal.
73485** The in-memory rollback journal is used to journal transactions for
73486** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
73487*/
73488
73489/* Forward references to internal structures */
73490typedef struct MemJournal MemJournal;
73491typedef struct FilePoint FilePoint;
73492typedef struct FileChunk FileChunk;
73493
73494/* Space to hold the rollback journal is allocated in increments of
73495** this many bytes.
73496**
73497** The size chosen is a little less than a power of two.  That way,
73498** the FileChunk object will have a size that almost exactly fills
73499** a power-of-two allocation.  This mimimizes wasted space in power-of-two
73500** memory allocators.
73501*/
73502#define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
73503
73504/* Macro to find the minimum of two numeric values.
73505*/
73506#ifndef MIN
73507# define MIN(x,y) ((x)<(y)?(x):(y))
73508#endif
73509
73510/*
73511** The rollback journal is composed of a linked list of these structures.
73512*/
73513struct FileChunk {
73514  FileChunk *pNext;               /* Next chunk in the journal */
73515  u8 zChunk[JOURNAL_CHUNKSIZE];   /* Content of this chunk */
73516};
73517
73518/*
73519** An instance of this object serves as a cursor into the rollback journal.
73520** The cursor can be either for reading or writing.
73521*/
73522struct FilePoint {
73523  sqlite3_int64 iOffset;          /* Offset from the beginning of the file */
73524  FileChunk *pChunk;              /* Specific chunk into which cursor points */
73525};
73526
73527/*
73528** This subclass is a subclass of sqlite3_file.  Each open memory-journal
73529** is an instance of this class.
73530*/
73531struct MemJournal {
73532  sqlite3_io_methods *pMethod;    /* Parent class. MUST BE FIRST */
73533  FileChunk *pFirst;              /* Head of in-memory chunk-list */
73534  FilePoint endpoint;             /* Pointer to the end of the file */
73535  FilePoint readpoint;            /* Pointer to the end of the last xRead() */
73536};
73537
73538/*
73539** Read data from the in-memory journal file.  This is the implementation
73540** of the sqlite3_vfs.xRead method.
73541*/
73542static int memjrnlRead(
73543  sqlite3_file *pJfd,    /* The journal file from which to read */
73544  void *zBuf,            /* Put the results here */
73545  int iAmt,              /* Number of bytes to read */
73546  sqlite_int64 iOfst     /* Begin reading at this offset */
73547){
73548  MemJournal *p = (MemJournal *)pJfd;
73549  u8 *zOut = zBuf;
73550  int nRead = iAmt;
73551  int iChunkOffset;
73552  FileChunk *pChunk;
73553
73554  /* SQLite never tries to read past the end of a rollback journal file */
73555  assert( iOfst+iAmt<=p->endpoint.iOffset );
73556
73557  if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
73558    sqlite3_int64 iOff = 0;
73559    for(pChunk=p->pFirst;
73560        ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
73561        pChunk=pChunk->pNext
73562    ){
73563      iOff += JOURNAL_CHUNKSIZE;
73564    }
73565  }else{
73566    pChunk = p->readpoint.pChunk;
73567  }
73568
73569  iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
73570  do {
73571    int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
73572    int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
73573    memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
73574    zOut += nCopy;
73575    nRead -= iSpace;
73576    iChunkOffset = 0;
73577  } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
73578  p->readpoint.iOffset = iOfst+iAmt;
73579  p->readpoint.pChunk = pChunk;
73580
73581  return SQLITE_OK;
73582}
73583
73584/*
73585** Write data to the file.
73586*/
73587static int memjrnlWrite(
73588  sqlite3_file *pJfd,    /* The journal file into which to write */
73589  const void *zBuf,      /* Take data to be written from here */
73590  int iAmt,              /* Number of bytes to write */
73591  sqlite_int64 iOfst     /* Begin writing at this offset into the file */
73592){
73593  MemJournal *p = (MemJournal *)pJfd;
73594  int nWrite = iAmt;
73595  u8 *zWrite = (u8 *)zBuf;
73596
73597  /* An in-memory journal file should only ever be appended to. Random
73598  ** access writes are not required by sqlite.
73599  */
73600  assert( iOfst==p->endpoint.iOffset );
73601  UNUSED_PARAMETER(iOfst);
73602
73603  while( nWrite>0 ){
73604    FileChunk *pChunk = p->endpoint.pChunk;
73605    int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
73606    int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
73607
73608    if( iChunkOffset==0 ){
73609      /* New chunk is required to extend the file. */
73610      FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
73611      if( !pNew ){
73612        return SQLITE_IOERR_NOMEM;
73613      }
73614      pNew->pNext = 0;
73615      if( pChunk ){
73616        assert( p->pFirst );
73617        pChunk->pNext = pNew;
73618      }else{
73619        assert( !p->pFirst );
73620        p->pFirst = pNew;
73621      }
73622      p->endpoint.pChunk = pNew;
73623    }
73624
73625    memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
73626    zWrite += iSpace;
73627    nWrite -= iSpace;
73628    p->endpoint.iOffset += iSpace;
73629  }
73630
73631  return SQLITE_OK;
73632}
73633
73634/*
73635** Truncate the file.
73636*/
73637static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
73638  MemJournal *p = (MemJournal *)pJfd;
73639  FileChunk *pChunk;
73640  assert(size==0);
73641  UNUSED_PARAMETER(size);
73642  pChunk = p->pFirst;
73643  while( pChunk ){
73644    FileChunk *pTmp = pChunk;
73645    pChunk = pChunk->pNext;
73646    sqlite3_free(pTmp);
73647  }
73648  sqlite3MemJournalOpen(pJfd);
73649  return SQLITE_OK;
73650}
73651
73652/*
73653** Close the file.
73654*/
73655static int memjrnlClose(sqlite3_file *pJfd){
73656  memjrnlTruncate(pJfd, 0);
73657  return SQLITE_OK;
73658}
73659
73660
73661/*
73662** Sync the file.
73663**
73664** Syncing an in-memory journal is a no-op.  And, in fact, this routine
73665** is never called in a working implementation.  This implementation
73666** exists purely as a contingency, in case some malfunction in some other
73667** part of SQLite causes Sync to be called by mistake.
73668*/
73669static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
73670  UNUSED_PARAMETER2(NotUsed, NotUsed2);
73671  return SQLITE_OK;
73672}
73673
73674/*
73675** Query the size of the file in bytes.
73676*/
73677static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
73678  MemJournal *p = (MemJournal *)pJfd;
73679  *pSize = (sqlite_int64) p->endpoint.iOffset;
73680  return SQLITE_OK;
73681}
73682
73683/*
73684** Table of methods for MemJournal sqlite3_file object.
73685*/
73686static const struct sqlite3_io_methods MemJournalMethods = {
73687  1,                /* iVersion */
73688  memjrnlClose,     /* xClose */
73689  memjrnlRead,      /* xRead */
73690  memjrnlWrite,     /* xWrite */
73691  memjrnlTruncate,  /* xTruncate */
73692  memjrnlSync,      /* xSync */
73693  memjrnlFileSize,  /* xFileSize */
73694  0,                /* xLock */
73695  0,                /* xUnlock */
73696  0,                /* xCheckReservedLock */
73697  0,                /* xFileControl */
73698  0,                /* xSectorSize */
73699  0,                /* xDeviceCharacteristics */
73700  0,                /* xShmMap */
73701  0,                /* xShmLock */
73702  0,                /* xShmBarrier */
73703  0,                /* xShmUnmap */
73704  0,                /* xFetch */
73705  0                 /* xUnfetch */
73706};
73707
73708/*
73709** Open a journal file.
73710*/
73711SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
73712  MemJournal *p = (MemJournal *)pJfd;
73713  assert( EIGHT_BYTE_ALIGNMENT(p) );
73714  memset(p, 0, sqlite3MemJournalSize());
73715  p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
73716}
73717
73718/*
73719** Return true if the file-handle passed as an argument is
73720** an in-memory journal
73721*/
73722SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
73723  return pJfd->pMethods==&MemJournalMethods;
73724}
73725
73726/*
73727** Return the number of bytes required to store a MemJournal file descriptor.
73728*/
73729SQLITE_PRIVATE int sqlite3MemJournalSize(void){
73730  return sizeof(MemJournal);
73731}
73732
73733/************** End of memjournal.c ******************************************/
73734/************** Begin file walker.c ******************************************/
73735/*
73736** 2008 August 16
73737**
73738** The author disclaims copyright to this source code.  In place of
73739** a legal notice, here is a blessing:
73740**
73741**    May you do good and not evil.
73742**    May you find forgiveness for yourself and forgive others.
73743**    May you share freely, never taking more than you give.
73744**
73745*************************************************************************
73746** This file contains routines used for walking the parser tree for
73747** an SQL statement.
73748*/
73749/* #include <stdlib.h> */
73750/* #include <string.h> */
73751
73752
73753/*
73754** Walk an expression tree.  Invoke the callback once for each node
73755** of the expression, while decending.  (In other words, the callback
73756** is invoked before visiting children.)
73757**
73758** The return value from the callback should be one of the WRC_*
73759** constants to specify how to proceed with the walk.
73760**
73761**    WRC_Continue      Continue descending down the tree.
73762**
73763**    WRC_Prune         Do not descend into child nodes.  But allow
73764**                      the walk to continue with sibling nodes.
73765**
73766**    WRC_Abort         Do no more callbacks.  Unwind the stack and
73767**                      return the top-level walk call.
73768**
73769** The return value from this routine is WRC_Abort to abandon the tree walk
73770** and WRC_Continue to continue.
73771*/
73772SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
73773  int rc;
73774  if( pExpr==0 ) return WRC_Continue;
73775  testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
73776  testcase( ExprHasProperty(pExpr, EP_Reduced) );
73777  rc = pWalker->xExprCallback(pWalker, pExpr);
73778  if( rc==WRC_Continue
73779              && !ExprHasAnyProperty(pExpr,EP_TokenOnly) ){
73780    if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
73781    if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
73782    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
73783      if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
73784    }else{
73785      if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
73786    }
73787  }
73788  return rc & WRC_Abort;
73789}
73790
73791/*
73792** Call sqlite3WalkExpr() for every expression in list p or until
73793** an abort request is seen.
73794*/
73795SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
73796  int i;
73797  struct ExprList_item *pItem;
73798  if( p ){
73799    for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
73800      if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
73801    }
73802  }
73803  return WRC_Continue;
73804}
73805
73806/*
73807** Walk all expressions associated with SELECT statement p.  Do
73808** not invoke the SELECT callback on p, but do (of course) invoke
73809** any expr callbacks and SELECT callbacks that come from subqueries.
73810** Return WRC_Abort or WRC_Continue.
73811*/
73812SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
73813  if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
73814  if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
73815  if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
73816  if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
73817  if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
73818  if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
73819  if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
73820  return WRC_Continue;
73821}
73822
73823/*
73824** Walk the parse trees associated with all subqueries in the
73825** FROM clause of SELECT statement p.  Do not invoke the select
73826** callback on p, but do invoke it on each FROM clause subquery
73827** and on any subqueries further down in the tree.  Return
73828** WRC_Abort or WRC_Continue;
73829*/
73830SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
73831  SrcList *pSrc;
73832  int i;
73833  struct SrcList_item *pItem;
73834
73835  pSrc = p->pSrc;
73836  if( ALWAYS(pSrc) ){
73837    for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
73838      if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
73839        return WRC_Abort;
73840      }
73841    }
73842  }
73843  return WRC_Continue;
73844}
73845
73846/*
73847** Call sqlite3WalkExpr() for every expression in Select statement p.
73848** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
73849** on the compound select chain, p->pPrior.  Invoke the xSelectCallback()
73850** either before or after the walk of expressions and FROM clause, depending
73851** on whether pWalker->bSelectDepthFirst is false or true, respectively.
73852**
73853** Return WRC_Continue under normal conditions.  Return WRC_Abort if
73854** there is an abort request.
73855**
73856** If the Walker does not have an xSelectCallback() then this routine
73857** is a no-op returning WRC_Continue.
73858*/
73859SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
73860  int rc;
73861  if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue;
73862  rc = WRC_Continue;
73863  pWalker->walkerDepth++;
73864  while( p ){
73865    if( !pWalker->bSelectDepthFirst ){
73866       rc = pWalker->xSelectCallback(pWalker, p);
73867       if( rc ) break;
73868    }
73869    if( sqlite3WalkSelectExpr(pWalker, p)
73870     || sqlite3WalkSelectFrom(pWalker, p)
73871    ){
73872      pWalker->walkerDepth--;
73873      return WRC_Abort;
73874    }
73875    if( pWalker->bSelectDepthFirst ){
73876      rc = pWalker->xSelectCallback(pWalker, p);
73877      /* Depth-first search is currently only used for
73878      ** selectAddSubqueryTypeInfo() and that routine always returns
73879      ** WRC_Continue (0).  So the following branch is never taken. */
73880      if( NEVER(rc) ) break;
73881    }
73882    p = p->pPrior;
73883  }
73884  pWalker->walkerDepth--;
73885  return rc & WRC_Abort;
73886}
73887
73888/************** End of walker.c **********************************************/
73889/************** Begin file resolve.c *****************************************/
73890/*
73891** 2008 August 18
73892**
73893** The author disclaims copyright to this source code.  In place of
73894** a legal notice, here is a blessing:
73895**
73896**    May you do good and not evil.
73897**    May you find forgiveness for yourself and forgive others.
73898**    May you share freely, never taking more than you give.
73899**
73900*************************************************************************
73901**
73902** This file contains routines used for walking the parser tree and
73903** resolve all identifiers by associating them with a particular
73904** table and column.
73905*/
73906/* #include <stdlib.h> */
73907/* #include <string.h> */
73908
73909/*
73910** Walk the expression tree pExpr and increase the aggregate function
73911** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
73912** This needs to occur when copying a TK_AGG_FUNCTION node from an
73913** outer query into an inner subquery.
73914**
73915** incrAggFunctionDepth(pExpr,n) is the main routine.  incrAggDepth(..)
73916** is a helper function - a callback for the tree walker.
73917*/
73918static int incrAggDepth(Walker *pWalker, Expr *pExpr){
73919  if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.i;
73920  return WRC_Continue;
73921}
73922static void incrAggFunctionDepth(Expr *pExpr, int N){
73923  if( N>0 ){
73924    Walker w;
73925    memset(&w, 0, sizeof(w));
73926    w.xExprCallback = incrAggDepth;
73927    w.u.i = N;
73928    sqlite3WalkExpr(&w, pExpr);
73929  }
73930}
73931
73932/*
73933** Turn the pExpr expression into an alias for the iCol-th column of the
73934** result set in pEList.
73935**
73936** If the result set column is a simple column reference, then this routine
73937** makes an exact copy.  But for any other kind of expression, this
73938** routine make a copy of the result set column as the argument to the
73939** TK_AS operator.  The TK_AS operator causes the expression to be
73940** evaluated just once and then reused for each alias.
73941**
73942** The reason for suppressing the TK_AS term when the expression is a simple
73943** column reference is so that the column reference will be recognized as
73944** usable by indices within the WHERE clause processing logic.
73945**
73946** Hack:  The TK_AS operator is inhibited if zType[0]=='G'.  This means
73947** that in a GROUP BY clause, the expression is evaluated twice.  Hence:
73948**
73949**     SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
73950**
73951** Is equivalent to:
73952**
73953**     SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
73954**
73955** The result of random()%5 in the GROUP BY clause is probably different
73956** from the result in the result-set.  We might fix this someday.  Or
73957** then again, we might not...
73958**
73959** If the reference is followed by a COLLATE operator, then make sure
73960** the COLLATE operator is preserved.  For example:
73961**
73962**     SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
73963**
73964** Should be transformed into:
73965**
73966**     SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
73967**
73968** The nSubquery parameter specifies how many levels of subquery the
73969** alias is removed from the original expression.  The usually value is
73970** zero but it might be more if the alias is contained within a subquery
73971** of the original expression.  The Expr.op2 field of TK_AGG_FUNCTION
73972** structures must be increased by the nSubquery amount.
73973*/
73974static void resolveAlias(
73975  Parse *pParse,         /* Parsing context */
73976  ExprList *pEList,      /* A result set */
73977  int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
73978  Expr *pExpr,           /* Transform this into an alias to the result set */
73979  const char *zType,     /* "GROUP" or "ORDER" or "" */
73980  int nSubquery          /* Number of subqueries that the label is moving */
73981){
73982  Expr *pOrig;           /* The iCol-th column of the result set */
73983  Expr *pDup;            /* Copy of pOrig */
73984  sqlite3 *db;           /* The database connection */
73985
73986  assert( iCol>=0 && iCol<pEList->nExpr );
73987  pOrig = pEList->a[iCol].pExpr;
73988  assert( pOrig!=0 );
73989  assert( pOrig->flags & EP_Resolved );
73990  db = pParse->db;
73991  pDup = sqlite3ExprDup(db, pOrig, 0);
73992  if( pDup==0 ) return;
73993  if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
73994    incrAggFunctionDepth(pDup, nSubquery);
73995    pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
73996    if( pDup==0 ) return;
73997    if( pEList->a[iCol].iAlias==0 ){
73998      pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
73999    }
74000    pDup->iTable = pEList->a[iCol].iAlias;
74001  }
74002  if( pExpr->op==TK_COLLATE ){
74003    pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
74004  }
74005
74006  /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
74007  ** prevents ExprDelete() from deleting the Expr structure itself,
74008  ** allowing it to be repopulated by the memcpy() on the following line.
74009  ** The pExpr->u.zToken might point into memory that will be freed by the
74010  ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
74011  ** make a copy of the token before doing the sqlite3DbFree().
74012  */
74013  ExprSetProperty(pExpr, EP_Static);
74014  sqlite3ExprDelete(db, pExpr);
74015  memcpy(pExpr, pDup, sizeof(*pExpr));
74016  if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
74017    assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
74018    pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
74019    pExpr->flags2 |= EP2_MallocedToken;
74020  }
74021  sqlite3DbFree(db, pDup);
74022}
74023
74024
74025/*
74026** Return TRUE if the name zCol occurs anywhere in the USING clause.
74027**
74028** Return FALSE if the USING clause is NULL or if it does not contain
74029** zCol.
74030*/
74031static int nameInUsingClause(IdList *pUsing, const char *zCol){
74032  if( pUsing ){
74033    int k;
74034    for(k=0; k<pUsing->nId; k++){
74035      if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
74036    }
74037  }
74038  return 0;
74039}
74040
74041/*
74042** Subqueries stores the original database, table and column names for their
74043** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
74044** Check to see if the zSpan given to this routine matches the zDb, zTab,
74045** and zCol.  If any of zDb, zTab, and zCol are NULL then those fields will
74046** match anything.
74047*/
74048SQLITE_PRIVATE int sqlite3MatchSpanName(
74049  const char *zSpan,
74050  const char *zCol,
74051  const char *zTab,
74052  const char *zDb
74053){
74054  int n;
74055  for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
74056  if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
74057    return 0;
74058  }
74059  zSpan += n+1;
74060  for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
74061  if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
74062    return 0;
74063  }
74064  zSpan += n+1;
74065  if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
74066    return 0;
74067  }
74068  return 1;
74069}
74070
74071/*
74072** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
74073** that name in the set of source tables in pSrcList and make the pExpr
74074** expression node refer back to that source column.  The following changes
74075** are made to pExpr:
74076**
74077**    pExpr->iDb           Set the index in db->aDb[] of the database X
74078**                         (even if X is implied).
74079**    pExpr->iTable        Set to the cursor number for the table obtained
74080**                         from pSrcList.
74081**    pExpr->pTab          Points to the Table structure of X.Y (even if
74082**                         X and/or Y are implied.)
74083**    pExpr->iColumn       Set to the column number within the table.
74084**    pExpr->op            Set to TK_COLUMN.
74085**    pExpr->pLeft         Any expression this points to is deleted
74086**    pExpr->pRight        Any expression this points to is deleted.
74087**
74088** The zDb variable is the name of the database (the "X").  This value may be
74089** NULL meaning that name is of the form Y.Z or Z.  Any available database
74090** can be used.  The zTable variable is the name of the table (the "Y").  This
74091** value can be NULL if zDb is also NULL.  If zTable is NULL it
74092** means that the form of the name is Z and that columns from any table
74093** can be used.
74094**
74095** If the name cannot be resolved unambiguously, leave an error message
74096** in pParse and return WRC_Abort.  Return WRC_Prune on success.
74097*/
74098static int lookupName(
74099  Parse *pParse,       /* The parsing context */
74100  const char *zDb,     /* Name of the database containing table, or NULL */
74101  const char *zTab,    /* Name of table containing column, or NULL */
74102  const char *zCol,    /* Name of the column. */
74103  NameContext *pNC,    /* The name context used to resolve the name */
74104  Expr *pExpr          /* Make this EXPR node point to the selected column */
74105){
74106  int i, j;                         /* Loop counters */
74107  int cnt = 0;                      /* Number of matching column names */
74108  int cntTab = 0;                   /* Number of matching table names */
74109  int nSubquery = 0;                /* How many levels of subquery */
74110  sqlite3 *db = pParse->db;         /* The database connection */
74111  struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
74112  struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
74113  NameContext *pTopNC = pNC;        /* First namecontext in the list */
74114  Schema *pSchema = 0;              /* Schema of the expression */
74115  int isTrigger = 0;
74116
74117  assert( pNC );     /* the name context cannot be NULL. */
74118  assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
74119  assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
74120
74121  /* Initialize the node to no-match */
74122  pExpr->iTable = -1;
74123  pExpr->pTab = 0;
74124  ExprSetIrreducible(pExpr);
74125
74126  /* Translate the schema name in zDb into a pointer to the corresponding
74127  ** schema.  If not found, pSchema will remain NULL and nothing will match
74128  ** resulting in an appropriate error message toward the end of this routine
74129  */
74130  if( zDb ){
74131    for(i=0; i<db->nDb; i++){
74132      assert( db->aDb[i].zName );
74133      if( sqlite3StrICmp(db->aDb[i].zName,zDb)==0 ){
74134        pSchema = db->aDb[i].pSchema;
74135        break;
74136      }
74137    }
74138  }
74139
74140  /* Start at the inner-most context and move outward until a match is found */
74141  while( pNC && cnt==0 ){
74142    ExprList *pEList;
74143    SrcList *pSrcList = pNC->pSrcList;
74144
74145    if( pSrcList ){
74146      for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
74147        Table *pTab;
74148        Column *pCol;
74149
74150        pTab = pItem->pTab;
74151        assert( pTab!=0 && pTab->zName!=0 );
74152        assert( pTab->nCol>0 );
74153        if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
74154          int hit = 0;
74155          pEList = pItem->pSelect->pEList;
74156          for(j=0; j<pEList->nExpr; j++){
74157            if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
74158              cnt++;
74159              cntTab = 2;
74160              pMatch = pItem;
74161              pExpr->iColumn = j;
74162              hit = 1;
74163            }
74164          }
74165          if( hit || zTab==0 ) continue;
74166        }
74167        if( zDb && pTab->pSchema!=pSchema ){
74168          continue;
74169        }
74170        if( zTab ){
74171          const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
74172          assert( zTabName!=0 );
74173          if( sqlite3StrICmp(zTabName, zTab)!=0 ){
74174            continue;
74175          }
74176        }
74177        if( 0==(cntTab++) ){
74178          pMatch = pItem;
74179        }
74180        for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
74181          if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
74182            /* If there has been exactly one prior match and this match
74183            ** is for the right-hand table of a NATURAL JOIN or is in a
74184            ** USING clause, then skip this match.
74185            */
74186            if( cnt==1 ){
74187              if( pItem->jointype & JT_NATURAL ) continue;
74188              if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
74189            }
74190            cnt++;
74191            pMatch = pItem;
74192            /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
74193            pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
74194            break;
74195          }
74196        }
74197      }
74198      if( pMatch ){
74199        pExpr->iTable = pMatch->iCursor;
74200        pExpr->pTab = pMatch->pTab;
74201        pSchema = pExpr->pTab->pSchema;
74202      }
74203    } /* if( pSrcList ) */
74204
74205#ifndef SQLITE_OMIT_TRIGGER
74206    /* If we have not already resolved the name, then maybe
74207    ** it is a new.* or old.* trigger argument reference
74208    */
74209    if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
74210      int op = pParse->eTriggerOp;
74211      Table *pTab = 0;
74212      assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
74213      if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
74214        pExpr->iTable = 1;
74215        pTab = pParse->pTriggerTab;
74216      }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
74217        pExpr->iTable = 0;
74218        pTab = pParse->pTriggerTab;
74219      }
74220
74221      if( pTab ){
74222        int iCol;
74223        pSchema = pTab->pSchema;
74224        cntTab++;
74225        for(iCol=0; iCol<pTab->nCol; iCol++){
74226          Column *pCol = &pTab->aCol[iCol];
74227          if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
74228            if( iCol==pTab->iPKey ){
74229              iCol = -1;
74230            }
74231            break;
74232          }
74233        }
74234        if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
74235          iCol = -1;        /* IMP: R-44911-55124 */
74236        }
74237        if( iCol<pTab->nCol ){
74238          cnt++;
74239          if( iCol<0 ){
74240            pExpr->affinity = SQLITE_AFF_INTEGER;
74241          }else if( pExpr->iTable==0 ){
74242            testcase( iCol==31 );
74243            testcase( iCol==32 );
74244            pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
74245          }else{
74246            testcase( iCol==31 );
74247            testcase( iCol==32 );
74248            pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
74249          }
74250          pExpr->iColumn = (i16)iCol;
74251          pExpr->pTab = pTab;
74252          isTrigger = 1;
74253        }
74254      }
74255    }
74256#endif /* !defined(SQLITE_OMIT_TRIGGER) */
74257
74258    /*
74259    ** Perhaps the name is a reference to the ROWID
74260    */
74261    if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
74262      cnt = 1;
74263      pExpr->iColumn = -1;     /* IMP: R-44911-55124 */
74264      pExpr->affinity = SQLITE_AFF_INTEGER;
74265    }
74266
74267    /*
74268    ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
74269    ** might refer to an result-set alias.  This happens, for example, when
74270    ** we are resolving names in the WHERE clause of the following command:
74271    **
74272    **     SELECT a+b AS x FROM table WHERE x<10;
74273    **
74274    ** In cases like this, replace pExpr with a copy of the expression that
74275    ** forms the result set entry ("a+b" in the example) and return immediately.
74276    ** Note that the expression in the result set should have already been
74277    ** resolved by the time the WHERE clause is resolved.
74278    */
74279    if( (pEList = pNC->pEList)!=0
74280     && zTab==0
74281     && ((pNC->ncFlags & NC_AsMaybe)==0 || cnt==0)
74282    ){
74283      for(j=0; j<pEList->nExpr; j++){
74284        char *zAs = pEList->a[j].zName;
74285        if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
74286          Expr *pOrig;
74287          assert( pExpr->pLeft==0 && pExpr->pRight==0 );
74288          assert( pExpr->x.pList==0 );
74289          assert( pExpr->x.pSelect==0 );
74290          pOrig = pEList->a[j].pExpr;
74291          if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
74292            sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
74293            return WRC_Abort;
74294          }
74295          resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
74296          cnt = 1;
74297          pMatch = 0;
74298          assert( zTab==0 && zDb==0 );
74299          goto lookupname_end;
74300        }
74301      }
74302    }
74303
74304    /* Advance to the next name context.  The loop will exit when either
74305    ** we have a match (cnt>0) or when we run out of name contexts.
74306    */
74307    if( cnt==0 ){
74308      pNC = pNC->pNext;
74309      nSubquery++;
74310    }
74311  }
74312
74313  /*
74314  ** If X and Y are NULL (in other words if only the column name Z is
74315  ** supplied) and the value of Z is enclosed in double-quotes, then
74316  ** Z is a string literal if it doesn't match any column names.  In that
74317  ** case, we need to return right away and not make any changes to
74318  ** pExpr.
74319  **
74320  ** Because no reference was made to outer contexts, the pNC->nRef
74321  ** fields are not changed in any context.
74322  */
74323  if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
74324    pExpr->op = TK_STRING;
74325    pExpr->pTab = 0;
74326    return WRC_Prune;
74327  }
74328
74329  /*
74330  ** cnt==0 means there was not match.  cnt>1 means there were two or
74331  ** more matches.  Either way, we have an error.
74332  */
74333  if( cnt!=1 ){
74334    const char *zErr;
74335    zErr = cnt==0 ? "no such column" : "ambiguous column name";
74336    if( zDb ){
74337      sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
74338    }else if( zTab ){
74339      sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
74340    }else{
74341      sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
74342    }
74343    pParse->checkSchema = 1;
74344    pTopNC->nErr++;
74345  }
74346
74347  /* If a column from a table in pSrcList is referenced, then record
74348  ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
74349  ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
74350  ** column number is greater than the number of bits in the bitmask
74351  ** then set the high-order bit of the bitmask.
74352  */
74353  if( pExpr->iColumn>=0 && pMatch!=0 ){
74354    int n = pExpr->iColumn;
74355    testcase( n==BMS-1 );
74356    if( n>=BMS ){
74357      n = BMS-1;
74358    }
74359    assert( pMatch->iCursor==pExpr->iTable );
74360    pMatch->colUsed |= ((Bitmask)1)<<n;
74361  }
74362
74363  /* Clean up and return
74364  */
74365  sqlite3ExprDelete(db, pExpr->pLeft);
74366  pExpr->pLeft = 0;
74367  sqlite3ExprDelete(db, pExpr->pRight);
74368  pExpr->pRight = 0;
74369  pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
74370lookupname_end:
74371  if( cnt==1 ){
74372    assert( pNC!=0 );
74373    if( pExpr->op!=TK_AS ){
74374      sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
74375    }
74376    /* Increment the nRef value on all name contexts from TopNC up to
74377    ** the point where the name matched. */
74378    for(;;){
74379      assert( pTopNC!=0 );
74380      pTopNC->nRef++;
74381      if( pTopNC==pNC ) break;
74382      pTopNC = pTopNC->pNext;
74383    }
74384    return WRC_Prune;
74385  } else {
74386    return WRC_Abort;
74387  }
74388}
74389
74390/*
74391** Allocate and return a pointer to an expression to load the column iCol
74392** from datasource iSrc in SrcList pSrc.
74393*/
74394SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
74395  Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
74396  if( p ){
74397    struct SrcList_item *pItem = &pSrc->a[iSrc];
74398    p->pTab = pItem->pTab;
74399    p->iTable = pItem->iCursor;
74400    if( p->pTab->iPKey==iCol ){
74401      p->iColumn = -1;
74402    }else{
74403      p->iColumn = (ynVar)iCol;
74404      testcase( iCol==BMS );
74405      testcase( iCol==BMS-1 );
74406      pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
74407    }
74408    ExprSetProperty(p, EP_Resolved);
74409  }
74410  return p;
74411}
74412
74413/*
74414** This routine is callback for sqlite3WalkExpr().
74415**
74416** Resolve symbolic names into TK_COLUMN operators for the current
74417** node in the expression tree.  Return 0 to continue the search down
74418** the tree or 2 to abort the tree walk.
74419**
74420** This routine also does error checking and name resolution for
74421** function names.  The operator for aggregate functions is changed
74422** to TK_AGG_FUNCTION.
74423*/
74424static int resolveExprStep(Walker *pWalker, Expr *pExpr){
74425  NameContext *pNC;
74426  Parse *pParse;
74427
74428  pNC = pWalker->u.pNC;
74429  assert( pNC!=0 );
74430  pParse = pNC->pParse;
74431  assert( pParse==pWalker->pParse );
74432
74433  if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
74434  ExprSetProperty(pExpr, EP_Resolved);
74435#ifndef NDEBUG
74436  if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
74437    SrcList *pSrcList = pNC->pSrcList;
74438    int i;
74439    for(i=0; i<pNC->pSrcList->nSrc; i++){
74440      assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
74441    }
74442  }
74443#endif
74444  switch( pExpr->op ){
74445
74446#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
74447    /* The special operator TK_ROW means use the rowid for the first
74448    ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
74449    ** clause processing on UPDATE and DELETE statements.
74450    */
74451    case TK_ROW: {
74452      SrcList *pSrcList = pNC->pSrcList;
74453      struct SrcList_item *pItem;
74454      assert( pSrcList && pSrcList->nSrc==1 );
74455      pItem = pSrcList->a;
74456      pExpr->op = TK_COLUMN;
74457      pExpr->pTab = pItem->pTab;
74458      pExpr->iTable = pItem->iCursor;
74459      pExpr->iColumn = -1;
74460      pExpr->affinity = SQLITE_AFF_INTEGER;
74461      break;
74462    }
74463#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
74464
74465    /* A lone identifier is the name of a column.
74466    */
74467    case TK_ID: {
74468      return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
74469    }
74470
74471    /* A table name and column name:     ID.ID
74472    ** Or a database, table and column:  ID.ID.ID
74473    */
74474    case TK_DOT: {
74475      const char *zColumn;
74476      const char *zTable;
74477      const char *zDb;
74478      Expr *pRight;
74479
74480      /* if( pSrcList==0 ) break; */
74481      pRight = pExpr->pRight;
74482      if( pRight->op==TK_ID ){
74483        zDb = 0;
74484        zTable = pExpr->pLeft->u.zToken;
74485        zColumn = pRight->u.zToken;
74486      }else{
74487        assert( pRight->op==TK_DOT );
74488        zDb = pExpr->pLeft->u.zToken;
74489        zTable = pRight->pLeft->u.zToken;
74490        zColumn = pRight->pRight->u.zToken;
74491      }
74492      return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
74493    }
74494
74495    /* Resolve function names
74496    */
74497    case TK_CONST_FUNC:
74498    case TK_FUNCTION: {
74499      ExprList *pList = pExpr->x.pList;    /* The argument list */
74500      int n = pList ? pList->nExpr : 0;    /* Number of arguments */
74501      int no_such_func = 0;       /* True if no such function exists */
74502      int wrong_num_args = 0;     /* True if wrong number of arguments */
74503      int is_agg = 0;             /* True if is an aggregate function */
74504      int auth;                   /* Authorization to use the function */
74505      int nId;                    /* Number of characters in function name */
74506      const char *zId;            /* The function name. */
74507      FuncDef *pDef;              /* Information about the function */
74508      u8 enc = ENC(pParse->db);   /* The database encoding */
74509
74510      testcase( pExpr->op==TK_CONST_FUNC );
74511      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
74512      zId = pExpr->u.zToken;
74513      nId = sqlite3Strlen30(zId);
74514      pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
74515      if( pDef==0 ){
74516        pDef = sqlite3FindFunction(pParse->db, zId, nId, -2, enc, 0);
74517        if( pDef==0 ){
74518          no_such_func = 1;
74519        }else{
74520          wrong_num_args = 1;
74521        }
74522      }else{
74523        is_agg = pDef->xFunc==0;
74524      }
74525#ifndef SQLITE_OMIT_AUTHORIZATION
74526      if( pDef ){
74527        auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
74528        if( auth!=SQLITE_OK ){
74529          if( auth==SQLITE_DENY ){
74530            sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
74531                                    pDef->zName);
74532            pNC->nErr++;
74533          }
74534          pExpr->op = TK_NULL;
74535          return WRC_Prune;
74536        }
74537      }
74538#endif
74539      if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
74540        sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
74541        pNC->nErr++;
74542        is_agg = 0;
74543      }else if( no_such_func && pParse->db->init.busy==0 ){
74544        sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
74545        pNC->nErr++;
74546      }else if( wrong_num_args ){
74547        sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
74548             nId, zId);
74549        pNC->nErr++;
74550      }
74551      if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
74552      sqlite3WalkExprList(pWalker, pList);
74553      if( is_agg ){
74554        NameContext *pNC2 = pNC;
74555        pExpr->op = TK_AGG_FUNCTION;
74556        pExpr->op2 = 0;
74557        while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
74558          pExpr->op2++;
74559          pNC2 = pNC2->pNext;
74560        }
74561        if( pNC2 ) pNC2->ncFlags |= NC_HasAgg;
74562        pNC->ncFlags |= NC_AllowAgg;
74563      }
74564      /* FIX ME:  Compute pExpr->affinity based on the expected return
74565      ** type of the function
74566      */
74567      return WRC_Prune;
74568    }
74569#ifndef SQLITE_OMIT_SUBQUERY
74570    case TK_SELECT:
74571    case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
74572#endif
74573    case TK_IN: {
74574      testcase( pExpr->op==TK_IN );
74575      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
74576        int nRef = pNC->nRef;
74577#ifndef SQLITE_OMIT_CHECK
74578        if( (pNC->ncFlags & NC_IsCheck)!=0 ){
74579          sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
74580        }
74581#endif
74582        sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
74583        assert( pNC->nRef>=nRef );
74584        if( nRef!=pNC->nRef ){
74585          ExprSetProperty(pExpr, EP_VarSelect);
74586        }
74587      }
74588      break;
74589    }
74590#ifndef SQLITE_OMIT_CHECK
74591    case TK_VARIABLE: {
74592      if( (pNC->ncFlags & NC_IsCheck)!=0 ){
74593        sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
74594      }
74595      break;
74596    }
74597#endif
74598  }
74599  return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
74600}
74601
74602/*
74603** pEList is a list of expressions which are really the result set of the
74604** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
74605** This routine checks to see if pE is a simple identifier which corresponds
74606** to the AS-name of one of the terms of the expression list.  If it is,
74607** this routine return an integer between 1 and N where N is the number of
74608** elements in pEList, corresponding to the matching entry.  If there is
74609** no match, or if pE is not a simple identifier, then this routine
74610** return 0.
74611**
74612** pEList has been resolved.  pE has not.
74613*/
74614static int resolveAsName(
74615  Parse *pParse,     /* Parsing context for error messages */
74616  ExprList *pEList,  /* List of expressions to scan */
74617  Expr *pE           /* Expression we are trying to match */
74618){
74619  int i;             /* Loop counter */
74620
74621  UNUSED_PARAMETER(pParse);
74622
74623  if( pE->op==TK_ID ){
74624    char *zCol = pE->u.zToken;
74625    for(i=0; i<pEList->nExpr; i++){
74626      char *zAs = pEList->a[i].zName;
74627      if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
74628        return i+1;
74629      }
74630    }
74631  }
74632  return 0;
74633}
74634
74635/*
74636** pE is a pointer to an expression which is a single term in the
74637** ORDER BY of a compound SELECT.  The expression has not been
74638** name resolved.
74639**
74640** At the point this routine is called, we already know that the
74641** ORDER BY term is not an integer index into the result set.  That
74642** case is handled by the calling routine.
74643**
74644** Attempt to match pE against result set columns in the left-most
74645** SELECT statement.  Return the index i of the matching column,
74646** as an indication to the caller that it should sort by the i-th column.
74647** The left-most column is 1.  In other words, the value returned is the
74648** same integer value that would be used in the SQL statement to indicate
74649** the column.
74650**
74651** If there is no match, return 0.  Return -1 if an error occurs.
74652*/
74653static int resolveOrderByTermToExprList(
74654  Parse *pParse,     /* Parsing context for error messages */
74655  Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
74656  Expr *pE           /* The specific ORDER BY term */
74657){
74658  int i;             /* Loop counter */
74659  ExprList *pEList;  /* The columns of the result set */
74660  NameContext nc;    /* Name context for resolving pE */
74661  sqlite3 *db;       /* Database connection */
74662  int rc;            /* Return code from subprocedures */
74663  u8 savedSuppErr;   /* Saved value of db->suppressErr */
74664
74665  assert( sqlite3ExprIsInteger(pE, &i)==0 );
74666  pEList = pSelect->pEList;
74667
74668  /* Resolve all names in the ORDER BY term expression
74669  */
74670  memset(&nc, 0, sizeof(nc));
74671  nc.pParse = pParse;
74672  nc.pSrcList = pSelect->pSrc;
74673  nc.pEList = pEList;
74674  nc.ncFlags = NC_AllowAgg;
74675  nc.nErr = 0;
74676  db = pParse->db;
74677  savedSuppErr = db->suppressErr;
74678  db->suppressErr = 1;
74679  rc = sqlite3ResolveExprNames(&nc, pE);
74680  db->suppressErr = savedSuppErr;
74681  if( rc ) return 0;
74682
74683  /* Try to match the ORDER BY expression against an expression
74684  ** in the result set.  Return an 1-based index of the matching
74685  ** result-set entry.
74686  */
74687  for(i=0; i<pEList->nExpr; i++){
74688    if( sqlite3ExprCompare(pEList->a[i].pExpr, pE)<2 ){
74689      return i+1;
74690    }
74691  }
74692
74693  /* If no match, return 0. */
74694  return 0;
74695}
74696
74697/*
74698** Generate an ORDER BY or GROUP BY term out-of-range error.
74699*/
74700static void resolveOutOfRangeError(
74701  Parse *pParse,         /* The error context into which to write the error */
74702  const char *zType,     /* "ORDER" or "GROUP" */
74703  int i,                 /* The index (1-based) of the term out of range */
74704  int mx                 /* Largest permissible value of i */
74705){
74706  sqlite3ErrorMsg(pParse,
74707    "%r %s BY term out of range - should be "
74708    "between 1 and %d", i, zType, mx);
74709}
74710
74711/*
74712** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
74713** each term of the ORDER BY clause is a constant integer between 1
74714** and N where N is the number of columns in the compound SELECT.
74715**
74716** ORDER BY terms that are already an integer between 1 and N are
74717** unmodified.  ORDER BY terms that are integers outside the range of
74718** 1 through N generate an error.  ORDER BY terms that are expressions
74719** are matched against result set expressions of compound SELECT
74720** beginning with the left-most SELECT and working toward the right.
74721** At the first match, the ORDER BY expression is transformed into
74722** the integer column number.
74723**
74724** Return the number of errors seen.
74725*/
74726static int resolveCompoundOrderBy(
74727  Parse *pParse,        /* Parsing context.  Leave error messages here */
74728  Select *pSelect       /* The SELECT statement containing the ORDER BY */
74729){
74730  int i;
74731  ExprList *pOrderBy;
74732  ExprList *pEList;
74733  sqlite3 *db;
74734  int moreToDo = 1;
74735
74736  pOrderBy = pSelect->pOrderBy;
74737  if( pOrderBy==0 ) return 0;
74738  db = pParse->db;
74739#if SQLITE_MAX_COLUMN
74740  if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
74741    sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
74742    return 1;
74743  }
74744#endif
74745  for(i=0; i<pOrderBy->nExpr; i++){
74746    pOrderBy->a[i].done = 0;
74747  }
74748  pSelect->pNext = 0;
74749  while( pSelect->pPrior ){
74750    pSelect->pPrior->pNext = pSelect;
74751    pSelect = pSelect->pPrior;
74752  }
74753  while( pSelect && moreToDo ){
74754    struct ExprList_item *pItem;
74755    moreToDo = 0;
74756    pEList = pSelect->pEList;
74757    assert( pEList!=0 );
74758    for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
74759      int iCol = -1;
74760      Expr *pE, *pDup;
74761      if( pItem->done ) continue;
74762      pE = sqlite3ExprSkipCollate(pItem->pExpr);
74763      if( sqlite3ExprIsInteger(pE, &iCol) ){
74764        if( iCol<=0 || iCol>pEList->nExpr ){
74765          resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
74766          return 1;
74767        }
74768      }else{
74769        iCol = resolveAsName(pParse, pEList, pE);
74770        if( iCol==0 ){
74771          pDup = sqlite3ExprDup(db, pE, 0);
74772          if( !db->mallocFailed ){
74773            assert(pDup);
74774            iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
74775          }
74776          sqlite3ExprDelete(db, pDup);
74777        }
74778      }
74779      if( iCol>0 ){
74780        /* Convert the ORDER BY term into an integer column number iCol,
74781        ** taking care to preserve the COLLATE clause if it exists */
74782        Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
74783        if( pNew==0 ) return 1;
74784        pNew->flags |= EP_IntValue;
74785        pNew->u.iValue = iCol;
74786        if( pItem->pExpr==pE ){
74787          pItem->pExpr = pNew;
74788        }else{
74789          assert( pItem->pExpr->op==TK_COLLATE );
74790          assert( pItem->pExpr->pLeft==pE );
74791          pItem->pExpr->pLeft = pNew;
74792        }
74793        sqlite3ExprDelete(db, pE);
74794        pItem->iOrderByCol = (u16)iCol;
74795        pItem->done = 1;
74796      }else{
74797        moreToDo = 1;
74798      }
74799    }
74800    pSelect = pSelect->pNext;
74801  }
74802  for(i=0; i<pOrderBy->nExpr; i++){
74803    if( pOrderBy->a[i].done==0 ){
74804      sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
74805            "column in the result set", i+1);
74806      return 1;
74807    }
74808  }
74809  return 0;
74810}
74811
74812/*
74813** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
74814** the SELECT statement pSelect.  If any term is reference to a
74815** result set expression (as determined by the ExprList.a.iCol field)
74816** then convert that term into a copy of the corresponding result set
74817** column.
74818**
74819** If any errors are detected, add an error message to pParse and
74820** return non-zero.  Return zero if no errors are seen.
74821*/
74822SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
74823  Parse *pParse,        /* Parsing context.  Leave error messages here */
74824  Select *pSelect,      /* The SELECT statement containing the clause */
74825  ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
74826  const char *zType     /* "ORDER" or "GROUP" */
74827){
74828  int i;
74829  sqlite3 *db = pParse->db;
74830  ExprList *pEList;
74831  struct ExprList_item *pItem;
74832
74833  if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
74834#if SQLITE_MAX_COLUMN
74835  if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
74836    sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
74837    return 1;
74838  }
74839#endif
74840  pEList = pSelect->pEList;
74841  assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
74842  for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
74843    if( pItem->iOrderByCol ){
74844      if( pItem->iOrderByCol>pEList->nExpr ){
74845        resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
74846        return 1;
74847      }
74848      resolveAlias(pParse, pEList, pItem->iOrderByCol-1, pItem->pExpr, zType,0);
74849    }
74850  }
74851  return 0;
74852}
74853
74854/*
74855** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
74856** The Name context of the SELECT statement is pNC.  zType is either
74857** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
74858**
74859** This routine resolves each term of the clause into an expression.
74860** If the order-by term is an integer I between 1 and N (where N is the
74861** number of columns in the result set of the SELECT) then the expression
74862** in the resolution is a copy of the I-th result-set expression.  If
74863** the order-by term is an identify that corresponds to the AS-name of
74864** a result-set expression, then the term resolves to a copy of the
74865** result-set expression.  Otherwise, the expression is resolved in
74866** the usual way - using sqlite3ResolveExprNames().
74867**
74868** This routine returns the number of errors.  If errors occur, then
74869** an appropriate error message might be left in pParse.  (OOM errors
74870** excepted.)
74871*/
74872static int resolveOrderGroupBy(
74873  NameContext *pNC,     /* The name context of the SELECT statement */
74874  Select *pSelect,      /* The SELECT statement holding pOrderBy */
74875  ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
74876  const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
74877){
74878  int i, j;                      /* Loop counters */
74879  int iCol;                      /* Column number */
74880  struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
74881  Parse *pParse;                 /* Parsing context */
74882  int nResult;                   /* Number of terms in the result set */
74883
74884  if( pOrderBy==0 ) return 0;
74885  nResult = pSelect->pEList->nExpr;
74886  pParse = pNC->pParse;
74887  for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
74888    Expr *pE = pItem->pExpr;
74889    iCol = resolveAsName(pParse, pSelect->pEList, pE);
74890    if( iCol>0 ){
74891      /* If an AS-name match is found, mark this ORDER BY column as being
74892      ** a copy of the iCol-th result-set column.  The subsequent call to
74893      ** sqlite3ResolveOrderGroupBy() will convert the expression to a
74894      ** copy of the iCol-th result-set expression. */
74895      pItem->iOrderByCol = (u16)iCol;
74896      continue;
74897    }
74898    if( sqlite3ExprIsInteger(sqlite3ExprSkipCollate(pE), &iCol) ){
74899      /* The ORDER BY term is an integer constant.  Again, set the column
74900      ** number so that sqlite3ResolveOrderGroupBy() will convert the
74901      ** order-by term to a copy of the result-set expression */
74902      if( iCol<1 || iCol>0xffff ){
74903        resolveOutOfRangeError(pParse, zType, i+1, nResult);
74904        return 1;
74905      }
74906      pItem->iOrderByCol = (u16)iCol;
74907      continue;
74908    }
74909
74910    /* Otherwise, treat the ORDER BY term as an ordinary expression */
74911    pItem->iOrderByCol = 0;
74912    if( sqlite3ResolveExprNames(pNC, pE) ){
74913      return 1;
74914    }
74915    for(j=0; j<pSelect->pEList->nExpr; j++){
74916      if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr)==0 ){
74917        pItem->iOrderByCol = j+1;
74918      }
74919    }
74920  }
74921  return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
74922}
74923
74924/*
74925** Resolve names in the SELECT statement p and all of its descendents.
74926*/
74927static int resolveSelectStep(Walker *pWalker, Select *p){
74928  NameContext *pOuterNC;  /* Context that contains this SELECT */
74929  NameContext sNC;        /* Name context of this SELECT */
74930  int isCompound;         /* True if p is a compound select */
74931  int nCompound;          /* Number of compound terms processed so far */
74932  Parse *pParse;          /* Parsing context */
74933  ExprList *pEList;       /* Result set expression list */
74934  int i;                  /* Loop counter */
74935  ExprList *pGroupBy;     /* The GROUP BY clause */
74936  Select *pLeftmost;      /* Left-most of SELECT of a compound */
74937  sqlite3 *db;            /* Database connection */
74938
74939
74940  assert( p!=0 );
74941  if( p->selFlags & SF_Resolved ){
74942    return WRC_Prune;
74943  }
74944  pOuterNC = pWalker->u.pNC;
74945  pParse = pWalker->pParse;
74946  db = pParse->db;
74947
74948  /* Normally sqlite3SelectExpand() will be called first and will have
74949  ** already expanded this SELECT.  However, if this is a subquery within
74950  ** an expression, sqlite3ResolveExprNames() will be called without a
74951  ** prior call to sqlite3SelectExpand().  When that happens, let
74952  ** sqlite3SelectPrep() do all of the processing for this SELECT.
74953  ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
74954  ** this routine in the correct order.
74955  */
74956  if( (p->selFlags & SF_Expanded)==0 ){
74957    sqlite3SelectPrep(pParse, p, pOuterNC);
74958    return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
74959  }
74960
74961  isCompound = p->pPrior!=0;
74962  nCompound = 0;
74963  pLeftmost = p;
74964  while( p ){
74965    assert( (p->selFlags & SF_Expanded)!=0 );
74966    assert( (p->selFlags & SF_Resolved)==0 );
74967    p->selFlags |= SF_Resolved;
74968
74969    /* Resolve the expressions in the LIMIT and OFFSET clauses. These
74970    ** are not allowed to refer to any names, so pass an empty NameContext.
74971    */
74972    memset(&sNC, 0, sizeof(sNC));
74973    sNC.pParse = pParse;
74974    if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
74975        sqlite3ResolveExprNames(&sNC, p->pOffset) ){
74976      return WRC_Abort;
74977    }
74978
74979    /* Recursively resolve names in all subqueries
74980    */
74981    for(i=0; i<p->pSrc->nSrc; i++){
74982      struct SrcList_item *pItem = &p->pSrc->a[i];
74983      if( pItem->pSelect ){
74984        NameContext *pNC;         /* Used to iterate name contexts */
74985        int nRef = 0;             /* Refcount for pOuterNC and outer contexts */
74986        const char *zSavedContext = pParse->zAuthContext;
74987
74988        /* Count the total number of references to pOuterNC and all of its
74989        ** parent contexts. After resolving references to expressions in
74990        ** pItem->pSelect, check if this value has changed. If so, then
74991        ** SELECT statement pItem->pSelect must be correlated. Set the
74992        ** pItem->isCorrelated flag if this is the case. */
74993        for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
74994
74995        if( pItem->zName ) pParse->zAuthContext = pItem->zName;
74996        sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
74997        pParse->zAuthContext = zSavedContext;
74998        if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
74999
75000        for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
75001        assert( pItem->isCorrelated==0 && nRef<=0 );
75002        pItem->isCorrelated = (nRef!=0);
75003      }
75004    }
75005
75006    /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
75007    ** resolve the result-set expression list.
75008    */
75009    sNC.ncFlags = NC_AllowAgg;
75010    sNC.pSrcList = p->pSrc;
75011    sNC.pNext = pOuterNC;
75012
75013    /* Resolve names in the result set. */
75014    pEList = p->pEList;
75015    assert( pEList!=0 );
75016    for(i=0; i<pEList->nExpr; i++){
75017      Expr *pX = pEList->a[i].pExpr;
75018      if( sqlite3ResolveExprNames(&sNC, pX) ){
75019        return WRC_Abort;
75020      }
75021    }
75022
75023    /* If there are no aggregate functions in the result-set, and no GROUP BY
75024    ** expression, do not allow aggregates in any of the other expressions.
75025    */
75026    assert( (p->selFlags & SF_Aggregate)==0 );
75027    pGroupBy = p->pGroupBy;
75028    if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
75029      p->selFlags |= SF_Aggregate;
75030    }else{
75031      sNC.ncFlags &= ~NC_AllowAgg;
75032    }
75033
75034    /* If a HAVING clause is present, then there must be a GROUP BY clause.
75035    */
75036    if( p->pHaving && !pGroupBy ){
75037      sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
75038      return WRC_Abort;
75039    }
75040
75041    /* Add the expression list to the name-context before parsing the
75042    ** other expressions in the SELECT statement. This is so that
75043    ** expressions in the WHERE clause (etc.) can refer to expressions by
75044    ** aliases in the result set.
75045    **
75046    ** Minor point: If this is the case, then the expression will be
75047    ** re-evaluated for each reference to it.
75048    */
75049    sNC.pEList = p->pEList;
75050    sNC.ncFlags |= NC_AsMaybe;
75051    if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
75052    if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
75053    sNC.ncFlags &= ~NC_AsMaybe;
75054
75055    /* The ORDER BY and GROUP BY clauses may not refer to terms in
75056    ** outer queries
75057    */
75058    sNC.pNext = 0;
75059    sNC.ncFlags |= NC_AllowAgg;
75060
75061    /* Process the ORDER BY clause for singleton SELECT statements.
75062    ** The ORDER BY clause for compounds SELECT statements is handled
75063    ** below, after all of the result-sets for all of the elements of
75064    ** the compound have been resolved.
75065    */
75066    if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
75067      return WRC_Abort;
75068    }
75069    if( db->mallocFailed ){
75070      return WRC_Abort;
75071    }
75072
75073    /* Resolve the GROUP BY clause.  At the same time, make sure
75074    ** the GROUP BY clause does not contain aggregate functions.
75075    */
75076    if( pGroupBy ){
75077      struct ExprList_item *pItem;
75078
75079      if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
75080        return WRC_Abort;
75081      }
75082      for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
75083        if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
75084          sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
75085              "the GROUP BY clause");
75086          return WRC_Abort;
75087        }
75088      }
75089    }
75090
75091    /* Advance to the next term of the compound
75092    */
75093    p = p->pPrior;
75094    nCompound++;
75095  }
75096
75097  /* Resolve the ORDER BY on a compound SELECT after all terms of
75098  ** the compound have been resolved.
75099  */
75100  if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
75101    return WRC_Abort;
75102  }
75103
75104  return WRC_Prune;
75105}
75106
75107/*
75108** This routine walks an expression tree and resolves references to
75109** table columns and result-set columns.  At the same time, do error
75110** checking on function usage and set a flag if any aggregate functions
75111** are seen.
75112**
75113** To resolve table columns references we look for nodes (or subtrees) of the
75114** form X.Y.Z or Y.Z or just Z where
75115**
75116**      X:   The name of a database.  Ex:  "main" or "temp" or
75117**           the symbolic name assigned to an ATTACH-ed database.
75118**
75119**      Y:   The name of a table in a FROM clause.  Or in a trigger
75120**           one of the special names "old" or "new".
75121**
75122**      Z:   The name of a column in table Y.
75123**
75124** The node at the root of the subtree is modified as follows:
75125**
75126**    Expr.op        Changed to TK_COLUMN
75127**    Expr.pTab      Points to the Table object for X.Y
75128**    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
75129**    Expr.iTable    The VDBE cursor number for X.Y
75130**
75131**
75132** To resolve result-set references, look for expression nodes of the
75133** form Z (with no X and Y prefix) where the Z matches the right-hand
75134** size of an AS clause in the result-set of a SELECT.  The Z expression
75135** is replaced by a copy of the left-hand side of the result-set expression.
75136** Table-name and function resolution occurs on the substituted expression
75137** tree.  For example, in:
75138**
75139**      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
75140**
75141** The "x" term of the order by is replaced by "a+b" to render:
75142**
75143**      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
75144**
75145** Function calls are checked to make sure that the function is
75146** defined and that the correct number of arguments are specified.
75147** If the function is an aggregate function, then the NC_HasAgg flag is
75148** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
75149** If an expression contains aggregate functions then the EP_Agg
75150** property on the expression is set.
75151**
75152** An error message is left in pParse if anything is amiss.  The number
75153** if errors is returned.
75154*/
75155SQLITE_PRIVATE int sqlite3ResolveExprNames(
75156  NameContext *pNC,       /* Namespace to resolve expressions in. */
75157  Expr *pExpr             /* The expression to be analyzed. */
75158){
75159  u8 savedHasAgg;
75160  Walker w;
75161
75162  if( pExpr==0 ) return 0;
75163#if SQLITE_MAX_EXPR_DEPTH>0
75164  {
75165    Parse *pParse = pNC->pParse;
75166    if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
75167      return 1;
75168    }
75169    pParse->nHeight += pExpr->nHeight;
75170  }
75171#endif
75172  savedHasAgg = pNC->ncFlags & NC_HasAgg;
75173  pNC->ncFlags &= ~NC_HasAgg;
75174  memset(&w, 0, sizeof(w));
75175  w.xExprCallback = resolveExprStep;
75176  w.xSelectCallback = resolveSelectStep;
75177  w.pParse = pNC->pParse;
75178  w.u.pNC = pNC;
75179  sqlite3WalkExpr(&w, pExpr);
75180#if SQLITE_MAX_EXPR_DEPTH>0
75181  pNC->pParse->nHeight -= pExpr->nHeight;
75182#endif
75183  if( pNC->nErr>0 || w.pParse->nErr>0 ){
75184    ExprSetProperty(pExpr, EP_Error);
75185  }
75186  if( pNC->ncFlags & NC_HasAgg ){
75187    ExprSetProperty(pExpr, EP_Agg);
75188  }else if( savedHasAgg ){
75189    pNC->ncFlags |= NC_HasAgg;
75190  }
75191  return ExprHasProperty(pExpr, EP_Error);
75192}
75193
75194
75195/*
75196** Resolve all names in all expressions of a SELECT and in all
75197** decendents of the SELECT, including compounds off of p->pPrior,
75198** subqueries in expressions, and subqueries used as FROM clause
75199** terms.
75200**
75201** See sqlite3ResolveExprNames() for a description of the kinds of
75202** transformations that occur.
75203**
75204** All SELECT statements should have been expanded using
75205** sqlite3SelectExpand() prior to invoking this routine.
75206*/
75207SQLITE_PRIVATE void sqlite3ResolveSelectNames(
75208  Parse *pParse,         /* The parser context */
75209  Select *p,             /* The SELECT statement being coded. */
75210  NameContext *pOuterNC  /* Name context for parent SELECT statement */
75211){
75212  Walker w;
75213
75214  assert( p!=0 );
75215  memset(&w, 0, sizeof(w));
75216  w.xExprCallback = resolveExprStep;
75217  w.xSelectCallback = resolveSelectStep;
75218  w.pParse = pParse;
75219  w.u.pNC = pOuterNC;
75220  sqlite3WalkSelect(&w, p);
75221}
75222
75223/************** End of resolve.c *********************************************/
75224/************** Begin file expr.c ********************************************/
75225/*
75226** 2001 September 15
75227**
75228** The author disclaims copyright to this source code.  In place of
75229** a legal notice, here is a blessing:
75230**
75231**    May you do good and not evil.
75232**    May you find forgiveness for yourself and forgive others.
75233**    May you share freely, never taking more than you give.
75234**
75235*************************************************************************
75236** This file contains routines used for analyzing expressions and
75237** for generating VDBE code that evaluates expressions in SQLite.
75238*/
75239
75240/*
75241** Return the 'affinity' of the expression pExpr if any.
75242**
75243** If pExpr is a column, a reference to a column via an 'AS' alias,
75244** or a sub-select with a column as the return value, then the
75245** affinity of that column is returned. Otherwise, 0x00 is returned,
75246** indicating no affinity for the expression.
75247**
75248** i.e. the WHERE clause expresssions in the following statements all
75249** have an affinity:
75250**
75251** CREATE TABLE t1(a);
75252** SELECT * FROM t1 WHERE a;
75253** SELECT a AS b FROM t1 WHERE b;
75254** SELECT * FROM t1 WHERE (select a from t1);
75255*/
75256SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
75257  int op;
75258  pExpr = sqlite3ExprSkipCollate(pExpr);
75259  op = pExpr->op;
75260  if( op==TK_SELECT ){
75261    assert( pExpr->flags&EP_xIsSelect );
75262    return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
75263  }
75264#ifndef SQLITE_OMIT_CAST
75265  if( op==TK_CAST ){
75266    assert( !ExprHasProperty(pExpr, EP_IntValue) );
75267    return sqlite3AffinityType(pExpr->u.zToken);
75268  }
75269#endif
75270  if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
75271   && pExpr->pTab!=0
75272  ){
75273    /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
75274    ** a TK_COLUMN but was previously evaluated and cached in a register */
75275    int j = pExpr->iColumn;
75276    if( j<0 ) return SQLITE_AFF_INTEGER;
75277    assert( pExpr->pTab && j<pExpr->pTab->nCol );
75278    return pExpr->pTab->aCol[j].affinity;
75279  }
75280  return pExpr->affinity;
75281}
75282
75283/*
75284** Set the collating sequence for expression pExpr to be the collating
75285** sequence named by pToken.   Return a pointer to a new Expr node that
75286** implements the COLLATE operator.
75287**
75288** If a memory allocation error occurs, that fact is recorded in pParse->db
75289** and the pExpr parameter is returned unchanged.
75290*/
75291SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr *pExpr, Token *pCollName){
75292  if( pCollName->n>0 ){
75293    Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, 1);
75294    if( pNew ){
75295      pNew->pLeft = pExpr;
75296      pNew->flags |= EP_Collate;
75297      pExpr = pNew;
75298    }
75299  }
75300  return pExpr;
75301}
75302SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
75303  Token s;
75304  assert( zC!=0 );
75305  s.z = zC;
75306  s.n = sqlite3Strlen30(s.z);
75307  return sqlite3ExprAddCollateToken(pParse, pExpr, &s);
75308}
75309
75310/*
75311** Skip over any TK_COLLATE and/or TK_AS operators at the root of
75312** an expression.
75313*/
75314SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
75315  while( pExpr && (pExpr->op==TK_COLLATE || pExpr->op==TK_AS) ){
75316    pExpr = pExpr->pLeft;
75317  }
75318  return pExpr;
75319}
75320
75321/*
75322** Return the collation sequence for the expression pExpr. If
75323** there is no defined collating sequence, return NULL.
75324**
75325** The collating sequence might be determined by a COLLATE operator
75326** or by the presence of a column with a defined collating sequence.
75327** COLLATE operators take first precedence.  Left operands take
75328** precedence over right operands.
75329*/
75330SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
75331  sqlite3 *db = pParse->db;
75332  CollSeq *pColl = 0;
75333  Expr *p = pExpr;
75334  while( p ){
75335    int op = p->op;
75336    if( op==TK_CAST || op==TK_UPLUS ){
75337      p = p->pLeft;
75338      continue;
75339    }
75340    assert( op!=TK_REGISTER || p->op2!=TK_COLLATE );
75341    if( op==TK_COLLATE ){
75342      pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
75343      break;
75344    }
75345    if( p->pTab!=0
75346     && (op==TK_AGG_COLUMN || op==TK_COLUMN
75347          || op==TK_REGISTER || op==TK_TRIGGER)
75348    ){
75349      /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
75350      ** a TK_COLUMN but was previously evaluated and cached in a register */
75351      int j = p->iColumn;
75352      if( j>=0 ){
75353        const char *zColl = p->pTab->aCol[j].zColl;
75354        pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
75355      }
75356      break;
75357    }
75358    if( p->flags & EP_Collate ){
75359      if( ALWAYS(p->pLeft) && (p->pLeft->flags & EP_Collate)!=0 ){
75360        p = p->pLeft;
75361      }else{
75362        p = p->pRight;
75363      }
75364    }else{
75365      break;
75366    }
75367  }
75368  if( sqlite3CheckCollSeq(pParse, pColl) ){
75369    pColl = 0;
75370  }
75371  return pColl;
75372}
75373
75374/*
75375** pExpr is an operand of a comparison operator.  aff2 is the
75376** type affinity of the other operand.  This routine returns the
75377** type affinity that should be used for the comparison operator.
75378*/
75379SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
75380  char aff1 = sqlite3ExprAffinity(pExpr);
75381  if( aff1 && aff2 ){
75382    /* Both sides of the comparison are columns. If one has numeric
75383    ** affinity, use that. Otherwise use no affinity.
75384    */
75385    if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
75386      return SQLITE_AFF_NUMERIC;
75387    }else{
75388      return SQLITE_AFF_NONE;
75389    }
75390  }else if( !aff1 && !aff2 ){
75391    /* Neither side of the comparison is a column.  Compare the
75392    ** results directly.
75393    */
75394    return SQLITE_AFF_NONE;
75395  }else{
75396    /* One side is a column, the other is not. Use the columns affinity. */
75397    assert( aff1==0 || aff2==0 );
75398    return (aff1 + aff2);
75399  }
75400}
75401
75402/*
75403** pExpr is a comparison operator.  Return the type affinity that should
75404** be applied to both operands prior to doing the comparison.
75405*/
75406static char comparisonAffinity(Expr *pExpr){
75407  char aff;
75408  assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
75409          pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
75410          pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
75411  assert( pExpr->pLeft );
75412  aff = sqlite3ExprAffinity(pExpr->pLeft);
75413  if( pExpr->pRight ){
75414    aff = sqlite3CompareAffinity(pExpr->pRight, aff);
75415  }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
75416    aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
75417  }else if( !aff ){
75418    aff = SQLITE_AFF_NONE;
75419  }
75420  return aff;
75421}
75422
75423/*
75424** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
75425** idx_affinity is the affinity of an indexed column. Return true
75426** if the index with affinity idx_affinity may be used to implement
75427** the comparison in pExpr.
75428*/
75429SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
75430  char aff = comparisonAffinity(pExpr);
75431  switch( aff ){
75432    case SQLITE_AFF_NONE:
75433      return 1;
75434    case SQLITE_AFF_TEXT:
75435      return idx_affinity==SQLITE_AFF_TEXT;
75436    default:
75437      return sqlite3IsNumericAffinity(idx_affinity);
75438  }
75439}
75440
75441/*
75442** Return the P5 value that should be used for a binary comparison
75443** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
75444*/
75445static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
75446  u8 aff = (char)sqlite3ExprAffinity(pExpr2);
75447  aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
75448  return aff;
75449}
75450
75451/*
75452** Return a pointer to the collation sequence that should be used by
75453** a binary comparison operator comparing pLeft and pRight.
75454**
75455** If the left hand expression has a collating sequence type, then it is
75456** used. Otherwise the collation sequence for the right hand expression
75457** is used, or the default (BINARY) if neither expression has a collating
75458** type.
75459**
75460** Argument pRight (but not pLeft) may be a null pointer. In this case,
75461** it is not considered.
75462*/
75463SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
75464  Parse *pParse,
75465  Expr *pLeft,
75466  Expr *pRight
75467){
75468  CollSeq *pColl;
75469  assert( pLeft );
75470  if( pLeft->flags & EP_Collate ){
75471    pColl = sqlite3ExprCollSeq(pParse, pLeft);
75472  }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
75473    pColl = sqlite3ExprCollSeq(pParse, pRight);
75474  }else{
75475    pColl = sqlite3ExprCollSeq(pParse, pLeft);
75476    if( !pColl ){
75477      pColl = sqlite3ExprCollSeq(pParse, pRight);
75478    }
75479  }
75480  return pColl;
75481}
75482
75483/*
75484** Generate code for a comparison operator.
75485*/
75486static int codeCompare(
75487  Parse *pParse,    /* The parsing (and code generating) context */
75488  Expr *pLeft,      /* The left operand */
75489  Expr *pRight,     /* The right operand */
75490  int opcode,       /* The comparison opcode */
75491  int in1, int in2, /* Register holding operands */
75492  int dest,         /* Jump here if true.  */
75493  int jumpIfNull    /* If true, jump if either operand is NULL */
75494){
75495  int p5;
75496  int addr;
75497  CollSeq *p4;
75498
75499  p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
75500  p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
75501  addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
75502                           (void*)p4, P4_COLLSEQ);
75503  sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
75504  return addr;
75505}
75506
75507#if SQLITE_MAX_EXPR_DEPTH>0
75508/*
75509** Check that argument nHeight is less than or equal to the maximum
75510** expression depth allowed. If it is not, leave an error message in
75511** pParse.
75512*/
75513SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
75514  int rc = SQLITE_OK;
75515  int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
75516  if( nHeight>mxHeight ){
75517    sqlite3ErrorMsg(pParse,
75518       "Expression tree is too large (maximum depth %d)", mxHeight
75519    );
75520    rc = SQLITE_ERROR;
75521  }
75522  return rc;
75523}
75524
75525/* The following three functions, heightOfExpr(), heightOfExprList()
75526** and heightOfSelect(), are used to determine the maximum height
75527** of any expression tree referenced by the structure passed as the
75528** first argument.
75529**
75530** If this maximum height is greater than the current value pointed
75531** to by pnHeight, the second parameter, then set *pnHeight to that
75532** value.
75533*/
75534static void heightOfExpr(Expr *p, int *pnHeight){
75535  if( p ){
75536    if( p->nHeight>*pnHeight ){
75537      *pnHeight = p->nHeight;
75538    }
75539  }
75540}
75541static void heightOfExprList(ExprList *p, int *pnHeight){
75542  if( p ){
75543    int i;
75544    for(i=0; i<p->nExpr; i++){
75545      heightOfExpr(p->a[i].pExpr, pnHeight);
75546    }
75547  }
75548}
75549static void heightOfSelect(Select *p, int *pnHeight){
75550  if( p ){
75551    heightOfExpr(p->pWhere, pnHeight);
75552    heightOfExpr(p->pHaving, pnHeight);
75553    heightOfExpr(p->pLimit, pnHeight);
75554    heightOfExpr(p->pOffset, pnHeight);
75555    heightOfExprList(p->pEList, pnHeight);
75556    heightOfExprList(p->pGroupBy, pnHeight);
75557    heightOfExprList(p->pOrderBy, pnHeight);
75558    heightOfSelect(p->pPrior, pnHeight);
75559  }
75560}
75561
75562/*
75563** Set the Expr.nHeight variable in the structure passed as an
75564** argument. An expression with no children, Expr.pList or
75565** Expr.pSelect member has a height of 1. Any other expression
75566** has a height equal to the maximum height of any other
75567** referenced Expr plus one.
75568*/
75569static void exprSetHeight(Expr *p){
75570  int nHeight = 0;
75571  heightOfExpr(p->pLeft, &nHeight);
75572  heightOfExpr(p->pRight, &nHeight);
75573  if( ExprHasProperty(p, EP_xIsSelect) ){
75574    heightOfSelect(p->x.pSelect, &nHeight);
75575  }else{
75576    heightOfExprList(p->x.pList, &nHeight);
75577  }
75578  p->nHeight = nHeight + 1;
75579}
75580
75581/*
75582** Set the Expr.nHeight variable using the exprSetHeight() function. If
75583** the height is greater than the maximum allowed expression depth,
75584** leave an error in pParse.
75585*/
75586SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
75587  exprSetHeight(p);
75588  sqlite3ExprCheckHeight(pParse, p->nHeight);
75589}
75590
75591/*
75592** Return the maximum height of any expression tree referenced
75593** by the select statement passed as an argument.
75594*/
75595SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
75596  int nHeight = 0;
75597  heightOfSelect(p, &nHeight);
75598  return nHeight;
75599}
75600#else
75601  #define exprSetHeight(y)
75602#endif /* SQLITE_MAX_EXPR_DEPTH>0 */
75603
75604/*
75605** This routine is the core allocator for Expr nodes.
75606**
75607** Construct a new expression node and return a pointer to it.  Memory
75608** for this node and for the pToken argument is a single allocation
75609** obtained from sqlite3DbMalloc().  The calling function
75610** is responsible for making sure the node eventually gets freed.
75611**
75612** If dequote is true, then the token (if it exists) is dequoted.
75613** If dequote is false, no dequoting is performance.  The deQuote
75614** parameter is ignored if pToken is NULL or if the token does not
75615** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
75616** then the EP_DblQuoted flag is set on the expression node.
75617**
75618** Special case:  If op==TK_INTEGER and pToken points to a string that
75619** can be translated into a 32-bit integer, then the token is not
75620** stored in u.zToken.  Instead, the integer values is written
75621** into u.iValue and the EP_IntValue flag is set.  No extra storage
75622** is allocated to hold the integer text and the dequote flag is ignored.
75623*/
75624SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
75625  sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
75626  int op,                 /* Expression opcode */
75627  const Token *pToken,    /* Token argument.  Might be NULL */
75628  int dequote             /* True to dequote */
75629){
75630  Expr *pNew;
75631  int nExtra = 0;
75632  int iValue = 0;
75633
75634  if( pToken ){
75635    if( op!=TK_INTEGER || pToken->z==0
75636          || sqlite3GetInt32(pToken->z, &iValue)==0 ){
75637      nExtra = pToken->n+1;
75638      assert( iValue>=0 );
75639    }
75640  }
75641  pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
75642  if( pNew ){
75643    pNew->op = (u8)op;
75644    pNew->iAgg = -1;
75645    if( pToken ){
75646      if( nExtra==0 ){
75647        pNew->flags |= EP_IntValue;
75648        pNew->u.iValue = iValue;
75649      }else{
75650        int c;
75651        pNew->u.zToken = (char*)&pNew[1];
75652        assert( pToken->z!=0 || pToken->n==0 );
75653        if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
75654        pNew->u.zToken[pToken->n] = 0;
75655        if( dequote && nExtra>=3
75656             && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
75657          sqlite3Dequote(pNew->u.zToken);
75658          if( c=='"' ) pNew->flags |= EP_DblQuoted;
75659        }
75660      }
75661    }
75662#if SQLITE_MAX_EXPR_DEPTH>0
75663    pNew->nHeight = 1;
75664#endif
75665  }
75666  return pNew;
75667}
75668
75669/*
75670** Allocate a new expression node from a zero-terminated token that has
75671** already been dequoted.
75672*/
75673SQLITE_PRIVATE Expr *sqlite3Expr(
75674  sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
75675  int op,                 /* Expression opcode */
75676  const char *zToken      /* Token argument.  Might be NULL */
75677){
75678  Token x;
75679  x.z = zToken;
75680  x.n = zToken ? sqlite3Strlen30(zToken) : 0;
75681  return sqlite3ExprAlloc(db, op, &x, 0);
75682}
75683
75684/*
75685** Attach subtrees pLeft and pRight to the Expr node pRoot.
75686**
75687** If pRoot==NULL that means that a memory allocation error has occurred.
75688** In that case, delete the subtrees pLeft and pRight.
75689*/
75690SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
75691  sqlite3 *db,
75692  Expr *pRoot,
75693  Expr *pLeft,
75694  Expr *pRight
75695){
75696  if( pRoot==0 ){
75697    assert( db->mallocFailed );
75698    sqlite3ExprDelete(db, pLeft);
75699    sqlite3ExprDelete(db, pRight);
75700  }else{
75701    if( pRight ){
75702      pRoot->pRight = pRight;
75703      pRoot->flags |= EP_Collate & pRight->flags;
75704    }
75705    if( pLeft ){
75706      pRoot->pLeft = pLeft;
75707      pRoot->flags |= EP_Collate & pLeft->flags;
75708    }
75709    exprSetHeight(pRoot);
75710  }
75711}
75712
75713/*
75714** Allocate a Expr node which joins as many as two subtrees.
75715**
75716** One or both of the subtrees can be NULL.  Return a pointer to the new
75717** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
75718** free the subtrees and return NULL.
75719*/
75720SQLITE_PRIVATE Expr *sqlite3PExpr(
75721  Parse *pParse,          /* Parsing context */
75722  int op,                 /* Expression opcode */
75723  Expr *pLeft,            /* Left operand */
75724  Expr *pRight,           /* Right operand */
75725  const Token *pToken     /* Argument token */
75726){
75727  Expr *p;
75728  if( op==TK_AND && pLeft && pRight ){
75729    /* Take advantage of short-circuit false optimization for AND */
75730    p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
75731  }else{
75732    p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
75733    sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
75734  }
75735  if( p ) {
75736    sqlite3ExprCheckHeight(pParse, p->nHeight);
75737  }
75738  return p;
75739}
75740
75741/*
75742** Return 1 if an expression must be FALSE in all cases and 0 if the
75743** expression might be true.  This is an optimization.  If is OK to
75744** return 0 here even if the expression really is always false (a
75745** false negative).  But it is a bug to return 1 if the expression
75746** might be true in some rare circumstances (a false positive.)
75747**
75748** Note that if the expression is part of conditional for a
75749** LEFT JOIN, then we cannot determine at compile-time whether or not
75750** is it true or false, so always return 0.
75751*/
75752static int exprAlwaysFalse(Expr *p){
75753  int v = 0;
75754  if( ExprHasProperty(p, EP_FromJoin) ) return 0;
75755  if( !sqlite3ExprIsInteger(p, &v) ) return 0;
75756  return v==0;
75757}
75758
75759/*
75760** Join two expressions using an AND operator.  If either expression is
75761** NULL, then just return the other expression.
75762**
75763** If one side or the other of the AND is known to be false, then instead
75764** of returning an AND expression, just return a constant expression with
75765** a value of false.
75766*/
75767SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
75768  if( pLeft==0 ){
75769    return pRight;
75770  }else if( pRight==0 ){
75771    return pLeft;
75772  }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
75773    sqlite3ExprDelete(db, pLeft);
75774    sqlite3ExprDelete(db, pRight);
75775    return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
75776  }else{
75777    Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
75778    sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
75779    return pNew;
75780  }
75781}
75782
75783/*
75784** Construct a new expression node for a function with multiple
75785** arguments.
75786*/
75787SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
75788  Expr *pNew;
75789  sqlite3 *db = pParse->db;
75790  assert( pToken );
75791  pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
75792  if( pNew==0 ){
75793    sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
75794    return 0;
75795  }
75796  pNew->x.pList = pList;
75797  assert( !ExprHasProperty(pNew, EP_xIsSelect) );
75798  sqlite3ExprSetHeight(pParse, pNew);
75799  return pNew;
75800}
75801
75802/*
75803** Assign a variable number to an expression that encodes a wildcard
75804** in the original SQL statement.
75805**
75806** Wildcards consisting of a single "?" are assigned the next sequential
75807** variable number.
75808**
75809** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
75810** sure "nnn" is not too be to avoid a denial of service attack when
75811** the SQL statement comes from an external source.
75812**
75813** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
75814** as the previous instance of the same wildcard.  Or if this is the first
75815** instance of the wildcard, the next sequenial variable number is
75816** assigned.
75817*/
75818SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
75819  sqlite3 *db = pParse->db;
75820  const char *z;
75821
75822  if( pExpr==0 ) return;
75823  assert( !ExprHasAnyProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
75824  z = pExpr->u.zToken;
75825  assert( z!=0 );
75826  assert( z[0]!=0 );
75827  if( z[1]==0 ){
75828    /* Wildcard of the form "?".  Assign the next variable number */
75829    assert( z[0]=='?' );
75830    pExpr->iColumn = (ynVar)(++pParse->nVar);
75831  }else{
75832    ynVar x = 0;
75833    u32 n = sqlite3Strlen30(z);
75834    if( z[0]=='?' ){
75835      /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
75836      ** use it as the variable number */
75837      i64 i;
75838      int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
75839      pExpr->iColumn = x = (ynVar)i;
75840      testcase( i==0 );
75841      testcase( i==1 );
75842      testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
75843      testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
75844      if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
75845        sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
75846            db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
75847        x = 0;
75848      }
75849      if( i>pParse->nVar ){
75850        pParse->nVar = (int)i;
75851      }
75852    }else{
75853      /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
75854      ** number as the prior appearance of the same name, or if the name
75855      ** has never appeared before, reuse the same variable number
75856      */
75857      ynVar i;
75858      for(i=0; i<pParse->nzVar; i++){
75859        if( pParse->azVar[i] && strcmp(pParse->azVar[i],z)==0 ){
75860          pExpr->iColumn = x = (ynVar)i+1;
75861          break;
75862        }
75863      }
75864      if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
75865    }
75866    if( x>0 ){
75867      if( x>pParse->nzVar ){
75868        char **a;
75869        a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
75870        if( a==0 ) return;  /* Error reported through db->mallocFailed */
75871        pParse->azVar = a;
75872        memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
75873        pParse->nzVar = x;
75874      }
75875      if( z[0]!='?' || pParse->azVar[x-1]==0 ){
75876        sqlite3DbFree(db, pParse->azVar[x-1]);
75877        pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
75878      }
75879    }
75880  }
75881  if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
75882    sqlite3ErrorMsg(pParse, "too many SQL variables");
75883  }
75884}
75885
75886/*
75887** Recursively delete an expression tree.
75888*/
75889SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
75890  if( p==0 ) return;
75891  /* Sanity check: Assert that the IntValue is non-negative if it exists */
75892  assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
75893  if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
75894    sqlite3ExprDelete(db, p->pLeft);
75895    sqlite3ExprDelete(db, p->pRight);
75896    if( !ExprHasProperty(p, EP_Reduced) && (p->flags2 & EP2_MallocedToken)!=0 ){
75897      sqlite3DbFree(db, p->u.zToken);
75898    }
75899    if( ExprHasProperty(p, EP_xIsSelect) ){
75900      sqlite3SelectDelete(db, p->x.pSelect);
75901    }else{
75902      sqlite3ExprListDelete(db, p->x.pList);
75903    }
75904  }
75905  if( !ExprHasProperty(p, EP_Static) ){
75906    sqlite3DbFree(db, p);
75907  }
75908}
75909
75910/*
75911** Return the number of bytes allocated for the expression structure
75912** passed as the first argument. This is always one of EXPR_FULLSIZE,
75913** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
75914*/
75915static int exprStructSize(Expr *p){
75916  if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
75917  if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
75918  return EXPR_FULLSIZE;
75919}
75920
75921/*
75922** The dupedExpr*Size() routines each return the number of bytes required
75923** to store a copy of an expression or expression tree.  They differ in
75924** how much of the tree is measured.
75925**
75926**     dupedExprStructSize()     Size of only the Expr structure
75927**     dupedExprNodeSize()       Size of Expr + space for token
75928**     dupedExprSize()           Expr + token + subtree components
75929**
75930***************************************************************************
75931**
75932** The dupedExprStructSize() function returns two values OR-ed together:
75933** (1) the space required for a copy of the Expr structure only and
75934** (2) the EP_xxx flags that indicate what the structure size should be.
75935** The return values is always one of:
75936**
75937**      EXPR_FULLSIZE
75938**      EXPR_REDUCEDSIZE   | EP_Reduced
75939**      EXPR_TOKENONLYSIZE | EP_TokenOnly
75940**
75941** The size of the structure can be found by masking the return value
75942** of this routine with 0xfff.  The flags can be found by masking the
75943** return value with EP_Reduced|EP_TokenOnly.
75944**
75945** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
75946** (unreduced) Expr objects as they or originally constructed by the parser.
75947** During expression analysis, extra information is computed and moved into
75948** later parts of teh Expr object and that extra information might get chopped
75949** off if the expression is reduced.  Note also that it does not work to
75950** make a EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
75951** to reduce a pristine expression tree from the parser.  The implementation
75952** of dupedExprStructSize() contain multiple assert() statements that attempt
75953** to enforce this constraint.
75954*/
75955static int dupedExprStructSize(Expr *p, int flags){
75956  int nSize;
75957  assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
75958  if( 0==(flags&EXPRDUP_REDUCE) ){
75959    nSize = EXPR_FULLSIZE;
75960  }else{
75961    assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
75962    assert( !ExprHasProperty(p, EP_FromJoin) );
75963    assert( (p->flags2 & EP2_MallocedToken)==0 );
75964    assert( (p->flags2 & EP2_Irreducible)==0 );
75965    if( p->pLeft || p->pRight || p->x.pList ){
75966      nSize = EXPR_REDUCEDSIZE | EP_Reduced;
75967    }else{
75968      nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
75969    }
75970  }
75971  return nSize;
75972}
75973
75974/*
75975** This function returns the space in bytes required to store the copy
75976** of the Expr structure and a copy of the Expr.u.zToken string (if that
75977** string is defined.)
75978*/
75979static int dupedExprNodeSize(Expr *p, int flags){
75980  int nByte = dupedExprStructSize(p, flags) & 0xfff;
75981  if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
75982    nByte += sqlite3Strlen30(p->u.zToken)+1;
75983  }
75984  return ROUND8(nByte);
75985}
75986
75987/*
75988** Return the number of bytes required to create a duplicate of the
75989** expression passed as the first argument. The second argument is a
75990** mask containing EXPRDUP_XXX flags.
75991**
75992** The value returned includes space to create a copy of the Expr struct
75993** itself and the buffer referred to by Expr.u.zToken, if any.
75994**
75995** If the EXPRDUP_REDUCE flag is set, then the return value includes
75996** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
75997** and Expr.pRight variables (but not for any structures pointed to or
75998** descended from the Expr.x.pList or Expr.x.pSelect variables).
75999*/
76000static int dupedExprSize(Expr *p, int flags){
76001  int nByte = 0;
76002  if( p ){
76003    nByte = dupedExprNodeSize(p, flags);
76004    if( flags&EXPRDUP_REDUCE ){
76005      nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
76006    }
76007  }
76008  return nByte;
76009}
76010
76011/*
76012** This function is similar to sqlite3ExprDup(), except that if pzBuffer
76013** is not NULL then *pzBuffer is assumed to point to a buffer large enough
76014** to store the copy of expression p, the copies of p->u.zToken
76015** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
76016** if any. Before returning, *pzBuffer is set to the first byte passed the
76017** portion of the buffer copied into by this function.
76018*/
76019static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
76020  Expr *pNew = 0;                      /* Value to return */
76021  if( p ){
76022    const int isReduced = (flags&EXPRDUP_REDUCE);
76023    u8 *zAlloc;
76024    u32 staticFlag = 0;
76025
76026    assert( pzBuffer==0 || isReduced );
76027
76028    /* Figure out where to write the new Expr structure. */
76029    if( pzBuffer ){
76030      zAlloc = *pzBuffer;
76031      staticFlag = EP_Static;
76032    }else{
76033      zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
76034    }
76035    pNew = (Expr *)zAlloc;
76036
76037    if( pNew ){
76038      /* Set nNewSize to the size allocated for the structure pointed to
76039      ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
76040      ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
76041      ** by the copy of the p->u.zToken string (if any).
76042      */
76043      const unsigned nStructSize = dupedExprStructSize(p, flags);
76044      const int nNewSize = nStructSize & 0xfff;
76045      int nToken;
76046      if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
76047        nToken = sqlite3Strlen30(p->u.zToken) + 1;
76048      }else{
76049        nToken = 0;
76050      }
76051      if( isReduced ){
76052        assert( ExprHasProperty(p, EP_Reduced)==0 );
76053        memcpy(zAlloc, p, nNewSize);
76054      }else{
76055        int nSize = exprStructSize(p);
76056        memcpy(zAlloc, p, nSize);
76057        memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
76058      }
76059
76060      /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
76061      pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
76062      pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
76063      pNew->flags |= staticFlag;
76064
76065      /* Copy the p->u.zToken string, if any. */
76066      if( nToken ){
76067        char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
76068        memcpy(zToken, p->u.zToken, nToken);
76069      }
76070
76071      if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
76072        /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
76073        if( ExprHasProperty(p, EP_xIsSelect) ){
76074          pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
76075        }else{
76076          pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
76077        }
76078      }
76079
76080      /* Fill in pNew->pLeft and pNew->pRight. */
76081      if( ExprHasAnyProperty(pNew, EP_Reduced|EP_TokenOnly) ){
76082        zAlloc += dupedExprNodeSize(p, flags);
76083        if( ExprHasProperty(pNew, EP_Reduced) ){
76084          pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
76085          pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
76086        }
76087        if( pzBuffer ){
76088          *pzBuffer = zAlloc;
76089        }
76090      }else{
76091        pNew->flags2 = 0;
76092        if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
76093          pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
76094          pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
76095        }
76096      }
76097
76098    }
76099  }
76100  return pNew;
76101}
76102
76103/*
76104** The following group of routines make deep copies of expressions,
76105** expression lists, ID lists, and select statements.  The copies can
76106** be deleted (by being passed to their respective ...Delete() routines)
76107** without effecting the originals.
76108**
76109** The expression list, ID, and source lists return by sqlite3ExprListDup(),
76110** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
76111** by subsequent calls to sqlite*ListAppend() routines.
76112**
76113** Any tables that the SrcList might point to are not duplicated.
76114**
76115** The flags parameter contains a combination of the EXPRDUP_XXX flags.
76116** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
76117** truncated version of the usual Expr structure that will be stored as
76118** part of the in-memory representation of the database schema.
76119*/
76120SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
76121  return exprDup(db, p, flags, 0);
76122}
76123SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
76124  ExprList *pNew;
76125  struct ExprList_item *pItem, *pOldItem;
76126  int i;
76127  if( p==0 ) return 0;
76128  pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
76129  if( pNew==0 ) return 0;
76130  pNew->iECursor = 0;
76131  pNew->nExpr = i = p->nExpr;
76132  if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
76133  pNew->a = pItem = sqlite3DbMallocRaw(db,  i*sizeof(p->a[0]) );
76134  if( pItem==0 ){
76135    sqlite3DbFree(db, pNew);
76136    return 0;
76137  }
76138  pOldItem = p->a;
76139  for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
76140    Expr *pOldExpr = pOldItem->pExpr;
76141    pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
76142    pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
76143    pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
76144    pItem->sortOrder = pOldItem->sortOrder;
76145    pItem->done = 0;
76146    pItem->iOrderByCol = pOldItem->iOrderByCol;
76147    pItem->iAlias = pOldItem->iAlias;
76148  }
76149  return pNew;
76150}
76151
76152/*
76153** If cursors, triggers, views and subqueries are all omitted from
76154** the build, then none of the following routines, except for
76155** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
76156** called with a NULL argument.
76157*/
76158#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
76159 || !defined(SQLITE_OMIT_SUBQUERY)
76160SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
76161  SrcList *pNew;
76162  int i;
76163  int nByte;
76164  if( p==0 ) return 0;
76165  nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
76166  pNew = sqlite3DbMallocRaw(db, nByte );
76167  if( pNew==0 ) return 0;
76168  pNew->nSrc = pNew->nAlloc = p->nSrc;
76169  for(i=0; i<p->nSrc; i++){
76170    struct SrcList_item *pNewItem = &pNew->a[i];
76171    struct SrcList_item *pOldItem = &p->a[i];
76172    Table *pTab;
76173    pNewItem->pSchema = pOldItem->pSchema;
76174    pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
76175    pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
76176    pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
76177    pNewItem->jointype = pOldItem->jointype;
76178    pNewItem->iCursor = pOldItem->iCursor;
76179    pNewItem->addrFillSub = pOldItem->addrFillSub;
76180    pNewItem->regReturn = pOldItem->regReturn;
76181    pNewItem->isCorrelated = pOldItem->isCorrelated;
76182    pNewItem->viaCoroutine = pOldItem->viaCoroutine;
76183    pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
76184    pNewItem->notIndexed = pOldItem->notIndexed;
76185    pNewItem->pIndex = pOldItem->pIndex;
76186    pTab = pNewItem->pTab = pOldItem->pTab;
76187    if( pTab ){
76188      pTab->nRef++;
76189    }
76190    pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
76191    pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
76192    pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
76193    pNewItem->colUsed = pOldItem->colUsed;
76194  }
76195  return pNew;
76196}
76197SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
76198  IdList *pNew;
76199  int i;
76200  if( p==0 ) return 0;
76201  pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
76202  if( pNew==0 ) return 0;
76203  pNew->nId = p->nId;
76204  pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
76205  if( pNew->a==0 ){
76206    sqlite3DbFree(db, pNew);
76207    return 0;
76208  }
76209  /* Note that because the size of the allocation for p->a[] is not
76210  ** necessarily a power of two, sqlite3IdListAppend() may not be called
76211  ** on the duplicate created by this function. */
76212  for(i=0; i<p->nId; i++){
76213    struct IdList_item *pNewItem = &pNew->a[i];
76214    struct IdList_item *pOldItem = &p->a[i];
76215    pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
76216    pNewItem->idx = pOldItem->idx;
76217  }
76218  return pNew;
76219}
76220SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
76221  Select *pNew, *pPrior;
76222  if( p==0 ) return 0;
76223  pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
76224  if( pNew==0 ) return 0;
76225  pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
76226  pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
76227  pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
76228  pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
76229  pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
76230  pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
76231  pNew->op = p->op;
76232  pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
76233  if( pPrior ) pPrior->pNext = pNew;
76234  pNew->pNext = 0;
76235  pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
76236  pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
76237  pNew->iLimit = 0;
76238  pNew->iOffset = 0;
76239  pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
76240  pNew->pRightmost = 0;
76241  pNew->addrOpenEphm[0] = -1;
76242  pNew->addrOpenEphm[1] = -1;
76243  pNew->addrOpenEphm[2] = -1;
76244  return pNew;
76245}
76246#else
76247SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
76248  assert( p==0 );
76249  return 0;
76250}
76251#endif
76252
76253
76254/*
76255** Add a new element to the end of an expression list.  If pList is
76256** initially NULL, then create a new expression list.
76257**
76258** If a memory allocation error occurs, the entire list is freed and
76259** NULL is returned.  If non-NULL is returned, then it is guaranteed
76260** that the new entry was successfully appended.
76261*/
76262SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
76263  Parse *pParse,          /* Parsing context */
76264  ExprList *pList,        /* List to which to append. Might be NULL */
76265  Expr *pExpr             /* Expression to be appended. Might be NULL */
76266){
76267  sqlite3 *db = pParse->db;
76268  if( pList==0 ){
76269    pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
76270    if( pList==0 ){
76271      goto no_mem;
76272    }
76273    pList->a = sqlite3DbMallocRaw(db, sizeof(pList->a[0]));
76274    if( pList->a==0 ) goto no_mem;
76275  }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
76276    struct ExprList_item *a;
76277    assert( pList->nExpr>0 );
76278    a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
76279    if( a==0 ){
76280      goto no_mem;
76281    }
76282    pList->a = a;
76283  }
76284  assert( pList->a!=0 );
76285  if( 1 ){
76286    struct ExprList_item *pItem = &pList->a[pList->nExpr++];
76287    memset(pItem, 0, sizeof(*pItem));
76288    pItem->pExpr = pExpr;
76289  }
76290  return pList;
76291
76292no_mem:
76293  /* Avoid leaking memory if malloc has failed. */
76294  sqlite3ExprDelete(db, pExpr);
76295  sqlite3ExprListDelete(db, pList);
76296  return 0;
76297}
76298
76299/*
76300** Set the ExprList.a[].zName element of the most recently added item
76301** on the expression list.
76302**
76303** pList might be NULL following an OOM error.  But pName should never be
76304** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
76305** is set.
76306*/
76307SQLITE_PRIVATE void sqlite3ExprListSetName(
76308  Parse *pParse,          /* Parsing context */
76309  ExprList *pList,        /* List to which to add the span. */
76310  Token *pName,           /* Name to be added */
76311  int dequote             /* True to cause the name to be dequoted */
76312){
76313  assert( pList!=0 || pParse->db->mallocFailed!=0 );
76314  if( pList ){
76315    struct ExprList_item *pItem;
76316    assert( pList->nExpr>0 );
76317    pItem = &pList->a[pList->nExpr-1];
76318    assert( pItem->zName==0 );
76319    pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
76320    if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
76321  }
76322}
76323
76324/*
76325** Set the ExprList.a[].zSpan element of the most recently added item
76326** on the expression list.
76327**
76328** pList might be NULL following an OOM error.  But pSpan should never be
76329** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
76330** is set.
76331*/
76332SQLITE_PRIVATE void sqlite3ExprListSetSpan(
76333  Parse *pParse,          /* Parsing context */
76334  ExprList *pList,        /* List to which to add the span. */
76335  ExprSpan *pSpan         /* The span to be added */
76336){
76337  sqlite3 *db = pParse->db;
76338  assert( pList!=0 || db->mallocFailed!=0 );
76339  if( pList ){
76340    struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
76341    assert( pList->nExpr>0 );
76342    assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
76343    sqlite3DbFree(db, pItem->zSpan);
76344    pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
76345                                    (int)(pSpan->zEnd - pSpan->zStart));
76346  }
76347}
76348
76349/*
76350** If the expression list pEList contains more than iLimit elements,
76351** leave an error message in pParse.
76352*/
76353SQLITE_PRIVATE void sqlite3ExprListCheckLength(
76354  Parse *pParse,
76355  ExprList *pEList,
76356  const char *zObject
76357){
76358  int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
76359  testcase( pEList && pEList->nExpr==mx );
76360  testcase( pEList && pEList->nExpr==mx+1 );
76361  if( pEList && pEList->nExpr>mx ){
76362    sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
76363  }
76364}
76365
76366/*
76367** Delete an entire expression list.
76368*/
76369SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
76370  int i;
76371  struct ExprList_item *pItem;
76372  if( pList==0 ) return;
76373  assert( pList->a!=0 || pList->nExpr==0 );
76374  for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
76375    sqlite3ExprDelete(db, pItem->pExpr);
76376    sqlite3DbFree(db, pItem->zName);
76377    sqlite3DbFree(db, pItem->zSpan);
76378  }
76379  sqlite3DbFree(db, pList->a);
76380  sqlite3DbFree(db, pList);
76381}
76382
76383/*
76384** These routines are Walker callbacks.  Walker.u.pi is a pointer
76385** to an integer.  These routines are checking an expression to see
76386** if it is a constant.  Set *Walker.u.pi to 0 if the expression is
76387** not constant.
76388**
76389** These callback routines are used to implement the following:
76390**
76391**     sqlite3ExprIsConstant()
76392**     sqlite3ExprIsConstantNotJoin()
76393**     sqlite3ExprIsConstantOrFunction()
76394**
76395*/
76396static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
76397
76398  /* If pWalker->u.i is 3 then any term of the expression that comes from
76399  ** the ON or USING clauses of a join disqualifies the expression
76400  ** from being considered constant. */
76401  if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
76402    pWalker->u.i = 0;
76403    return WRC_Abort;
76404  }
76405
76406  switch( pExpr->op ){
76407    /* Consider functions to be constant if all their arguments are constant
76408    ** and pWalker->u.i==2 */
76409    case TK_FUNCTION:
76410      if( pWalker->u.i==2 ) return 0;
76411      /* Fall through */
76412    case TK_ID:
76413    case TK_COLUMN:
76414    case TK_AGG_FUNCTION:
76415    case TK_AGG_COLUMN:
76416      testcase( pExpr->op==TK_ID );
76417      testcase( pExpr->op==TK_COLUMN );
76418      testcase( pExpr->op==TK_AGG_FUNCTION );
76419      testcase( pExpr->op==TK_AGG_COLUMN );
76420      pWalker->u.i = 0;
76421      return WRC_Abort;
76422    default:
76423      testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
76424      testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
76425      return WRC_Continue;
76426  }
76427}
76428static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
76429  UNUSED_PARAMETER(NotUsed);
76430  pWalker->u.i = 0;
76431  return WRC_Abort;
76432}
76433static int exprIsConst(Expr *p, int initFlag){
76434  Walker w;
76435  memset(&w, 0, sizeof(w));
76436  w.u.i = initFlag;
76437  w.xExprCallback = exprNodeIsConstant;
76438  w.xSelectCallback = selectNodeIsConstant;
76439  sqlite3WalkExpr(&w, p);
76440  return w.u.i;
76441}
76442
76443/*
76444** Walk an expression tree.  Return 1 if the expression is constant
76445** and 0 if it involves variables or function calls.
76446**
76447** For the purposes of this function, a double-quoted string (ex: "abc")
76448** is considered a variable but a single-quoted string (ex: 'abc') is
76449** a constant.
76450*/
76451SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
76452  return exprIsConst(p, 1);
76453}
76454
76455/*
76456** Walk an expression tree.  Return 1 if the expression is constant
76457** that does no originate from the ON or USING clauses of a join.
76458** Return 0 if it involves variables or function calls or terms from
76459** an ON or USING clause.
76460*/
76461SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
76462  return exprIsConst(p, 3);
76463}
76464
76465/*
76466** Walk an expression tree.  Return 1 if the expression is constant
76467** or a function call with constant arguments.  Return and 0 if there
76468** are any variables.
76469**
76470** For the purposes of this function, a double-quoted string (ex: "abc")
76471** is considered a variable but a single-quoted string (ex: 'abc') is
76472** a constant.
76473*/
76474SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
76475  return exprIsConst(p, 2);
76476}
76477
76478/*
76479** If the expression p codes a constant integer that is small enough
76480** to fit in a 32-bit integer, return 1 and put the value of the integer
76481** in *pValue.  If the expression is not an integer or if it is too big
76482** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
76483*/
76484SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
76485  int rc = 0;
76486
76487  /* If an expression is an integer literal that fits in a signed 32-bit
76488  ** integer, then the EP_IntValue flag will have already been set */
76489  assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
76490           || sqlite3GetInt32(p->u.zToken, &rc)==0 );
76491
76492  if( p->flags & EP_IntValue ){
76493    *pValue = p->u.iValue;
76494    return 1;
76495  }
76496  switch( p->op ){
76497    case TK_UPLUS: {
76498      rc = sqlite3ExprIsInteger(p->pLeft, pValue);
76499      break;
76500    }
76501    case TK_UMINUS: {
76502      int v;
76503      if( sqlite3ExprIsInteger(p->pLeft, &v) ){
76504        *pValue = -v;
76505        rc = 1;
76506      }
76507      break;
76508    }
76509    default: break;
76510  }
76511  return rc;
76512}
76513
76514/*
76515** Return FALSE if there is no chance that the expression can be NULL.
76516**
76517** If the expression might be NULL or if the expression is too complex
76518** to tell return TRUE.
76519**
76520** This routine is used as an optimization, to skip OP_IsNull opcodes
76521** when we know that a value cannot be NULL.  Hence, a false positive
76522** (returning TRUE when in fact the expression can never be NULL) might
76523** be a small performance hit but is otherwise harmless.  On the other
76524** hand, a false negative (returning FALSE when the result could be NULL)
76525** will likely result in an incorrect answer.  So when in doubt, return
76526** TRUE.
76527*/
76528SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
76529  u8 op;
76530  while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
76531  op = p->op;
76532  if( op==TK_REGISTER ) op = p->op2;
76533  switch( op ){
76534    case TK_INTEGER:
76535    case TK_STRING:
76536    case TK_FLOAT:
76537    case TK_BLOB:
76538      return 0;
76539    default:
76540      return 1;
76541  }
76542}
76543
76544/*
76545** Generate an OP_IsNull instruction that tests register iReg and jumps
76546** to location iDest if the value in iReg is NULL.  The value in iReg
76547** was computed by pExpr.  If we can look at pExpr at compile-time and
76548** determine that it can never generate a NULL, then the OP_IsNull operation
76549** can be omitted.
76550*/
76551SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(
76552  Vdbe *v,            /* The VDBE under construction */
76553  const Expr *pExpr,  /* Only generate OP_IsNull if this expr can be NULL */
76554  int iReg,           /* Test the value in this register for NULL */
76555  int iDest           /* Jump here if the value is null */
76556){
76557  if( sqlite3ExprCanBeNull(pExpr) ){
76558    sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest);
76559  }
76560}
76561
76562/*
76563** Return TRUE if the given expression is a constant which would be
76564** unchanged by OP_Affinity with the affinity given in the second
76565** argument.
76566**
76567** This routine is used to determine if the OP_Affinity operation
76568** can be omitted.  When in doubt return FALSE.  A false negative
76569** is harmless.  A false positive, however, can result in the wrong
76570** answer.
76571*/
76572SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
76573  u8 op;
76574  if( aff==SQLITE_AFF_NONE ) return 1;
76575  while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
76576  op = p->op;
76577  if( op==TK_REGISTER ) op = p->op2;
76578  switch( op ){
76579    case TK_INTEGER: {
76580      return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
76581    }
76582    case TK_FLOAT: {
76583      return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
76584    }
76585    case TK_STRING: {
76586      return aff==SQLITE_AFF_TEXT;
76587    }
76588    case TK_BLOB: {
76589      return 1;
76590    }
76591    case TK_COLUMN: {
76592      assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
76593      return p->iColumn<0
76594          && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
76595    }
76596    default: {
76597      return 0;
76598    }
76599  }
76600}
76601
76602/*
76603** Return TRUE if the given string is a row-id column name.
76604*/
76605SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
76606  if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
76607  if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
76608  if( sqlite3StrICmp(z, "OID")==0 ) return 1;
76609  return 0;
76610}
76611
76612/*
76613** Return true if we are able to the IN operator optimization on a
76614** query of the form
76615**
76616**       x IN (SELECT ...)
76617**
76618** Where the SELECT... clause is as specified by the parameter to this
76619** routine.
76620**
76621** The Select object passed in has already been preprocessed and no
76622** errors have been found.
76623*/
76624#ifndef SQLITE_OMIT_SUBQUERY
76625static int isCandidateForInOpt(Select *p){
76626  SrcList *pSrc;
76627  ExprList *pEList;
76628  Table *pTab;
76629  if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
76630  if( p->pPrior ) return 0;              /* Not a compound SELECT */
76631  if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
76632    testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
76633    testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
76634    return 0; /* No DISTINCT keyword and no aggregate functions */
76635  }
76636  assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
76637  if( p->pLimit ) return 0;              /* Has no LIMIT clause */
76638  assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
76639  if( p->pWhere ) return 0;              /* Has no WHERE clause */
76640  pSrc = p->pSrc;
76641  assert( pSrc!=0 );
76642  if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
76643  if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
76644  pTab = pSrc->a[0].pTab;
76645  if( NEVER(pTab==0) ) return 0;
76646  assert( pTab->pSelect==0 );            /* FROM clause is not a view */
76647  if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
76648  pEList = p->pEList;
76649  if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
76650  if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
76651  return 1;
76652}
76653#endif /* SQLITE_OMIT_SUBQUERY */
76654
76655/*
76656** Code an OP_Once instruction and allocate space for its flag. Return the
76657** address of the new instruction.
76658*/
76659SQLITE_PRIVATE int sqlite3CodeOnce(Parse *pParse){
76660  Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */
76661  return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
76662}
76663
76664/*
76665** This function is used by the implementation of the IN (...) operator.
76666** The pX parameter is the expression on the RHS of the IN operator, which
76667** might be either a list of expressions or a subquery.
76668**
76669** The job of this routine is to find or create a b-tree object that can
76670** be used either to test for membership in the RHS set or to iterate through
76671** all members of the RHS set, skipping duplicates.
76672**
76673** A cursor is opened on the b-tree object that the RHS of the IN operator
76674** and pX->iTable is set to the index of that cursor.
76675**
76676** The returned value of this function indicates the b-tree type, as follows:
76677**
76678**   IN_INDEX_ROWID      - The cursor was opened on a database table.
76679**   IN_INDEX_INDEX_ASC  - The cursor was opened on an ascending index.
76680**   IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
76681**   IN_INDEX_EPH        - The cursor was opened on a specially created and
76682**                         populated epheremal table.
76683**
76684** An existing b-tree might be used if the RHS expression pX is a simple
76685** subquery such as:
76686**
76687**     SELECT <column> FROM <table>
76688**
76689** If the RHS of the IN operator is a list or a more complex subquery, then
76690** an ephemeral table might need to be generated from the RHS and then
76691** pX->iTable made to point to the ephermeral table instead of an
76692** existing table.
76693**
76694** If the prNotFound parameter is 0, then the b-tree will be used to iterate
76695** through the set members, skipping any duplicates. In this case an
76696** epheremal table must be used unless the selected <column> is guaranteed
76697** to be unique - either because it is an INTEGER PRIMARY KEY or it
76698** has a UNIQUE constraint or UNIQUE index.
76699**
76700** If the prNotFound parameter is not 0, then the b-tree will be used
76701** for fast set membership tests. In this case an epheremal table must
76702** be used unless <column> is an INTEGER PRIMARY KEY or an index can
76703** be found with <column> as its left-most column.
76704**
76705** When the b-tree is being used for membership tests, the calling function
76706** needs to know whether or not the structure contains an SQL NULL
76707** value in order to correctly evaluate expressions like "X IN (Y, Z)".
76708** If there is any chance that the (...) might contain a NULL value at
76709** runtime, then a register is allocated and the register number written
76710** to *prNotFound. If there is no chance that the (...) contains a
76711** NULL value, then *prNotFound is left unchanged.
76712**
76713** If a register is allocated and its location stored in *prNotFound, then
76714** its initial value is NULL.  If the (...) does not remain constant
76715** for the duration of the query (i.e. the SELECT within the (...)
76716** is a correlated subquery) then the value of the allocated register is
76717** reset to NULL each time the subquery is rerun. This allows the
76718** caller to use vdbe code equivalent to the following:
76719**
76720**   if( register==NULL ){
76721**     has_null = <test if data structure contains null>
76722**     register = 1
76723**   }
76724**
76725** in order to avoid running the <test if data structure contains null>
76726** test more often than is necessary.
76727*/
76728#ifndef SQLITE_OMIT_SUBQUERY
76729SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
76730  Select *p;                            /* SELECT to the right of IN operator */
76731  int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
76732  int iTab = pParse->nTab++;            /* Cursor of the RHS table */
76733  int mustBeUnique = (prNotFound==0);   /* True if RHS must be unique */
76734  Vdbe *v = sqlite3GetVdbe(pParse);     /* Virtual machine being coded */
76735
76736  assert( pX->op==TK_IN );
76737
76738  /* Check to see if an existing table or index can be used to
76739  ** satisfy the query.  This is preferable to generating a new
76740  ** ephemeral table.
76741  */
76742  p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
76743  if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
76744    sqlite3 *db = pParse->db;              /* Database connection */
76745    Table *pTab;                           /* Table <table>. */
76746    Expr *pExpr;                           /* Expression <column> */
76747    int iCol;                              /* Index of column <column> */
76748    int iDb;                               /* Database idx for pTab */
76749
76750    assert( p );                        /* Because of isCandidateForInOpt(p) */
76751    assert( p->pEList!=0 );             /* Because of isCandidateForInOpt(p) */
76752    assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
76753    assert( p->pSrc!=0 );               /* Because of isCandidateForInOpt(p) */
76754    pTab = p->pSrc->a[0].pTab;
76755    pExpr = p->pEList->a[0].pExpr;
76756    iCol = pExpr->iColumn;
76757
76758    /* Code an OP_VerifyCookie and OP_TableLock for <table>. */
76759    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
76760    sqlite3CodeVerifySchema(pParse, iDb);
76761    sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
76762
76763    /* This function is only called from two places. In both cases the vdbe
76764    ** has already been allocated. So assume sqlite3GetVdbe() is always
76765    ** successful here.
76766    */
76767    assert(v);
76768    if( iCol<0 ){
76769      int iAddr;
76770
76771      iAddr = sqlite3CodeOnce(pParse);
76772
76773      sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
76774      eType = IN_INDEX_ROWID;
76775
76776      sqlite3VdbeJumpHere(v, iAddr);
76777    }else{
76778      Index *pIdx;                         /* Iterator variable */
76779
76780      /* The collation sequence used by the comparison. If an index is to
76781      ** be used in place of a temp-table, it must be ordered according
76782      ** to this collation sequence.  */
76783      CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
76784
76785      /* Check that the affinity that will be used to perform the
76786      ** comparison is the same as the affinity of the column. If
76787      ** it is not, it is not possible to use any index.
76788      */
76789      int affinity_ok = sqlite3IndexAffinityOk(pX, pTab->aCol[iCol].affinity);
76790
76791      for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
76792        if( (pIdx->aiColumn[0]==iCol)
76793         && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
76794         && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
76795        ){
76796          int iAddr;
76797          char *pKey;
76798
76799          pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
76800          iAddr = sqlite3CodeOnce(pParse);
76801
76802          sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
76803                               pKey,P4_KEYINFO_HANDOFF);
76804          VdbeComment((v, "%s", pIdx->zName));
76805          assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
76806          eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
76807
76808          sqlite3VdbeJumpHere(v, iAddr);
76809          if( prNotFound && !pTab->aCol[iCol].notNull ){
76810            *prNotFound = ++pParse->nMem;
76811            sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
76812          }
76813        }
76814      }
76815    }
76816  }
76817
76818  if( eType==0 ){
76819    /* Could not found an existing table or index to use as the RHS b-tree.
76820    ** We will have to generate an ephemeral table to do the job.
76821    */
76822    double savedNQueryLoop = pParse->nQueryLoop;
76823    int rMayHaveNull = 0;
76824    eType = IN_INDEX_EPH;
76825    if( prNotFound ){
76826      *prNotFound = rMayHaveNull = ++pParse->nMem;
76827      sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
76828    }else{
76829      testcase( pParse->nQueryLoop>(double)1 );
76830      pParse->nQueryLoop = (double)1;
76831      if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
76832        eType = IN_INDEX_ROWID;
76833      }
76834    }
76835    sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
76836    pParse->nQueryLoop = savedNQueryLoop;
76837  }else{
76838    pX->iTable = iTab;
76839  }
76840  return eType;
76841}
76842#endif
76843
76844/*
76845** Generate code for scalar subqueries used as a subquery expression, EXISTS,
76846** or IN operators.  Examples:
76847**
76848**     (SELECT a FROM b)          -- subquery
76849**     EXISTS (SELECT a FROM b)   -- EXISTS subquery
76850**     x IN (4,5,11)              -- IN operator with list on right-hand side
76851**     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
76852**
76853** The pExpr parameter describes the expression that contains the IN
76854** operator or subquery.
76855**
76856** If parameter isRowid is non-zero, then expression pExpr is guaranteed
76857** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
76858** to some integer key column of a table B-Tree. In this case, use an
76859** intkey B-Tree to store the set of IN(...) values instead of the usual
76860** (slower) variable length keys B-Tree.
76861**
76862** If rMayHaveNull is non-zero, that means that the operation is an IN
76863** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
76864** Furthermore, the IN is in a WHERE clause and that we really want
76865** to iterate over the RHS of the IN operator in order to quickly locate
76866** all corresponding LHS elements.  All this routine does is initialize
76867** the register given by rMayHaveNull to NULL.  Calling routines will take
76868** care of changing this register value to non-NULL if the RHS is NULL-free.
76869**
76870** If rMayHaveNull is zero, that means that the subquery is being used
76871** for membership testing only.  There is no need to initialize any
76872** registers to indicate the presense or absence of NULLs on the RHS.
76873**
76874** For a SELECT or EXISTS operator, return the register that holds the
76875** result.  For IN operators or if an error occurs, the return value is 0.
76876*/
76877#ifndef SQLITE_OMIT_SUBQUERY
76878SQLITE_PRIVATE int sqlite3CodeSubselect(
76879  Parse *pParse,          /* Parsing context */
76880  Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
76881  int rMayHaveNull,       /* Register that records whether NULLs exist in RHS */
76882  int isRowid             /* If true, LHS of IN operator is a rowid */
76883){
76884  int testAddr = -1;                      /* One-time test address */
76885  int rReg = 0;                           /* Register storing resulting */
76886  Vdbe *v = sqlite3GetVdbe(pParse);
76887  if( NEVER(v==0) ) return 0;
76888  sqlite3ExprCachePush(pParse);
76889
76890  /* This code must be run in its entirety every time it is encountered
76891  ** if any of the following is true:
76892  **
76893  **    *  The right-hand side is a correlated subquery
76894  **    *  The right-hand side is an expression list containing variables
76895  **    *  We are inside a trigger
76896  **
76897  ** If all of the above are false, then we can run this code just once
76898  ** save the results, and reuse the same result on subsequent invocations.
76899  */
76900  if( !ExprHasAnyProperty(pExpr, EP_VarSelect) ){
76901    testAddr = sqlite3CodeOnce(pParse);
76902  }
76903
76904#ifndef SQLITE_OMIT_EXPLAIN
76905  if( pParse->explain==2 ){
76906    char *zMsg = sqlite3MPrintf(
76907        pParse->db, "EXECUTE %s%s SUBQUERY %d", testAddr>=0?"":"CORRELATED ",
76908        pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
76909    );
76910    sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
76911  }
76912#endif
76913
76914  switch( pExpr->op ){
76915    case TK_IN: {
76916      char affinity;              /* Affinity of the LHS of the IN */
76917      KeyInfo keyInfo;            /* Keyinfo for the generated table */
76918      static u8 sortOrder = 0;    /* Fake aSortOrder for keyInfo */
76919      int addr;                   /* Address of OP_OpenEphemeral instruction */
76920      Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
76921
76922      if( rMayHaveNull ){
76923        sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
76924      }
76925
76926      affinity = sqlite3ExprAffinity(pLeft);
76927
76928      /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
76929      ** expression it is handled the same way.  An ephemeral table is
76930      ** filled with single-field index keys representing the results
76931      ** from the SELECT or the <exprlist>.
76932      **
76933      ** If the 'x' expression is a column value, or the SELECT...
76934      ** statement returns a column value, then the affinity of that
76935      ** column is used to build the index keys. If both 'x' and the
76936      ** SELECT... statement are columns, then numeric affinity is used
76937      ** if either column has NUMERIC or INTEGER affinity. If neither
76938      ** 'x' nor the SELECT... statement are columns, then numeric affinity
76939      ** is used.
76940      */
76941      pExpr->iTable = pParse->nTab++;
76942      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
76943      if( rMayHaveNull==0 ) sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
76944      memset(&keyInfo, 0, sizeof(keyInfo));
76945      keyInfo.nField = 1;
76946      keyInfo.aSortOrder = &sortOrder;
76947
76948      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
76949        /* Case 1:     expr IN (SELECT ...)
76950        **
76951        ** Generate code to write the results of the select into the temporary
76952        ** table allocated and opened above.
76953        */
76954        SelectDest dest;
76955        ExprList *pEList;
76956
76957        assert( !isRowid );
76958        sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
76959        dest.affSdst = (u8)affinity;
76960        assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
76961        pExpr->x.pSelect->iLimit = 0;
76962        if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
76963          return 0;
76964        }
76965        pEList = pExpr->x.pSelect->pEList;
76966        if( ALWAYS(pEList!=0 && pEList->nExpr>0) ){
76967          keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
76968              pEList->a[0].pExpr);
76969        }
76970      }else if( ALWAYS(pExpr->x.pList!=0) ){
76971        /* Case 2:     expr IN (exprlist)
76972        **
76973        ** For each expression, build an index key from the evaluation and
76974        ** store it in the temporary table. If <expr> is a column, then use
76975        ** that columns affinity when building index keys. If <expr> is not
76976        ** a column, use numeric affinity.
76977        */
76978        int i;
76979        ExprList *pList = pExpr->x.pList;
76980        struct ExprList_item *pItem;
76981        int r1, r2, r3;
76982
76983        if( !affinity ){
76984          affinity = SQLITE_AFF_NONE;
76985        }
76986        keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
76987        keyInfo.aSortOrder = &sortOrder;
76988
76989        /* Loop through each expression in <exprlist>. */
76990        r1 = sqlite3GetTempReg(pParse);
76991        r2 = sqlite3GetTempReg(pParse);
76992        sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
76993        for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
76994          Expr *pE2 = pItem->pExpr;
76995          int iValToIns;
76996
76997          /* If the expression is not constant then we will need to
76998          ** disable the test that was generated above that makes sure
76999          ** this code only executes once.  Because for a non-constant
77000          ** expression we need to rerun this code each time.
77001          */
77002          if( testAddr>=0 && !sqlite3ExprIsConstant(pE2) ){
77003            sqlite3VdbeChangeToNoop(v, testAddr);
77004            testAddr = -1;
77005          }
77006
77007          /* Evaluate the expression and insert it into the temp table */
77008          if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
77009            sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
77010          }else{
77011            r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
77012            if( isRowid ){
77013              sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
77014                                sqlite3VdbeCurrentAddr(v)+2);
77015              sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
77016            }else{
77017              sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
77018              sqlite3ExprCacheAffinityChange(pParse, r3, 1);
77019              sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
77020            }
77021          }
77022        }
77023        sqlite3ReleaseTempReg(pParse, r1);
77024        sqlite3ReleaseTempReg(pParse, r2);
77025      }
77026      if( !isRowid ){
77027        sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
77028      }
77029      break;
77030    }
77031
77032    case TK_EXISTS:
77033    case TK_SELECT:
77034    default: {
77035      /* If this has to be a scalar SELECT.  Generate code to put the
77036      ** value of this select in a memory cell and record the number
77037      ** of the memory cell in iColumn.  If this is an EXISTS, write
77038      ** an integer 0 (not exists) or 1 (exists) into a memory cell
77039      ** and record that memory cell in iColumn.
77040      */
77041      Select *pSel;                         /* SELECT statement to encode */
77042      SelectDest dest;                      /* How to deal with SELECt result */
77043
77044      testcase( pExpr->op==TK_EXISTS );
77045      testcase( pExpr->op==TK_SELECT );
77046      assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
77047
77048      assert( ExprHasProperty(pExpr, EP_xIsSelect) );
77049      pSel = pExpr->x.pSelect;
77050      sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
77051      if( pExpr->op==TK_SELECT ){
77052        dest.eDest = SRT_Mem;
77053        sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iSDParm);
77054        VdbeComment((v, "Init subquery result"));
77055      }else{
77056        dest.eDest = SRT_Exists;
77057        sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
77058        VdbeComment((v, "Init EXISTS result"));
77059      }
77060      sqlite3ExprDelete(pParse->db, pSel->pLimit);
77061      pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
77062                                  &sqlite3IntTokens[1]);
77063      pSel->iLimit = 0;
77064      if( sqlite3Select(pParse, pSel, &dest) ){
77065        return 0;
77066      }
77067      rReg = dest.iSDParm;
77068      ExprSetIrreducible(pExpr);
77069      break;
77070    }
77071  }
77072
77073  if( testAddr>=0 ){
77074    sqlite3VdbeJumpHere(v, testAddr);
77075  }
77076  sqlite3ExprCachePop(pParse, 1);
77077
77078  return rReg;
77079}
77080#endif /* SQLITE_OMIT_SUBQUERY */
77081
77082#ifndef SQLITE_OMIT_SUBQUERY
77083/*
77084** Generate code for an IN expression.
77085**
77086**      x IN (SELECT ...)
77087**      x IN (value, value, ...)
77088**
77089** The left-hand side (LHS) is a scalar expression.  The right-hand side (RHS)
77090** is an array of zero or more values.  The expression is true if the LHS is
77091** contained within the RHS.  The value of the expression is unknown (NULL)
77092** if the LHS is NULL or if the LHS is not contained within the RHS and the
77093** RHS contains one or more NULL values.
77094**
77095** This routine generates code will jump to destIfFalse if the LHS is not
77096** contained within the RHS.  If due to NULLs we cannot determine if the LHS
77097** is contained in the RHS then jump to destIfNull.  If the LHS is contained
77098** within the RHS then fall through.
77099*/
77100static void sqlite3ExprCodeIN(
77101  Parse *pParse,        /* Parsing and code generating context */
77102  Expr *pExpr,          /* The IN expression */
77103  int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
77104  int destIfNull        /* Jump here if the results are unknown due to NULLs */
77105){
77106  int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
77107  char affinity;        /* Comparison affinity to use */
77108  int eType;            /* Type of the RHS */
77109  int r1;               /* Temporary use register */
77110  Vdbe *v;              /* Statement under construction */
77111
77112  /* Compute the RHS.   After this step, the table with cursor
77113  ** pExpr->iTable will contains the values that make up the RHS.
77114  */
77115  v = pParse->pVdbe;
77116  assert( v!=0 );       /* OOM detected prior to this routine */
77117  VdbeNoopComment((v, "begin IN expr"));
77118  eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull);
77119
77120  /* Figure out the affinity to use to create a key from the results
77121  ** of the expression. affinityStr stores a static string suitable for
77122  ** P4 of OP_MakeRecord.
77123  */
77124  affinity = comparisonAffinity(pExpr);
77125
77126  /* Code the LHS, the <expr> from "<expr> IN (...)".
77127  */
77128  sqlite3ExprCachePush(pParse);
77129  r1 = sqlite3GetTempReg(pParse);
77130  sqlite3ExprCode(pParse, pExpr->pLeft, r1);
77131
77132  /* If the LHS is NULL, then the result is either false or NULL depending
77133  ** on whether the RHS is empty or not, respectively.
77134  */
77135  if( destIfNull==destIfFalse ){
77136    /* Shortcut for the common case where the false and NULL outcomes are
77137    ** the same. */
77138    sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
77139  }else{
77140    int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1);
77141    sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
77142    sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
77143    sqlite3VdbeJumpHere(v, addr1);
77144  }
77145
77146  if( eType==IN_INDEX_ROWID ){
77147    /* In this case, the RHS is the ROWID of table b-tree
77148    */
77149    sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);
77150    sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
77151  }else{
77152    /* In this case, the RHS is an index b-tree.
77153    */
77154    sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
77155
77156    /* If the set membership test fails, then the result of the
77157    ** "x IN (...)" expression must be either 0 or NULL. If the set
77158    ** contains no NULL values, then the result is 0. If the set
77159    ** contains one or more NULL values, then the result of the
77160    ** expression is also NULL.
77161    */
77162    if( rRhsHasNull==0 || destIfFalse==destIfNull ){
77163      /* This branch runs if it is known at compile time that the RHS
77164      ** cannot contain NULL values. This happens as the result
77165      ** of a "NOT NULL" constraint in the database schema.
77166      **
77167      ** Also run this branch if NULL is equivalent to FALSE
77168      ** for this particular IN operator.
77169      */
77170      sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
77171
77172    }else{
77173      /* In this branch, the RHS of the IN might contain a NULL and
77174      ** the presence of a NULL on the RHS makes a difference in the
77175      ** outcome.
77176      */
77177      int j1, j2, j3;
77178
77179      /* First check to see if the LHS is contained in the RHS.  If so,
77180      ** then the presence of NULLs in the RHS does not matter, so jump
77181      ** over all of the code that follows.
77182      */
77183      j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
77184
77185      /* Here we begin generating code that runs if the LHS is not
77186      ** contained within the RHS.  Generate additional code that
77187      ** tests the RHS for NULLs.  If the RHS contains a NULL then
77188      ** jump to destIfNull.  If there are no NULLs in the RHS then
77189      ** jump to destIfFalse.
77190      */
77191      j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);
77192      j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
77193      sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);
77194      sqlite3VdbeJumpHere(v, j3);
77195      sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);
77196      sqlite3VdbeJumpHere(v, j2);
77197
77198      /* Jump to the appropriate target depending on whether or not
77199      ** the RHS contains a NULL
77200      */
77201      sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);
77202      sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
77203
77204      /* The OP_Found at the top of this branch jumps here when true,
77205      ** causing the overall IN expression evaluation to fall through.
77206      */
77207      sqlite3VdbeJumpHere(v, j1);
77208    }
77209  }
77210  sqlite3ReleaseTempReg(pParse, r1);
77211  sqlite3ExprCachePop(pParse, 1);
77212  VdbeComment((v, "end IN expr"));
77213}
77214#endif /* SQLITE_OMIT_SUBQUERY */
77215
77216/*
77217** Duplicate an 8-byte value
77218*/
77219static char *dup8bytes(Vdbe *v, const char *in){
77220  char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
77221  if( out ){
77222    memcpy(out, in, 8);
77223  }
77224  return out;
77225}
77226
77227#ifndef SQLITE_OMIT_FLOATING_POINT
77228/*
77229** Generate an instruction that will put the floating point
77230** value described by z[0..n-1] into register iMem.
77231**
77232** The z[] string will probably not be zero-terminated.  But the
77233** z[n] character is guaranteed to be something that does not look
77234** like the continuation of the number.
77235*/
77236static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
77237  if( ALWAYS(z!=0) ){
77238    double value;
77239    char *zV;
77240    sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
77241    assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
77242    if( negateFlag ) value = -value;
77243    zV = dup8bytes(v, (char*)&value);
77244    sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
77245  }
77246}
77247#endif
77248
77249
77250/*
77251** Generate an instruction that will put the integer describe by
77252** text z[0..n-1] into register iMem.
77253**
77254** Expr.u.zToken is always UTF8 and zero-terminated.
77255*/
77256static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
77257  Vdbe *v = pParse->pVdbe;
77258  if( pExpr->flags & EP_IntValue ){
77259    int i = pExpr->u.iValue;
77260    assert( i>=0 );
77261    if( negFlag ) i = -i;
77262    sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
77263  }else{
77264    int c;
77265    i64 value;
77266    const char *z = pExpr->u.zToken;
77267    assert( z!=0 );
77268    c = sqlite3Atoi64(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
77269    if( c==0 || (c==2 && negFlag) ){
77270      char *zV;
77271      if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
77272      zV = dup8bytes(v, (char*)&value);
77273      sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
77274    }else{
77275#ifdef SQLITE_OMIT_FLOATING_POINT
77276      sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
77277#else
77278      codeReal(v, z, negFlag, iMem);
77279#endif
77280    }
77281  }
77282}
77283
77284/*
77285** Clear a cache entry.
77286*/
77287static void cacheEntryClear(Parse *pParse, struct yColCache *p){
77288  if( p->tempReg ){
77289    if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
77290      pParse->aTempReg[pParse->nTempReg++] = p->iReg;
77291    }
77292    p->tempReg = 0;
77293  }
77294}
77295
77296
77297/*
77298** Record in the column cache that a particular column from a
77299** particular table is stored in a particular register.
77300*/
77301SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
77302  int i;
77303  int minLru;
77304  int idxLru;
77305  struct yColCache *p;
77306
77307  assert( iReg>0 );  /* Register numbers are always positive */
77308  assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
77309
77310  /* The SQLITE_ColumnCache flag disables the column cache.  This is used
77311  ** for testing only - to verify that SQLite always gets the same answer
77312  ** with and without the column cache.
77313  */
77314  if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
77315
77316  /* First replace any existing entry.
77317  **
77318  ** Actually, the way the column cache is currently used, we are guaranteed
77319  ** that the object will never already be in cache.  Verify this guarantee.
77320  */
77321#ifndef NDEBUG
77322  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
77323    assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
77324  }
77325#endif
77326
77327  /* Find an empty slot and replace it */
77328  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
77329    if( p->iReg==0 ){
77330      p->iLevel = pParse->iCacheLevel;
77331      p->iTable = iTab;
77332      p->iColumn = iCol;
77333      p->iReg = iReg;
77334      p->tempReg = 0;
77335      p->lru = pParse->iCacheCnt++;
77336      return;
77337    }
77338  }
77339
77340  /* Replace the last recently used */
77341  minLru = 0x7fffffff;
77342  idxLru = -1;
77343  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
77344    if( p->lru<minLru ){
77345      idxLru = i;
77346      minLru = p->lru;
77347    }
77348  }
77349  if( ALWAYS(idxLru>=0) ){
77350    p = &pParse->aColCache[idxLru];
77351    p->iLevel = pParse->iCacheLevel;
77352    p->iTable = iTab;
77353    p->iColumn = iCol;
77354    p->iReg = iReg;
77355    p->tempReg = 0;
77356    p->lru = pParse->iCacheCnt++;
77357    return;
77358  }
77359}
77360
77361/*
77362** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
77363** Purge the range of registers from the column cache.
77364*/
77365SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
77366  int i;
77367  int iLast = iReg + nReg - 1;
77368  struct yColCache *p;
77369  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
77370    int r = p->iReg;
77371    if( r>=iReg && r<=iLast ){
77372      cacheEntryClear(pParse, p);
77373      p->iReg = 0;
77374    }
77375  }
77376}
77377
77378/*
77379** Remember the current column cache context.  Any new entries added
77380** added to the column cache after this call are removed when the
77381** corresponding pop occurs.
77382*/
77383SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
77384  pParse->iCacheLevel++;
77385}
77386
77387/*
77388** Remove from the column cache any entries that were added since the
77389** the previous N Push operations.  In other words, restore the cache
77390** to the state it was in N Pushes ago.
77391*/
77392SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse, int N){
77393  int i;
77394  struct yColCache *p;
77395  assert( N>0 );
77396  assert( pParse->iCacheLevel>=N );
77397  pParse->iCacheLevel -= N;
77398  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
77399    if( p->iReg && p->iLevel>pParse->iCacheLevel ){
77400      cacheEntryClear(pParse, p);
77401      p->iReg = 0;
77402    }
77403  }
77404}
77405
77406/*
77407** When a cached column is reused, make sure that its register is
77408** no longer available as a temp register.  ticket #3879:  that same
77409** register might be in the cache in multiple places, so be sure to
77410** get them all.
77411*/
77412static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
77413  int i;
77414  struct yColCache *p;
77415  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
77416    if( p->iReg==iReg ){
77417      p->tempReg = 0;
77418    }
77419  }
77420}
77421
77422/*
77423** Generate code to extract the value of the iCol-th column of a table.
77424*/
77425SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
77426  Vdbe *v,        /* The VDBE under construction */
77427  Table *pTab,    /* The table containing the value */
77428  int iTabCur,    /* The cursor for this table */
77429  int iCol,       /* Index of the column to extract */
77430  int regOut      /* Extract the valud into this register */
77431){
77432  if( iCol<0 || iCol==pTab->iPKey ){
77433    sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
77434  }else{
77435    int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
77436    sqlite3VdbeAddOp3(v, op, iTabCur, iCol, regOut);
77437  }
77438  if( iCol>=0 ){
77439    sqlite3ColumnDefault(v, pTab, iCol, regOut);
77440  }
77441}
77442
77443/*
77444** Generate code that will extract the iColumn-th column from
77445** table pTab and store the column value in a register.  An effort
77446** is made to store the column value in register iReg, but this is
77447** not guaranteed.  The location of the column value is returned.
77448**
77449** There must be an open cursor to pTab in iTable when this routine
77450** is called.  If iColumn<0 then code is generated that extracts the rowid.
77451*/
77452SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
77453  Parse *pParse,   /* Parsing and code generating context */
77454  Table *pTab,     /* Description of the table we are reading from */
77455  int iColumn,     /* Index of the table column */
77456  int iTable,      /* The cursor pointing to the table */
77457  int iReg,        /* Store results here */
77458  u8 p5            /* P5 value for OP_Column */
77459){
77460  Vdbe *v = pParse->pVdbe;
77461  int i;
77462  struct yColCache *p;
77463
77464  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
77465    if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
77466      p->lru = pParse->iCacheCnt++;
77467      sqlite3ExprCachePinRegister(pParse, p->iReg);
77468      return p->iReg;
77469    }
77470  }
77471  assert( v!=0 );
77472  sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
77473  if( p5 ){
77474    sqlite3VdbeChangeP5(v, p5);
77475  }else{
77476    sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
77477  }
77478  return iReg;
77479}
77480
77481/*
77482** Clear all column cache entries.
77483*/
77484SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
77485  int i;
77486  struct yColCache *p;
77487
77488  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
77489    if( p->iReg ){
77490      cacheEntryClear(pParse, p);
77491      p->iReg = 0;
77492    }
77493  }
77494}
77495
77496/*
77497** Record the fact that an affinity change has occurred on iCount
77498** registers starting with iStart.
77499*/
77500SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
77501  sqlite3ExprCacheRemove(pParse, iStart, iCount);
77502}
77503
77504/*
77505** Generate code to move content from registers iFrom...iFrom+nReg-1
77506** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
77507*/
77508SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
77509  int i;
77510  struct yColCache *p;
77511  assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
77512  sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg-1);
77513  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
77514    int x = p->iReg;
77515    if( x>=iFrom && x<iFrom+nReg ){
77516      p->iReg += iTo-iFrom;
77517    }
77518  }
77519}
77520
77521#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
77522/*
77523** Return true if any register in the range iFrom..iTo (inclusive)
77524** is used as part of the column cache.
77525**
77526** This routine is used within assert() and testcase() macros only
77527** and does not appear in a normal build.
77528*/
77529static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
77530  int i;
77531  struct yColCache *p;
77532  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
77533    int r = p->iReg;
77534    if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
77535  }
77536  return 0;
77537}
77538#endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
77539
77540/*
77541** Generate code into the current Vdbe to evaluate the given
77542** expression.  Attempt to store the results in register "target".
77543** Return the register where results are stored.
77544**
77545** With this routine, there is no guarantee that results will
77546** be stored in target.  The result might be stored in some other
77547** register if it is convenient to do so.  The calling function
77548** must check the return code and move the results to the desired
77549** register.
77550*/
77551SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
77552  Vdbe *v = pParse->pVdbe;  /* The VM under construction */
77553  int op;                   /* The opcode being coded */
77554  int inReg = target;       /* Results stored in register inReg */
77555  int regFree1 = 0;         /* If non-zero free this temporary register */
77556  int regFree2 = 0;         /* If non-zero free this temporary register */
77557  int r1, r2, r3, r4;       /* Various register numbers */
77558  sqlite3 *db = pParse->db; /* The database connection */
77559
77560  assert( target>0 && target<=pParse->nMem );
77561  if( v==0 ){
77562    assert( pParse->db->mallocFailed );
77563    return 0;
77564  }
77565
77566  if( pExpr==0 ){
77567    op = TK_NULL;
77568  }else{
77569    op = pExpr->op;
77570  }
77571  switch( op ){
77572    case TK_AGG_COLUMN: {
77573      AggInfo *pAggInfo = pExpr->pAggInfo;
77574      struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
77575      if( !pAggInfo->directMode ){
77576        assert( pCol->iMem>0 );
77577        inReg = pCol->iMem;
77578        break;
77579      }else if( pAggInfo->useSortingIdx ){
77580        sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
77581                              pCol->iSorterColumn, target);
77582        break;
77583      }
77584      /* Otherwise, fall thru into the TK_COLUMN case */
77585    }
77586    case TK_COLUMN: {
77587      if( pExpr->iTable<0 ){
77588        /* This only happens when coding check constraints */
77589        assert( pParse->ckBase>0 );
77590        inReg = pExpr->iColumn + pParse->ckBase;
77591      }else{
77592        inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
77593                                 pExpr->iColumn, pExpr->iTable, target,
77594                                 pExpr->op2);
77595      }
77596      break;
77597    }
77598    case TK_INTEGER: {
77599      codeInteger(pParse, pExpr, 0, target);
77600      break;
77601    }
77602#ifndef SQLITE_OMIT_FLOATING_POINT
77603    case TK_FLOAT: {
77604      assert( !ExprHasProperty(pExpr, EP_IntValue) );
77605      codeReal(v, pExpr->u.zToken, 0, target);
77606      break;
77607    }
77608#endif
77609    case TK_STRING: {
77610      assert( !ExprHasProperty(pExpr, EP_IntValue) );
77611      sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
77612      break;
77613    }
77614    case TK_NULL: {
77615      sqlite3VdbeAddOp2(v, OP_Null, 0, target);
77616      break;
77617    }
77618#ifndef SQLITE_OMIT_BLOB_LITERAL
77619    case TK_BLOB: {
77620      int n;
77621      const char *z;
77622      char *zBlob;
77623      assert( !ExprHasProperty(pExpr, EP_IntValue) );
77624      assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
77625      assert( pExpr->u.zToken[1]=='\'' );
77626      z = &pExpr->u.zToken[2];
77627      n = sqlite3Strlen30(z) - 1;
77628      assert( z[n]=='\'' );
77629      zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
77630      sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
77631      break;
77632    }
77633#endif
77634    case TK_VARIABLE: {
77635      assert( !ExprHasProperty(pExpr, EP_IntValue) );
77636      assert( pExpr->u.zToken!=0 );
77637      assert( pExpr->u.zToken[0]!=0 );
77638      sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
77639      if( pExpr->u.zToken[1]!=0 ){
77640        assert( pExpr->u.zToken[0]=='?'
77641             || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
77642        sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
77643      }
77644      break;
77645    }
77646    case TK_REGISTER: {
77647      inReg = pExpr->iTable;
77648      break;
77649    }
77650    case TK_AS: {
77651      inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
77652      break;
77653    }
77654#ifndef SQLITE_OMIT_CAST
77655    case TK_CAST: {
77656      /* Expressions of the form:   CAST(pLeft AS token) */
77657      int aff, to_op;
77658      inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
77659      assert( !ExprHasProperty(pExpr, EP_IntValue) );
77660      aff = sqlite3AffinityType(pExpr->u.zToken);
77661      to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
77662      assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
77663      assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
77664      assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
77665      assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
77666      assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
77667      testcase( to_op==OP_ToText );
77668      testcase( to_op==OP_ToBlob );
77669      testcase( to_op==OP_ToNumeric );
77670      testcase( to_op==OP_ToInt );
77671      testcase( to_op==OP_ToReal );
77672      if( inReg!=target ){
77673        sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
77674        inReg = target;
77675      }
77676      sqlite3VdbeAddOp1(v, to_op, inReg);
77677      testcase( usedAsColumnCache(pParse, inReg, inReg) );
77678      sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
77679      break;
77680    }
77681#endif /* SQLITE_OMIT_CAST */
77682    case TK_LT:
77683    case TK_LE:
77684    case TK_GT:
77685    case TK_GE:
77686    case TK_NE:
77687    case TK_EQ: {
77688      assert( TK_LT==OP_Lt );
77689      assert( TK_LE==OP_Le );
77690      assert( TK_GT==OP_Gt );
77691      assert( TK_GE==OP_Ge );
77692      assert( TK_EQ==OP_Eq );
77693      assert( TK_NE==OP_Ne );
77694      testcase( op==TK_LT );
77695      testcase( op==TK_LE );
77696      testcase( op==TK_GT );
77697      testcase( op==TK_GE );
77698      testcase( op==TK_EQ );
77699      testcase( op==TK_NE );
77700      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77701      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
77702      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
77703                  r1, r2, inReg, SQLITE_STOREP2);
77704      testcase( regFree1==0 );
77705      testcase( regFree2==0 );
77706      break;
77707    }
77708    case TK_IS:
77709    case TK_ISNOT: {
77710      testcase( op==TK_IS );
77711      testcase( op==TK_ISNOT );
77712      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77713      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
77714      op = (op==TK_IS) ? TK_EQ : TK_NE;
77715      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
77716                  r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
77717      testcase( regFree1==0 );
77718      testcase( regFree2==0 );
77719      break;
77720    }
77721    case TK_AND:
77722    case TK_OR:
77723    case TK_PLUS:
77724    case TK_STAR:
77725    case TK_MINUS:
77726    case TK_REM:
77727    case TK_BITAND:
77728    case TK_BITOR:
77729    case TK_SLASH:
77730    case TK_LSHIFT:
77731    case TK_RSHIFT:
77732    case TK_CONCAT: {
77733      assert( TK_AND==OP_And );
77734      assert( TK_OR==OP_Or );
77735      assert( TK_PLUS==OP_Add );
77736      assert( TK_MINUS==OP_Subtract );
77737      assert( TK_REM==OP_Remainder );
77738      assert( TK_BITAND==OP_BitAnd );
77739      assert( TK_BITOR==OP_BitOr );
77740      assert( TK_SLASH==OP_Divide );
77741      assert( TK_LSHIFT==OP_ShiftLeft );
77742      assert( TK_RSHIFT==OP_ShiftRight );
77743      assert( TK_CONCAT==OP_Concat );
77744      testcase( op==TK_AND );
77745      testcase( op==TK_OR );
77746      testcase( op==TK_PLUS );
77747      testcase( op==TK_MINUS );
77748      testcase( op==TK_REM );
77749      testcase( op==TK_BITAND );
77750      testcase( op==TK_BITOR );
77751      testcase( op==TK_SLASH );
77752      testcase( op==TK_LSHIFT );
77753      testcase( op==TK_RSHIFT );
77754      testcase( op==TK_CONCAT );
77755      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77756      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
77757      sqlite3VdbeAddOp3(v, op, r2, r1, target);
77758      testcase( regFree1==0 );
77759      testcase( regFree2==0 );
77760      break;
77761    }
77762    case TK_UMINUS: {
77763      Expr *pLeft = pExpr->pLeft;
77764      assert( pLeft );
77765      if( pLeft->op==TK_INTEGER ){
77766        codeInteger(pParse, pLeft, 1, target);
77767#ifndef SQLITE_OMIT_FLOATING_POINT
77768      }else if( pLeft->op==TK_FLOAT ){
77769        assert( !ExprHasProperty(pExpr, EP_IntValue) );
77770        codeReal(v, pLeft->u.zToken, 1, target);
77771#endif
77772      }else{
77773        regFree1 = r1 = sqlite3GetTempReg(pParse);
77774        sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
77775        r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
77776        sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
77777        testcase( regFree2==0 );
77778      }
77779      inReg = target;
77780      break;
77781    }
77782    case TK_BITNOT:
77783    case TK_NOT: {
77784      assert( TK_BITNOT==OP_BitNot );
77785      assert( TK_NOT==OP_Not );
77786      testcase( op==TK_BITNOT );
77787      testcase( op==TK_NOT );
77788      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77789      testcase( regFree1==0 );
77790      inReg = target;
77791      sqlite3VdbeAddOp2(v, op, r1, inReg);
77792      break;
77793    }
77794    case TK_ISNULL:
77795    case TK_NOTNULL: {
77796      int addr;
77797      assert( TK_ISNULL==OP_IsNull );
77798      assert( TK_NOTNULL==OP_NotNull );
77799      testcase( op==TK_ISNULL );
77800      testcase( op==TK_NOTNULL );
77801      sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
77802      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77803      testcase( regFree1==0 );
77804      addr = sqlite3VdbeAddOp1(v, op, r1);
77805      sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
77806      sqlite3VdbeJumpHere(v, addr);
77807      break;
77808    }
77809    case TK_AGG_FUNCTION: {
77810      AggInfo *pInfo = pExpr->pAggInfo;
77811      if( pInfo==0 ){
77812        assert( !ExprHasProperty(pExpr, EP_IntValue) );
77813        sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
77814      }else{
77815        inReg = pInfo->aFunc[pExpr->iAgg].iMem;
77816      }
77817      break;
77818    }
77819    case TK_CONST_FUNC:
77820    case TK_FUNCTION: {
77821      ExprList *pFarg;       /* List of function arguments */
77822      int nFarg;             /* Number of function arguments */
77823      FuncDef *pDef;         /* The function definition object */
77824      int nId;               /* Length of the function name in bytes */
77825      const char *zId;       /* The function name */
77826      int constMask = 0;     /* Mask of function arguments that are constant */
77827      int i;                 /* Loop counter */
77828      u8 enc = ENC(db);      /* The text encoding used by this database */
77829      CollSeq *pColl = 0;    /* A collating sequence */
77830
77831      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
77832      testcase( op==TK_CONST_FUNC );
77833      testcase( op==TK_FUNCTION );
77834      if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
77835        pFarg = 0;
77836      }else{
77837        pFarg = pExpr->x.pList;
77838      }
77839      nFarg = pFarg ? pFarg->nExpr : 0;
77840      assert( !ExprHasProperty(pExpr, EP_IntValue) );
77841      zId = pExpr->u.zToken;
77842      nId = sqlite3Strlen30(zId);
77843      pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
77844      if( pDef==0 ){
77845        sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
77846        break;
77847      }
77848
77849      /* Attempt a direct implementation of the built-in COALESCE() and
77850      ** IFNULL() functions.  This avoids unnecessary evalation of
77851      ** arguments past the first non-NULL argument.
77852      */
77853      if( pDef->flags & SQLITE_FUNC_COALESCE ){
77854        int endCoalesce = sqlite3VdbeMakeLabel(v);
77855        assert( nFarg>=2 );
77856        sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
77857        for(i=1; i<nFarg; i++){
77858          sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
77859          sqlite3ExprCacheRemove(pParse, target, 1);
77860          sqlite3ExprCachePush(pParse);
77861          sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
77862          sqlite3ExprCachePop(pParse, 1);
77863        }
77864        sqlite3VdbeResolveLabel(v, endCoalesce);
77865        break;
77866      }
77867
77868
77869      if( pFarg ){
77870        r1 = sqlite3GetTempRange(pParse, nFarg);
77871
77872        /* For length() and typeof() functions with a column argument,
77873        ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
77874        ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
77875        ** loading.
77876        */
77877        if( (pDef->flags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
77878          u8 exprOp;
77879          assert( nFarg==1 );
77880          assert( pFarg->a[0].pExpr!=0 );
77881          exprOp = pFarg->a[0].pExpr->op;
77882          if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
77883            assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
77884            assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
77885            testcase( pDef->flags==SQLITE_FUNC_LENGTH );
77886            pFarg->a[0].pExpr->op2 = pDef->flags;
77887          }
77888        }
77889
77890        sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
77891        sqlite3ExprCodeExprList(pParse, pFarg, r1, 1);
77892        sqlite3ExprCachePop(pParse, 1);   /* Ticket 2ea2425d34be */
77893      }else{
77894        r1 = 0;
77895      }
77896#ifndef SQLITE_OMIT_VIRTUALTABLE
77897      /* Possibly overload the function if the first argument is
77898      ** a virtual table column.
77899      **
77900      ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
77901      ** second argument, not the first, as the argument to test to
77902      ** see if it is a column in a virtual table.  This is done because
77903      ** the left operand of infix functions (the operand we want to
77904      ** control overloading) ends up as the second argument to the
77905      ** function.  The expression "A glob B" is equivalent to
77906      ** "glob(B,A).  We want to use the A in "A glob B" to test
77907      ** for function overloading.  But we use the B term in "glob(B,A)".
77908      */
77909      if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
77910        pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
77911      }else if( nFarg>0 ){
77912        pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
77913      }
77914#endif
77915      for(i=0; i<nFarg; i++){
77916        if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
77917          constMask |= (1<<i);
77918        }
77919        if( (pDef->flags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
77920          pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
77921        }
77922      }
77923      if( pDef->flags & SQLITE_FUNC_NEEDCOLL ){
77924        if( !pColl ) pColl = db->pDfltColl;
77925        sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
77926      }
77927      sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
77928                        (char*)pDef, P4_FUNCDEF);
77929      sqlite3VdbeChangeP5(v, (u8)nFarg);
77930      if( nFarg ){
77931        sqlite3ReleaseTempRange(pParse, r1, nFarg);
77932      }
77933      break;
77934    }
77935#ifndef SQLITE_OMIT_SUBQUERY
77936    case TK_EXISTS:
77937    case TK_SELECT: {
77938      testcase( op==TK_EXISTS );
77939      testcase( op==TK_SELECT );
77940      inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
77941      break;
77942    }
77943    case TK_IN: {
77944      int destIfFalse = sqlite3VdbeMakeLabel(v);
77945      int destIfNull = sqlite3VdbeMakeLabel(v);
77946      sqlite3VdbeAddOp2(v, OP_Null, 0, target);
77947      sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
77948      sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
77949      sqlite3VdbeResolveLabel(v, destIfFalse);
77950      sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
77951      sqlite3VdbeResolveLabel(v, destIfNull);
77952      break;
77953    }
77954#endif /* SQLITE_OMIT_SUBQUERY */
77955
77956
77957    /*
77958    **    x BETWEEN y AND z
77959    **
77960    ** This is equivalent to
77961    **
77962    **    x>=y AND x<=z
77963    **
77964    ** X is stored in pExpr->pLeft.
77965    ** Y is stored in pExpr->pList->a[0].pExpr.
77966    ** Z is stored in pExpr->pList->a[1].pExpr.
77967    */
77968    case TK_BETWEEN: {
77969      Expr *pLeft = pExpr->pLeft;
77970      struct ExprList_item *pLItem = pExpr->x.pList->a;
77971      Expr *pRight = pLItem->pExpr;
77972
77973      r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
77974      r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
77975      testcase( regFree1==0 );
77976      testcase( regFree2==0 );
77977      r3 = sqlite3GetTempReg(pParse);
77978      r4 = sqlite3GetTempReg(pParse);
77979      codeCompare(pParse, pLeft, pRight, OP_Ge,
77980                  r1, r2, r3, SQLITE_STOREP2);
77981      pLItem++;
77982      pRight = pLItem->pExpr;
77983      sqlite3ReleaseTempReg(pParse, regFree2);
77984      r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
77985      testcase( regFree2==0 );
77986      codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
77987      sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
77988      sqlite3ReleaseTempReg(pParse, r3);
77989      sqlite3ReleaseTempReg(pParse, r4);
77990      break;
77991    }
77992    case TK_COLLATE:
77993    case TK_UPLUS: {
77994      inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
77995      break;
77996    }
77997
77998    case TK_TRIGGER: {
77999      /* If the opcode is TK_TRIGGER, then the expression is a reference
78000      ** to a column in the new.* or old.* pseudo-tables available to
78001      ** trigger programs. In this case Expr.iTable is set to 1 for the
78002      ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
78003      ** is set to the column of the pseudo-table to read, or to -1 to
78004      ** read the rowid field.
78005      **
78006      ** The expression is implemented using an OP_Param opcode. The p1
78007      ** parameter is set to 0 for an old.rowid reference, or to (i+1)
78008      ** to reference another column of the old.* pseudo-table, where
78009      ** i is the index of the column. For a new.rowid reference, p1 is
78010      ** set to (n+1), where n is the number of columns in each pseudo-table.
78011      ** For a reference to any other column in the new.* pseudo-table, p1
78012      ** is set to (n+2+i), where n and i are as defined previously. For
78013      ** example, if the table on which triggers are being fired is
78014      ** declared as:
78015      **
78016      **   CREATE TABLE t1(a, b);
78017      **
78018      ** Then p1 is interpreted as follows:
78019      **
78020      **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
78021      **   p1==1   ->    old.a         p1==4   ->    new.a
78022      **   p1==2   ->    old.b         p1==5   ->    new.b
78023      */
78024      Table *pTab = pExpr->pTab;
78025      int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
78026
78027      assert( pExpr->iTable==0 || pExpr->iTable==1 );
78028      assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
78029      assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
78030      assert( p1>=0 && p1<(pTab->nCol*2+2) );
78031
78032      sqlite3VdbeAddOp2(v, OP_Param, p1, target);
78033      VdbeComment((v, "%s.%s -> $%d",
78034        (pExpr->iTable ? "new" : "old"),
78035        (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
78036        target
78037      ));
78038
78039#ifndef SQLITE_OMIT_FLOATING_POINT
78040      /* If the column has REAL affinity, it may currently be stored as an
78041      ** integer. Use OP_RealAffinity to make sure it is really real.  */
78042      if( pExpr->iColumn>=0
78043       && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
78044      ){
78045        sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
78046      }
78047#endif
78048      break;
78049    }
78050
78051
78052    /*
78053    ** Form A:
78054    **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
78055    **
78056    ** Form B:
78057    **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
78058    **
78059    ** Form A is can be transformed into the equivalent form B as follows:
78060    **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
78061    **        WHEN x=eN THEN rN ELSE y END
78062    **
78063    ** X (if it exists) is in pExpr->pLeft.
78064    ** Y is in pExpr->pRight.  The Y is also optional.  If there is no
78065    ** ELSE clause and no other term matches, then the result of the
78066    ** exprssion is NULL.
78067    ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
78068    **
78069    ** The result of the expression is the Ri for the first matching Ei,
78070    ** or if there is no matching Ei, the ELSE term Y, or if there is
78071    ** no ELSE term, NULL.
78072    */
78073    default: assert( op==TK_CASE ); {
78074      int endLabel;                     /* GOTO label for end of CASE stmt */
78075      int nextCase;                     /* GOTO label for next WHEN clause */
78076      int nExpr;                        /* 2x number of WHEN terms */
78077      int i;                            /* Loop counter */
78078      ExprList *pEList;                 /* List of WHEN terms */
78079      struct ExprList_item *aListelem;  /* Array of WHEN terms */
78080      Expr opCompare;                   /* The X==Ei expression */
78081      Expr cacheX;                      /* Cached expression X */
78082      Expr *pX;                         /* The X expression */
78083      Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
78084      VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
78085
78086      assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
78087      assert((pExpr->x.pList->nExpr % 2) == 0);
78088      assert(pExpr->x.pList->nExpr > 0);
78089      pEList = pExpr->x.pList;
78090      aListelem = pEList->a;
78091      nExpr = pEList->nExpr;
78092      endLabel = sqlite3VdbeMakeLabel(v);
78093      if( (pX = pExpr->pLeft)!=0 ){
78094        cacheX = *pX;
78095        testcase( pX->op==TK_COLUMN );
78096        testcase( pX->op==TK_REGISTER );
78097        cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
78098        testcase( regFree1==0 );
78099        cacheX.op = TK_REGISTER;
78100        opCompare.op = TK_EQ;
78101        opCompare.pLeft = &cacheX;
78102        pTest = &opCompare;
78103        /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
78104        ** The value in regFree1 might get SCopy-ed into the file result.
78105        ** So make sure that the regFree1 register is not reused for other
78106        ** purposes and possibly overwritten.  */
78107        regFree1 = 0;
78108      }
78109      for(i=0; i<nExpr; i=i+2){
78110        sqlite3ExprCachePush(pParse);
78111        if( pX ){
78112          assert( pTest!=0 );
78113          opCompare.pRight = aListelem[i].pExpr;
78114        }else{
78115          pTest = aListelem[i].pExpr;
78116        }
78117        nextCase = sqlite3VdbeMakeLabel(v);
78118        testcase( pTest->op==TK_COLUMN );
78119        sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
78120        testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
78121        testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
78122        sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
78123        sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
78124        sqlite3ExprCachePop(pParse, 1);
78125        sqlite3VdbeResolveLabel(v, nextCase);
78126      }
78127      if( pExpr->pRight ){
78128        sqlite3ExprCachePush(pParse);
78129        sqlite3ExprCode(pParse, pExpr->pRight, target);
78130        sqlite3ExprCachePop(pParse, 1);
78131      }else{
78132        sqlite3VdbeAddOp2(v, OP_Null, 0, target);
78133      }
78134      assert( db->mallocFailed || pParse->nErr>0
78135           || pParse->iCacheLevel==iCacheLevel );
78136      sqlite3VdbeResolveLabel(v, endLabel);
78137      break;
78138    }
78139#ifndef SQLITE_OMIT_TRIGGER
78140    case TK_RAISE: {
78141      assert( pExpr->affinity==OE_Rollback
78142           || pExpr->affinity==OE_Abort
78143           || pExpr->affinity==OE_Fail
78144           || pExpr->affinity==OE_Ignore
78145      );
78146      if( !pParse->pTriggerTab ){
78147        sqlite3ErrorMsg(pParse,
78148                       "RAISE() may only be used within a trigger-program");
78149        return 0;
78150      }
78151      if( pExpr->affinity==OE_Abort ){
78152        sqlite3MayAbort(pParse);
78153      }
78154      assert( !ExprHasProperty(pExpr, EP_IntValue) );
78155      if( pExpr->affinity==OE_Ignore ){
78156        sqlite3VdbeAddOp4(
78157            v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
78158      }else{
78159        sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
78160                              pExpr->affinity, pExpr->u.zToken, 0);
78161      }
78162
78163      break;
78164    }
78165#endif
78166  }
78167  sqlite3ReleaseTempReg(pParse, regFree1);
78168  sqlite3ReleaseTempReg(pParse, regFree2);
78169  return inReg;
78170}
78171
78172/*
78173** Generate code to evaluate an expression and store the results
78174** into a register.  Return the register number where the results
78175** are stored.
78176**
78177** If the register is a temporary register that can be deallocated,
78178** then write its number into *pReg.  If the result register is not
78179** a temporary, then set *pReg to zero.
78180*/
78181SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
78182  int r1 = sqlite3GetTempReg(pParse);
78183  int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
78184  if( r2==r1 ){
78185    *pReg = r1;
78186  }else{
78187    sqlite3ReleaseTempReg(pParse, r1);
78188    *pReg = 0;
78189  }
78190  return r2;
78191}
78192
78193/*
78194** Generate code that will evaluate expression pExpr and store the
78195** results in register target.  The results are guaranteed to appear
78196** in register target.
78197*/
78198SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
78199  int inReg;
78200
78201  assert( target>0 && target<=pParse->nMem );
78202  if( pExpr && pExpr->op==TK_REGISTER ){
78203    sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
78204  }else{
78205    inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
78206    assert( pParse->pVdbe || pParse->db->mallocFailed );
78207    if( inReg!=target && pParse->pVdbe ){
78208      sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
78209    }
78210  }
78211  return target;
78212}
78213
78214/*
78215** Generate code that evalutes the given expression and puts the result
78216** in register target.
78217**
78218** Also make a copy of the expression results into another "cache" register
78219** and modify the expression so that the next time it is evaluated,
78220** the result is a copy of the cache register.
78221**
78222** This routine is used for expressions that are used multiple
78223** times.  They are evaluated once and the results of the expression
78224** are reused.
78225*/
78226SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
78227  Vdbe *v = pParse->pVdbe;
78228  int inReg;
78229  inReg = sqlite3ExprCode(pParse, pExpr, target);
78230  assert( target>0 );
78231  /* This routine is called for terms to INSERT or UPDATE.  And the only
78232  ** other place where expressions can be converted into TK_REGISTER is
78233  ** in WHERE clause processing.  So as currently implemented, there is
78234  ** no way for a TK_REGISTER to exist here.  But it seems prudent to
78235  ** keep the ALWAYS() in case the conditions above change with future
78236  ** modifications or enhancements. */
78237  if( ALWAYS(pExpr->op!=TK_REGISTER) ){
78238    int iMem;
78239    iMem = ++pParse->nMem;
78240    sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
78241    pExpr->iTable = iMem;
78242    pExpr->op2 = pExpr->op;
78243    pExpr->op = TK_REGISTER;
78244  }
78245  return inReg;
78246}
78247
78248#if defined(SQLITE_ENABLE_TREE_EXPLAIN)
78249/*
78250** Generate a human-readable explanation of an expression tree.
78251*/
78252SQLITE_PRIVATE void sqlite3ExplainExpr(Vdbe *pOut, Expr *pExpr){
78253  int op;                   /* The opcode being coded */
78254  const char *zBinOp = 0;   /* Binary operator */
78255  const char *zUniOp = 0;   /* Unary operator */
78256  if( pExpr==0 ){
78257    op = TK_NULL;
78258  }else{
78259    op = pExpr->op;
78260  }
78261  switch( op ){
78262    case TK_AGG_COLUMN: {
78263      sqlite3ExplainPrintf(pOut, "AGG{%d:%d}",
78264            pExpr->iTable, pExpr->iColumn);
78265      break;
78266    }
78267    case TK_COLUMN: {
78268      if( pExpr->iTable<0 ){
78269        /* This only happens when coding check constraints */
78270        sqlite3ExplainPrintf(pOut, "COLUMN(%d)", pExpr->iColumn);
78271      }else{
78272        sqlite3ExplainPrintf(pOut, "{%d:%d}",
78273                             pExpr->iTable, pExpr->iColumn);
78274      }
78275      break;
78276    }
78277    case TK_INTEGER: {
78278      if( pExpr->flags & EP_IntValue ){
78279        sqlite3ExplainPrintf(pOut, "%d", pExpr->u.iValue);
78280      }else{
78281        sqlite3ExplainPrintf(pOut, "%s", pExpr->u.zToken);
78282      }
78283      break;
78284    }
78285#ifndef SQLITE_OMIT_FLOATING_POINT
78286    case TK_FLOAT: {
78287      sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
78288      break;
78289    }
78290#endif
78291    case TK_STRING: {
78292      sqlite3ExplainPrintf(pOut,"%Q", pExpr->u.zToken);
78293      break;
78294    }
78295    case TK_NULL: {
78296      sqlite3ExplainPrintf(pOut,"NULL");
78297      break;
78298    }
78299#ifndef SQLITE_OMIT_BLOB_LITERAL
78300    case TK_BLOB: {
78301      sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
78302      break;
78303    }
78304#endif
78305    case TK_VARIABLE: {
78306      sqlite3ExplainPrintf(pOut,"VARIABLE(%s,%d)",
78307                           pExpr->u.zToken, pExpr->iColumn);
78308      break;
78309    }
78310    case TK_REGISTER: {
78311      sqlite3ExplainPrintf(pOut,"REGISTER(%d)", pExpr->iTable);
78312      break;
78313    }
78314    case TK_AS: {
78315      sqlite3ExplainExpr(pOut, pExpr->pLeft);
78316      break;
78317    }
78318#ifndef SQLITE_OMIT_CAST
78319    case TK_CAST: {
78320      /* Expressions of the form:   CAST(pLeft AS token) */
78321      const char *zAff = "unk";
78322      switch( sqlite3AffinityType(pExpr->u.zToken) ){
78323        case SQLITE_AFF_TEXT:    zAff = "TEXT";     break;
78324        case SQLITE_AFF_NONE:    zAff = "NONE";     break;
78325        case SQLITE_AFF_NUMERIC: zAff = "NUMERIC";  break;
78326        case SQLITE_AFF_INTEGER: zAff = "INTEGER";  break;
78327        case SQLITE_AFF_REAL:    zAff = "REAL";     break;
78328      }
78329      sqlite3ExplainPrintf(pOut, "CAST-%s(", zAff);
78330      sqlite3ExplainExpr(pOut, pExpr->pLeft);
78331      sqlite3ExplainPrintf(pOut, ")");
78332      break;
78333    }
78334#endif /* SQLITE_OMIT_CAST */
78335    case TK_LT:      zBinOp = "LT";     break;
78336    case TK_LE:      zBinOp = "LE";     break;
78337    case TK_GT:      zBinOp = "GT";     break;
78338    case TK_GE:      zBinOp = "GE";     break;
78339    case TK_NE:      zBinOp = "NE";     break;
78340    case TK_EQ:      zBinOp = "EQ";     break;
78341    case TK_IS:      zBinOp = "IS";     break;
78342    case TK_ISNOT:   zBinOp = "ISNOT";  break;
78343    case TK_AND:     zBinOp = "AND";    break;
78344    case TK_OR:      zBinOp = "OR";     break;
78345    case TK_PLUS:    zBinOp = "ADD";    break;
78346    case TK_STAR:    zBinOp = "MUL";    break;
78347    case TK_MINUS:   zBinOp = "SUB";    break;
78348    case TK_REM:     zBinOp = "REM";    break;
78349    case TK_BITAND:  zBinOp = "BITAND"; break;
78350    case TK_BITOR:   zBinOp = "BITOR";  break;
78351    case TK_SLASH:   zBinOp = "DIV";    break;
78352    case TK_LSHIFT:  zBinOp = "LSHIFT"; break;
78353    case TK_RSHIFT:  zBinOp = "RSHIFT"; break;
78354    case TK_CONCAT:  zBinOp = "CONCAT"; break;
78355
78356    case TK_UMINUS:  zUniOp = "UMINUS"; break;
78357    case TK_UPLUS:   zUniOp = "UPLUS";  break;
78358    case TK_BITNOT:  zUniOp = "BITNOT"; break;
78359    case TK_NOT:     zUniOp = "NOT";    break;
78360    case TK_ISNULL:  zUniOp = "ISNULL"; break;
78361    case TK_NOTNULL: zUniOp = "NOTNULL"; break;
78362
78363    case TK_COLLATE: {
78364      sqlite3ExplainExpr(pOut, pExpr->pLeft);
78365      sqlite3ExplainPrintf(pOut,".COLLATE(%s)",pExpr->u.zToken);
78366      break;
78367    }
78368
78369    case TK_AGG_FUNCTION:
78370    case TK_CONST_FUNC:
78371    case TK_FUNCTION: {
78372      ExprList *pFarg;       /* List of function arguments */
78373      if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
78374        pFarg = 0;
78375      }else{
78376        pFarg = pExpr->x.pList;
78377      }
78378      if( op==TK_AGG_FUNCTION ){
78379        sqlite3ExplainPrintf(pOut, "AGG_FUNCTION%d:%s(",
78380                             pExpr->op2, pExpr->u.zToken);
78381      }else{
78382        sqlite3ExplainPrintf(pOut, "FUNCTION:%s(", pExpr->u.zToken);
78383      }
78384      if( pFarg ){
78385        sqlite3ExplainExprList(pOut, pFarg);
78386      }
78387      sqlite3ExplainPrintf(pOut, ")");
78388      break;
78389    }
78390#ifndef SQLITE_OMIT_SUBQUERY
78391    case TK_EXISTS: {
78392      sqlite3ExplainPrintf(pOut, "EXISTS(");
78393      sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
78394      sqlite3ExplainPrintf(pOut,")");
78395      break;
78396    }
78397    case TK_SELECT: {
78398      sqlite3ExplainPrintf(pOut, "(");
78399      sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
78400      sqlite3ExplainPrintf(pOut, ")");
78401      break;
78402    }
78403    case TK_IN: {
78404      sqlite3ExplainPrintf(pOut, "IN(");
78405      sqlite3ExplainExpr(pOut, pExpr->pLeft);
78406      sqlite3ExplainPrintf(pOut, ",");
78407      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
78408        sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
78409      }else{
78410        sqlite3ExplainExprList(pOut, pExpr->x.pList);
78411      }
78412      sqlite3ExplainPrintf(pOut, ")");
78413      break;
78414    }
78415#endif /* SQLITE_OMIT_SUBQUERY */
78416
78417    /*
78418    **    x BETWEEN y AND z
78419    **
78420    ** This is equivalent to
78421    **
78422    **    x>=y AND x<=z
78423    **
78424    ** X is stored in pExpr->pLeft.
78425    ** Y is stored in pExpr->pList->a[0].pExpr.
78426    ** Z is stored in pExpr->pList->a[1].pExpr.
78427    */
78428    case TK_BETWEEN: {
78429      Expr *pX = pExpr->pLeft;
78430      Expr *pY = pExpr->x.pList->a[0].pExpr;
78431      Expr *pZ = pExpr->x.pList->a[1].pExpr;
78432      sqlite3ExplainPrintf(pOut, "BETWEEN(");
78433      sqlite3ExplainExpr(pOut, pX);
78434      sqlite3ExplainPrintf(pOut, ",");
78435      sqlite3ExplainExpr(pOut, pY);
78436      sqlite3ExplainPrintf(pOut, ",");
78437      sqlite3ExplainExpr(pOut, pZ);
78438      sqlite3ExplainPrintf(pOut, ")");
78439      break;
78440    }
78441    case TK_TRIGGER: {
78442      /* If the opcode is TK_TRIGGER, then the expression is a reference
78443      ** to a column in the new.* or old.* pseudo-tables available to
78444      ** trigger programs. In this case Expr.iTable is set to 1 for the
78445      ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
78446      ** is set to the column of the pseudo-table to read, or to -1 to
78447      ** read the rowid field.
78448      */
78449      sqlite3ExplainPrintf(pOut, "%s(%d)",
78450          pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
78451      break;
78452    }
78453    case TK_CASE: {
78454      sqlite3ExplainPrintf(pOut, "CASE(");
78455      sqlite3ExplainExpr(pOut, pExpr->pLeft);
78456      sqlite3ExplainPrintf(pOut, ",");
78457      sqlite3ExplainExprList(pOut, pExpr->x.pList);
78458      break;
78459    }
78460#ifndef SQLITE_OMIT_TRIGGER
78461    case TK_RAISE: {
78462      const char *zType = "unk";
78463      switch( pExpr->affinity ){
78464        case OE_Rollback:   zType = "rollback";  break;
78465        case OE_Abort:      zType = "abort";     break;
78466        case OE_Fail:       zType = "fail";      break;
78467        case OE_Ignore:     zType = "ignore";    break;
78468      }
78469      sqlite3ExplainPrintf(pOut, "RAISE-%s(%s)", zType, pExpr->u.zToken);
78470      break;
78471    }
78472#endif
78473  }
78474  if( zBinOp ){
78475    sqlite3ExplainPrintf(pOut,"%s(", zBinOp);
78476    sqlite3ExplainExpr(pOut, pExpr->pLeft);
78477    sqlite3ExplainPrintf(pOut,",");
78478    sqlite3ExplainExpr(pOut, pExpr->pRight);
78479    sqlite3ExplainPrintf(pOut,")");
78480  }else if( zUniOp ){
78481    sqlite3ExplainPrintf(pOut,"%s(", zUniOp);
78482    sqlite3ExplainExpr(pOut, pExpr->pLeft);
78483    sqlite3ExplainPrintf(pOut,")");
78484  }
78485}
78486#endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
78487
78488#if defined(SQLITE_ENABLE_TREE_EXPLAIN)
78489/*
78490** Generate a human-readable explanation of an expression list.
78491*/
78492SQLITE_PRIVATE void sqlite3ExplainExprList(Vdbe *pOut, ExprList *pList){
78493  int i;
78494  if( pList==0 || pList->nExpr==0 ){
78495    sqlite3ExplainPrintf(pOut, "(empty-list)");
78496    return;
78497  }else if( pList->nExpr==1 ){
78498    sqlite3ExplainExpr(pOut, pList->a[0].pExpr);
78499  }else{
78500    sqlite3ExplainPush(pOut);
78501    for(i=0; i<pList->nExpr; i++){
78502      sqlite3ExplainPrintf(pOut, "item[%d] = ", i);
78503      sqlite3ExplainPush(pOut);
78504      sqlite3ExplainExpr(pOut, pList->a[i].pExpr);
78505      sqlite3ExplainPop(pOut);
78506      if( pList->a[i].zName ){
78507        sqlite3ExplainPrintf(pOut, " AS %s", pList->a[i].zName);
78508      }
78509      if( pList->a[i].bSpanIsTab ){
78510        sqlite3ExplainPrintf(pOut, " (%s)", pList->a[i].zSpan);
78511      }
78512      if( i<pList->nExpr-1 ){
78513        sqlite3ExplainNL(pOut);
78514      }
78515    }
78516    sqlite3ExplainPop(pOut);
78517  }
78518}
78519#endif /* SQLITE_DEBUG */
78520
78521/*
78522** Return TRUE if pExpr is an constant expression that is appropriate
78523** for factoring out of a loop.  Appropriate expressions are:
78524**
78525**    *  Any expression that evaluates to two or more opcodes.
78526**
78527**    *  Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null,
78528**       or OP_Variable that does not need to be placed in a
78529**       specific register.
78530**
78531** There is no point in factoring out single-instruction constant
78532** expressions that need to be placed in a particular register.
78533** We could factor them out, but then we would end up adding an
78534** OP_SCopy instruction to move the value into the correct register
78535** later.  We might as well just use the original instruction and
78536** avoid the OP_SCopy.
78537*/
78538static int isAppropriateForFactoring(Expr *p){
78539  if( !sqlite3ExprIsConstantNotJoin(p) ){
78540    return 0;  /* Only constant expressions are appropriate for factoring */
78541  }
78542  if( (p->flags & EP_FixedDest)==0 ){
78543    return 1;  /* Any constant without a fixed destination is appropriate */
78544  }
78545  while( p->op==TK_UPLUS ) p = p->pLeft;
78546  switch( p->op ){
78547#ifndef SQLITE_OMIT_BLOB_LITERAL
78548    case TK_BLOB:
78549#endif
78550    case TK_VARIABLE:
78551    case TK_INTEGER:
78552    case TK_FLOAT:
78553    case TK_NULL:
78554    case TK_STRING: {
78555      testcase( p->op==TK_BLOB );
78556      testcase( p->op==TK_VARIABLE );
78557      testcase( p->op==TK_INTEGER );
78558      testcase( p->op==TK_FLOAT );
78559      testcase( p->op==TK_NULL );
78560      testcase( p->op==TK_STRING );
78561      /* Single-instruction constants with a fixed destination are
78562      ** better done in-line.  If we factor them, they will just end
78563      ** up generating an OP_SCopy to move the value to the destination
78564      ** register. */
78565      return 0;
78566    }
78567    case TK_UMINUS: {
78568      if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
78569        return 0;
78570      }
78571      break;
78572    }
78573    default: {
78574      break;
78575    }
78576  }
78577  return 1;
78578}
78579
78580/*
78581** If pExpr is a constant expression that is appropriate for
78582** factoring out of a loop, then evaluate the expression
78583** into a register and convert the expression into a TK_REGISTER
78584** expression.
78585*/
78586static int evalConstExpr(Walker *pWalker, Expr *pExpr){
78587  Parse *pParse = pWalker->pParse;
78588  switch( pExpr->op ){
78589    case TK_IN:
78590    case TK_REGISTER: {
78591      return WRC_Prune;
78592    }
78593    case TK_COLLATE: {
78594      return WRC_Continue;
78595    }
78596    case TK_FUNCTION:
78597    case TK_AGG_FUNCTION:
78598    case TK_CONST_FUNC: {
78599      /* The arguments to a function have a fixed destination.
78600      ** Mark them this way to avoid generated unneeded OP_SCopy
78601      ** instructions.
78602      */
78603      ExprList *pList = pExpr->x.pList;
78604      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
78605      if( pList ){
78606        int i = pList->nExpr;
78607        struct ExprList_item *pItem = pList->a;
78608        for(; i>0; i--, pItem++){
78609          if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest;
78610        }
78611      }
78612      break;
78613    }
78614  }
78615  if( isAppropriateForFactoring(pExpr) ){
78616    int r1 = ++pParse->nMem;
78617    int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
78618    /* If r2!=r1, it means that register r1 is never used.  That is harmless
78619    ** but suboptimal, so we want to know about the situation to fix it.
78620    ** Hence the following assert: */
78621    assert( r2==r1 );
78622    pExpr->op2 = pExpr->op;
78623    pExpr->op = TK_REGISTER;
78624    pExpr->iTable = r2;
78625    return WRC_Prune;
78626  }
78627  return WRC_Continue;
78628}
78629
78630/*
78631** Preevaluate constant subexpressions within pExpr and store the
78632** results in registers.  Modify pExpr so that the constant subexpresions
78633** are TK_REGISTER opcodes that refer to the precomputed values.
78634**
78635** This routine is a no-op if the jump to the cookie-check code has
78636** already occur.  Since the cookie-check jump is generated prior to
78637** any other serious processing, this check ensures that there is no
78638** way to accidently bypass the constant initializations.
78639**
78640** This routine is also a no-op if the SQLITE_FactorOutConst optimization
78641** is disabled via the sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS)
78642** interface.  This allows test logic to verify that the same answer is
78643** obtained for queries regardless of whether or not constants are
78644** precomputed into registers or if they are inserted in-line.
78645*/
78646SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
78647  Walker w;
78648  if( pParse->cookieGoto ) return;
78649  if( OptimizationDisabled(pParse->db, SQLITE_FactorOutConst) ) return;
78650  memset(&w, 0, sizeof(w));
78651  w.xExprCallback = evalConstExpr;
78652  w.pParse = pParse;
78653  sqlite3WalkExpr(&w, pExpr);
78654}
78655
78656
78657/*
78658** Generate code that pushes the value of every element of the given
78659** expression list into a sequence of registers beginning at target.
78660**
78661** Return the number of elements evaluated.
78662*/
78663SQLITE_PRIVATE int sqlite3ExprCodeExprList(
78664  Parse *pParse,     /* Parsing context */
78665  ExprList *pList,   /* The expression list to be coded */
78666  int target,        /* Where to write results */
78667  int doHardCopy     /* Make a hard copy of every element */
78668){
78669  struct ExprList_item *pItem;
78670  int i, n;
78671  assert( pList!=0 );
78672  assert( target>0 );
78673  assert( pParse->pVdbe!=0 );  /* Never gets this far otherwise */
78674  n = pList->nExpr;
78675  for(pItem=pList->a, i=0; i<n; i++, pItem++){
78676    Expr *pExpr = pItem->pExpr;
78677    int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
78678    if( inReg!=target+i ){
78679      sqlite3VdbeAddOp2(pParse->pVdbe, doHardCopy ? OP_Copy : OP_SCopy,
78680                        inReg, target+i);
78681    }
78682  }
78683  return n;
78684}
78685
78686/*
78687** Generate code for a BETWEEN operator.
78688**
78689**    x BETWEEN y AND z
78690**
78691** The above is equivalent to
78692**
78693**    x>=y AND x<=z
78694**
78695** Code it as such, taking care to do the common subexpression
78696** elementation of x.
78697*/
78698static void exprCodeBetween(
78699  Parse *pParse,    /* Parsing and code generating context */
78700  Expr *pExpr,      /* The BETWEEN expression */
78701  int dest,         /* Jump here if the jump is taken */
78702  int jumpIfTrue,   /* Take the jump if the BETWEEN is true */
78703  int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
78704){
78705  Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
78706  Expr compLeft;    /* The  x>=y  term */
78707  Expr compRight;   /* The  x<=z  term */
78708  Expr exprX;       /* The  x  subexpression */
78709  int regFree1 = 0; /* Temporary use register */
78710
78711  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
78712  exprX = *pExpr->pLeft;
78713  exprAnd.op = TK_AND;
78714  exprAnd.pLeft = &compLeft;
78715  exprAnd.pRight = &compRight;
78716  compLeft.op = TK_GE;
78717  compLeft.pLeft = &exprX;
78718  compLeft.pRight = pExpr->x.pList->a[0].pExpr;
78719  compRight.op = TK_LE;
78720  compRight.pLeft = &exprX;
78721  compRight.pRight = pExpr->x.pList->a[1].pExpr;
78722  exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
78723  exprX.op = TK_REGISTER;
78724  if( jumpIfTrue ){
78725    sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
78726  }else{
78727    sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
78728  }
78729  sqlite3ReleaseTempReg(pParse, regFree1);
78730
78731  /* Ensure adequate test coverage */
78732  testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
78733  testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
78734  testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
78735  testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
78736  testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
78737  testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
78738  testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
78739  testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
78740}
78741
78742/*
78743** Generate code for a boolean expression such that a jump is made
78744** to the label "dest" if the expression is true but execution
78745** continues straight thru if the expression is false.
78746**
78747** If the expression evaluates to NULL (neither true nor false), then
78748** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
78749**
78750** This code depends on the fact that certain token values (ex: TK_EQ)
78751** are the same as opcode values (ex: OP_Eq) that implement the corresponding
78752** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
78753** the make process cause these values to align.  Assert()s in the code
78754** below verify that the numbers are aligned correctly.
78755*/
78756SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
78757  Vdbe *v = pParse->pVdbe;
78758  int op = 0;
78759  int regFree1 = 0;
78760  int regFree2 = 0;
78761  int r1, r2;
78762
78763  assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
78764  if( NEVER(v==0) )     return;  /* Existence of VDBE checked by caller */
78765  if( NEVER(pExpr==0) ) return;  /* No way this can happen */
78766  op = pExpr->op;
78767  switch( op ){
78768    case TK_AND: {
78769      int d2 = sqlite3VdbeMakeLabel(v);
78770      testcase( jumpIfNull==0 );
78771      sqlite3ExprCachePush(pParse);
78772      sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
78773      sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
78774      sqlite3VdbeResolveLabel(v, d2);
78775      sqlite3ExprCachePop(pParse, 1);
78776      break;
78777    }
78778    case TK_OR: {
78779      testcase( jumpIfNull==0 );
78780      sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
78781      sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
78782      break;
78783    }
78784    case TK_NOT: {
78785      testcase( jumpIfNull==0 );
78786      sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
78787      break;
78788    }
78789    case TK_LT:
78790    case TK_LE:
78791    case TK_GT:
78792    case TK_GE:
78793    case TK_NE:
78794    case TK_EQ: {
78795      assert( TK_LT==OP_Lt );
78796      assert( TK_LE==OP_Le );
78797      assert( TK_GT==OP_Gt );
78798      assert( TK_GE==OP_Ge );
78799      assert( TK_EQ==OP_Eq );
78800      assert( TK_NE==OP_Ne );
78801      testcase( op==TK_LT );
78802      testcase( op==TK_LE );
78803      testcase( op==TK_GT );
78804      testcase( op==TK_GE );
78805      testcase( op==TK_EQ );
78806      testcase( op==TK_NE );
78807      testcase( jumpIfNull==0 );
78808      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
78809      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
78810      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
78811                  r1, r2, dest, jumpIfNull);
78812      testcase( regFree1==0 );
78813      testcase( regFree2==0 );
78814      break;
78815    }
78816    case TK_IS:
78817    case TK_ISNOT: {
78818      testcase( op==TK_IS );
78819      testcase( op==TK_ISNOT );
78820      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
78821      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
78822      op = (op==TK_IS) ? TK_EQ : TK_NE;
78823      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
78824                  r1, r2, dest, SQLITE_NULLEQ);
78825      testcase( regFree1==0 );
78826      testcase( regFree2==0 );
78827      break;
78828    }
78829    case TK_ISNULL:
78830    case TK_NOTNULL: {
78831      assert( TK_ISNULL==OP_IsNull );
78832      assert( TK_NOTNULL==OP_NotNull );
78833      testcase( op==TK_ISNULL );
78834      testcase( op==TK_NOTNULL );
78835      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
78836      sqlite3VdbeAddOp2(v, op, r1, dest);
78837      testcase( regFree1==0 );
78838      break;
78839    }
78840    case TK_BETWEEN: {
78841      testcase( jumpIfNull==0 );
78842      exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
78843      break;
78844    }
78845#ifndef SQLITE_OMIT_SUBQUERY
78846    case TK_IN: {
78847      int destIfFalse = sqlite3VdbeMakeLabel(v);
78848      int destIfNull = jumpIfNull ? dest : destIfFalse;
78849      sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
78850      sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
78851      sqlite3VdbeResolveLabel(v, destIfFalse);
78852      break;
78853    }
78854#endif
78855    default: {
78856      r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
78857      sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
78858      testcase( regFree1==0 );
78859      testcase( jumpIfNull==0 );
78860      break;
78861    }
78862  }
78863  sqlite3ReleaseTempReg(pParse, regFree1);
78864  sqlite3ReleaseTempReg(pParse, regFree2);
78865}
78866
78867/*
78868** Generate code for a boolean expression such that a jump is made
78869** to the label "dest" if the expression is false but execution
78870** continues straight thru if the expression is true.
78871**
78872** If the expression evaluates to NULL (neither true nor false) then
78873** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
78874** is 0.
78875*/
78876SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
78877  Vdbe *v = pParse->pVdbe;
78878  int op = 0;
78879  int regFree1 = 0;
78880  int regFree2 = 0;
78881  int r1, r2;
78882
78883  assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
78884  if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
78885  if( pExpr==0 )    return;
78886
78887  /* The value of pExpr->op and op are related as follows:
78888  **
78889  **       pExpr->op            op
78890  **       ---------          ----------
78891  **       TK_ISNULL          OP_NotNull
78892  **       TK_NOTNULL         OP_IsNull
78893  **       TK_NE              OP_Eq
78894  **       TK_EQ              OP_Ne
78895  **       TK_GT              OP_Le
78896  **       TK_LE              OP_Gt
78897  **       TK_GE              OP_Lt
78898  **       TK_LT              OP_Ge
78899  **
78900  ** For other values of pExpr->op, op is undefined and unused.
78901  ** The value of TK_ and OP_ constants are arranged such that we
78902  ** can compute the mapping above using the following expression.
78903  ** Assert()s verify that the computation is correct.
78904  */
78905  op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
78906
78907  /* Verify correct alignment of TK_ and OP_ constants
78908  */
78909  assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
78910  assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
78911  assert( pExpr->op!=TK_NE || op==OP_Eq );
78912  assert( pExpr->op!=TK_EQ || op==OP_Ne );
78913  assert( pExpr->op!=TK_LT || op==OP_Ge );
78914  assert( pExpr->op!=TK_LE || op==OP_Gt );
78915  assert( pExpr->op!=TK_GT || op==OP_Le );
78916  assert( pExpr->op!=TK_GE || op==OP_Lt );
78917
78918  switch( pExpr->op ){
78919    case TK_AND: {
78920      testcase( jumpIfNull==0 );
78921      sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
78922      sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
78923      break;
78924    }
78925    case TK_OR: {
78926      int d2 = sqlite3VdbeMakeLabel(v);
78927      testcase( jumpIfNull==0 );
78928      sqlite3ExprCachePush(pParse);
78929      sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
78930      sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
78931      sqlite3VdbeResolveLabel(v, d2);
78932      sqlite3ExprCachePop(pParse, 1);
78933      break;
78934    }
78935    case TK_NOT: {
78936      testcase( jumpIfNull==0 );
78937      sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
78938      break;
78939    }
78940    case TK_LT:
78941    case TK_LE:
78942    case TK_GT:
78943    case TK_GE:
78944    case TK_NE:
78945    case TK_EQ: {
78946      testcase( op==TK_LT );
78947      testcase( op==TK_LE );
78948      testcase( op==TK_GT );
78949      testcase( op==TK_GE );
78950      testcase( op==TK_EQ );
78951      testcase( op==TK_NE );
78952      testcase( jumpIfNull==0 );
78953      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
78954      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
78955      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
78956                  r1, r2, dest, jumpIfNull);
78957      testcase( regFree1==0 );
78958      testcase( regFree2==0 );
78959      break;
78960    }
78961    case TK_IS:
78962    case TK_ISNOT: {
78963      testcase( pExpr->op==TK_IS );
78964      testcase( pExpr->op==TK_ISNOT );
78965      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
78966      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
78967      op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
78968      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
78969                  r1, r2, dest, SQLITE_NULLEQ);
78970      testcase( regFree1==0 );
78971      testcase( regFree2==0 );
78972      break;
78973    }
78974    case TK_ISNULL:
78975    case TK_NOTNULL: {
78976      testcase( op==TK_ISNULL );
78977      testcase( op==TK_NOTNULL );
78978      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
78979      sqlite3VdbeAddOp2(v, op, r1, dest);
78980      testcase( regFree1==0 );
78981      break;
78982    }
78983    case TK_BETWEEN: {
78984      testcase( jumpIfNull==0 );
78985      exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
78986      break;
78987    }
78988#ifndef SQLITE_OMIT_SUBQUERY
78989    case TK_IN: {
78990      if( jumpIfNull ){
78991        sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
78992      }else{
78993        int destIfNull = sqlite3VdbeMakeLabel(v);
78994        sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
78995        sqlite3VdbeResolveLabel(v, destIfNull);
78996      }
78997      break;
78998    }
78999#endif
79000    default: {
79001      r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
79002      sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
79003      testcase( regFree1==0 );
79004      testcase( jumpIfNull==0 );
79005      break;
79006    }
79007  }
79008  sqlite3ReleaseTempReg(pParse, regFree1);
79009  sqlite3ReleaseTempReg(pParse, regFree2);
79010}
79011
79012/*
79013** Do a deep comparison of two expression trees.  Return 0 if the two
79014** expressions are completely identical.  Return 1 if they differ only
79015** by a COLLATE operator at the top level.  Return 2 if there are differences
79016** other than the top-level COLLATE operator.
79017**
79018** Sometimes this routine will return 2 even if the two expressions
79019** really are equivalent.  If we cannot prove that the expressions are
79020** identical, we return 2 just to be safe.  So if this routine
79021** returns 2, then you do not really know for certain if the two
79022** expressions are the same.  But if you get a 0 or 1 return, then you
79023** can be sure the expressions are the same.  In the places where
79024** this routine is used, it does not hurt to get an extra 2 - that
79025** just might result in some slightly slower code.  But returning
79026** an incorrect 0 or 1 could lead to a malfunction.
79027*/
79028SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB){
79029  if( pA==0||pB==0 ){
79030    return pB==pA ? 0 : 2;
79031  }
79032  assert( !ExprHasAnyProperty(pA, EP_TokenOnly|EP_Reduced) );
79033  assert( !ExprHasAnyProperty(pB, EP_TokenOnly|EP_Reduced) );
79034  if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
79035    return 2;
79036  }
79037  if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
79038  if( pA->op!=pB->op ){
79039    if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB)<2 ){
79040      return 1;
79041    }
79042    if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft)<2 ){
79043      return 1;
79044    }
79045    return 2;
79046  }
79047  if( sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 2;
79048  if( sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 2;
79049  if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList) ) return 2;
79050  if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 2;
79051  if( ExprHasProperty(pA, EP_IntValue) ){
79052    if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
79053      return 2;
79054    }
79055  }else if( pA->op!=TK_COLUMN && ALWAYS(pA->op!=TK_AGG_COLUMN) && pA->u.zToken){
79056    if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 2;
79057    if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
79058      return pA->op==TK_COLLATE ? 1 : 2;
79059    }
79060  }
79061  return 0;
79062}
79063
79064/*
79065** Compare two ExprList objects.  Return 0 if they are identical and
79066** non-zero if they differ in any way.
79067**
79068** This routine might return non-zero for equivalent ExprLists.  The
79069** only consequence will be disabled optimizations.  But this routine
79070** must never return 0 if the two ExprList objects are different, or
79071** a malfunction will result.
79072**
79073** Two NULL pointers are considered to be the same.  But a NULL pointer
79074** always differs from a non-NULL pointer.
79075*/
79076SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB){
79077  int i;
79078  if( pA==0 && pB==0 ) return 0;
79079  if( pA==0 || pB==0 ) return 1;
79080  if( pA->nExpr!=pB->nExpr ) return 1;
79081  for(i=0; i<pA->nExpr; i++){
79082    Expr *pExprA = pA->a[i].pExpr;
79083    Expr *pExprB = pB->a[i].pExpr;
79084    if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
79085    if( sqlite3ExprCompare(pExprA, pExprB) ) return 1;
79086  }
79087  return 0;
79088}
79089
79090/*
79091** An instance of the following structure is used by the tree walker
79092** to count references to table columns in the arguments of an
79093** aggregate function, in order to implement the
79094** sqlite3FunctionThisSrc() routine.
79095*/
79096struct SrcCount {
79097  SrcList *pSrc;   /* One particular FROM clause in a nested query */
79098  int nThis;       /* Number of references to columns in pSrcList */
79099  int nOther;      /* Number of references to columns in other FROM clauses */
79100};
79101
79102/*
79103** Count the number of references to columns.
79104*/
79105static int exprSrcCount(Walker *pWalker, Expr *pExpr){
79106  /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
79107  ** is always called before sqlite3ExprAnalyzeAggregates() and so the
79108  ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN.  If
79109  ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
79110  ** NEVER() will need to be removed. */
79111  if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
79112    int i;
79113    struct SrcCount *p = pWalker->u.pSrcCount;
79114    SrcList *pSrc = p->pSrc;
79115    for(i=0; i<pSrc->nSrc; i++){
79116      if( pExpr->iTable==pSrc->a[i].iCursor ) break;
79117    }
79118    if( i<pSrc->nSrc ){
79119      p->nThis++;
79120    }else{
79121      p->nOther++;
79122    }
79123  }
79124  return WRC_Continue;
79125}
79126
79127/*
79128** Determine if any of the arguments to the pExpr Function reference
79129** pSrcList.  Return true if they do.  Also return true if the function
79130** has no arguments or has only constant arguments.  Return false if pExpr
79131** references columns but not columns of tables found in pSrcList.
79132*/
79133SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
79134  Walker w;
79135  struct SrcCount cnt;
79136  assert( pExpr->op==TK_AGG_FUNCTION );
79137  memset(&w, 0, sizeof(w));
79138  w.xExprCallback = exprSrcCount;
79139  w.u.pSrcCount = &cnt;
79140  cnt.pSrc = pSrcList;
79141  cnt.nThis = 0;
79142  cnt.nOther = 0;
79143  sqlite3WalkExprList(&w, pExpr->x.pList);
79144  return cnt.nThis>0 || cnt.nOther==0;
79145}
79146
79147/*
79148** Add a new element to the pAggInfo->aCol[] array.  Return the index of
79149** the new element.  Return a negative number if malloc fails.
79150*/
79151static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
79152  int i;
79153  pInfo->aCol = sqlite3ArrayAllocate(
79154       db,
79155       pInfo->aCol,
79156       sizeof(pInfo->aCol[0]),
79157       &pInfo->nColumn,
79158       &i
79159  );
79160  return i;
79161}
79162
79163/*
79164** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
79165** the new element.  Return a negative number if malloc fails.
79166*/
79167static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
79168  int i;
79169  pInfo->aFunc = sqlite3ArrayAllocate(
79170       db,
79171       pInfo->aFunc,
79172       sizeof(pInfo->aFunc[0]),
79173       &pInfo->nFunc,
79174       &i
79175  );
79176  return i;
79177}
79178
79179/*
79180** This is the xExprCallback for a tree walker.  It is used to
79181** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
79182** for additional information.
79183*/
79184static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
79185  int i;
79186  NameContext *pNC = pWalker->u.pNC;
79187  Parse *pParse = pNC->pParse;
79188  SrcList *pSrcList = pNC->pSrcList;
79189  AggInfo *pAggInfo = pNC->pAggInfo;
79190
79191  switch( pExpr->op ){
79192    case TK_AGG_COLUMN:
79193    case TK_COLUMN: {
79194      testcase( pExpr->op==TK_AGG_COLUMN );
79195      testcase( pExpr->op==TK_COLUMN );
79196      /* Check to see if the column is in one of the tables in the FROM
79197      ** clause of the aggregate query */
79198      if( ALWAYS(pSrcList!=0) ){
79199        struct SrcList_item *pItem = pSrcList->a;
79200        for(i=0; i<pSrcList->nSrc; i++, pItem++){
79201          struct AggInfo_col *pCol;
79202          assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
79203          if( pExpr->iTable==pItem->iCursor ){
79204            /* If we reach this point, it means that pExpr refers to a table
79205            ** that is in the FROM clause of the aggregate query.
79206            **
79207            ** Make an entry for the column in pAggInfo->aCol[] if there
79208            ** is not an entry there already.
79209            */
79210            int k;
79211            pCol = pAggInfo->aCol;
79212            for(k=0; k<pAggInfo->nColumn; k++, pCol++){
79213              if( pCol->iTable==pExpr->iTable &&
79214                  pCol->iColumn==pExpr->iColumn ){
79215                break;
79216              }
79217            }
79218            if( (k>=pAggInfo->nColumn)
79219             && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
79220            ){
79221              pCol = &pAggInfo->aCol[k];
79222              pCol->pTab = pExpr->pTab;
79223              pCol->iTable = pExpr->iTable;
79224              pCol->iColumn = pExpr->iColumn;
79225              pCol->iMem = ++pParse->nMem;
79226              pCol->iSorterColumn = -1;
79227              pCol->pExpr = pExpr;
79228              if( pAggInfo->pGroupBy ){
79229                int j, n;
79230                ExprList *pGB = pAggInfo->pGroupBy;
79231                struct ExprList_item *pTerm = pGB->a;
79232                n = pGB->nExpr;
79233                for(j=0; j<n; j++, pTerm++){
79234                  Expr *pE = pTerm->pExpr;
79235                  if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
79236                      pE->iColumn==pExpr->iColumn ){
79237                    pCol->iSorterColumn = j;
79238                    break;
79239                  }
79240                }
79241              }
79242              if( pCol->iSorterColumn<0 ){
79243                pCol->iSorterColumn = pAggInfo->nSortingColumn++;
79244              }
79245            }
79246            /* There is now an entry for pExpr in pAggInfo->aCol[] (either
79247            ** because it was there before or because we just created it).
79248            ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
79249            ** pAggInfo->aCol[] entry.
79250            */
79251            ExprSetIrreducible(pExpr);
79252            pExpr->pAggInfo = pAggInfo;
79253            pExpr->op = TK_AGG_COLUMN;
79254            pExpr->iAgg = (i16)k;
79255            break;
79256          } /* endif pExpr->iTable==pItem->iCursor */
79257        } /* end loop over pSrcList */
79258      }
79259      return WRC_Prune;
79260    }
79261    case TK_AGG_FUNCTION: {
79262      if( (pNC->ncFlags & NC_InAggFunc)==0
79263       && pWalker->walkerDepth==pExpr->op2
79264      ){
79265        /* Check to see if pExpr is a duplicate of another aggregate
79266        ** function that is already in the pAggInfo structure
79267        */
79268        struct AggInfo_func *pItem = pAggInfo->aFunc;
79269        for(i=0; i<pAggInfo->nFunc; i++, pItem++){
79270          if( sqlite3ExprCompare(pItem->pExpr, pExpr)==0 ){
79271            break;
79272          }
79273        }
79274        if( i>=pAggInfo->nFunc ){
79275          /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
79276          */
79277          u8 enc = ENC(pParse->db);
79278          i = addAggInfoFunc(pParse->db, pAggInfo);
79279          if( i>=0 ){
79280            assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
79281            pItem = &pAggInfo->aFunc[i];
79282            pItem->pExpr = pExpr;
79283            pItem->iMem = ++pParse->nMem;
79284            assert( !ExprHasProperty(pExpr, EP_IntValue) );
79285            pItem->pFunc = sqlite3FindFunction(pParse->db,
79286                   pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
79287                   pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
79288            if( pExpr->flags & EP_Distinct ){
79289              pItem->iDistinct = pParse->nTab++;
79290            }else{
79291              pItem->iDistinct = -1;
79292            }
79293          }
79294        }
79295        /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
79296        */
79297        assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
79298        ExprSetIrreducible(pExpr);
79299        pExpr->iAgg = (i16)i;
79300        pExpr->pAggInfo = pAggInfo;
79301        return WRC_Prune;
79302      }else{
79303        return WRC_Continue;
79304      }
79305    }
79306  }
79307  return WRC_Continue;
79308}
79309static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
79310  UNUSED_PARAMETER(pWalker);
79311  UNUSED_PARAMETER(pSelect);
79312  return WRC_Continue;
79313}
79314
79315/*
79316** Analyze the pExpr expression looking for aggregate functions and
79317** for variables that need to be added to AggInfo object that pNC->pAggInfo
79318** points to.  Additional entries are made on the AggInfo object as
79319** necessary.
79320**
79321** This routine should only be called after the expression has been
79322** analyzed by sqlite3ResolveExprNames().
79323*/
79324SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
79325  Walker w;
79326  memset(&w, 0, sizeof(w));
79327  w.xExprCallback = analyzeAggregate;
79328  w.xSelectCallback = analyzeAggregatesInSelect;
79329  w.u.pNC = pNC;
79330  assert( pNC->pSrcList!=0 );
79331  sqlite3WalkExpr(&w, pExpr);
79332}
79333
79334/*
79335** Call sqlite3ExprAnalyzeAggregates() for every expression in an
79336** expression list.  Return the number of errors.
79337**
79338** If an error is found, the analysis is cut short.
79339*/
79340SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
79341  struct ExprList_item *pItem;
79342  int i;
79343  if( pList ){
79344    for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
79345      sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
79346    }
79347  }
79348}
79349
79350/*
79351** Allocate a single new register for use to hold some intermediate result.
79352*/
79353SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
79354  if( pParse->nTempReg==0 ){
79355    return ++pParse->nMem;
79356  }
79357  return pParse->aTempReg[--pParse->nTempReg];
79358}
79359
79360/*
79361** Deallocate a register, making available for reuse for some other
79362** purpose.
79363**
79364** If a register is currently being used by the column cache, then
79365** the dallocation is deferred until the column cache line that uses
79366** the register becomes stale.
79367*/
79368SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
79369  if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
79370    int i;
79371    struct yColCache *p;
79372    for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
79373      if( p->iReg==iReg ){
79374        p->tempReg = 1;
79375        return;
79376      }
79377    }
79378    pParse->aTempReg[pParse->nTempReg++] = iReg;
79379  }
79380}
79381
79382/*
79383** Allocate or deallocate a block of nReg consecutive registers
79384*/
79385SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
79386  int i, n;
79387  i = pParse->iRangeReg;
79388  n = pParse->nRangeReg;
79389  if( nReg<=n ){
79390    assert( !usedAsColumnCache(pParse, i, i+n-1) );
79391    pParse->iRangeReg += nReg;
79392    pParse->nRangeReg -= nReg;
79393  }else{
79394    i = pParse->nMem+1;
79395    pParse->nMem += nReg;
79396  }
79397  return i;
79398}
79399SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
79400  sqlite3ExprCacheRemove(pParse, iReg, nReg);
79401  if( nReg>pParse->nRangeReg ){
79402    pParse->nRangeReg = nReg;
79403    pParse->iRangeReg = iReg;
79404  }
79405}
79406
79407/*
79408** Mark all temporary registers as being unavailable for reuse.
79409*/
79410SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
79411  pParse->nTempReg = 0;
79412  pParse->nRangeReg = 0;
79413}
79414
79415/************** End of expr.c ************************************************/
79416/************** Begin file alter.c *******************************************/
79417/*
79418** 2005 February 15
79419**
79420** The author disclaims copyright to this source code.  In place of
79421** a legal notice, here is a blessing:
79422**
79423**    May you do good and not evil.
79424**    May you find forgiveness for yourself and forgive others.
79425**    May you share freely, never taking more than you give.
79426**
79427*************************************************************************
79428** This file contains C code routines that used to generate VDBE code
79429** that implements the ALTER TABLE command.
79430*/
79431
79432/*
79433** The code in this file only exists if we are not omitting the
79434** ALTER TABLE logic from the build.
79435*/
79436#ifndef SQLITE_OMIT_ALTERTABLE
79437
79438
79439/*
79440** This function is used by SQL generated to implement the
79441** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
79442** CREATE INDEX command. The second is a table name. The table name in
79443** the CREATE TABLE or CREATE INDEX statement is replaced with the third
79444** argument and the result returned. Examples:
79445**
79446** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
79447**     -> 'CREATE TABLE def(a, b, c)'
79448**
79449** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
79450**     -> 'CREATE INDEX i ON def(a, b, c)'
79451*/
79452static void renameTableFunc(
79453  sqlite3_context *context,
79454  int NotUsed,
79455  sqlite3_value **argv
79456){
79457  unsigned char const *zSql = sqlite3_value_text(argv[0]);
79458  unsigned char const *zTableName = sqlite3_value_text(argv[1]);
79459
79460  int token;
79461  Token tname;
79462  unsigned char const *zCsr = zSql;
79463  int len = 0;
79464  char *zRet;
79465
79466  sqlite3 *db = sqlite3_context_db_handle(context);
79467
79468  UNUSED_PARAMETER(NotUsed);
79469
79470  /* The principle used to locate the table name in the CREATE TABLE
79471  ** statement is that the table name is the first non-space token that
79472  ** is immediately followed by a TK_LP or TK_USING token.
79473  */
79474  if( zSql ){
79475    do {
79476      if( !*zCsr ){
79477        /* Ran out of input before finding an opening bracket. Return NULL. */
79478        return;
79479      }
79480
79481      /* Store the token that zCsr points to in tname. */
79482      tname.z = (char*)zCsr;
79483      tname.n = len;
79484
79485      /* Advance zCsr to the next token. Store that token type in 'token',
79486      ** and its length in 'len' (to be used next iteration of this loop).
79487      */
79488      do {
79489        zCsr += len;
79490        len = sqlite3GetToken(zCsr, &token);
79491      } while( token==TK_SPACE );
79492      assert( len>0 );
79493    } while( token!=TK_LP && token!=TK_USING );
79494
79495    zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
79496       zTableName, tname.z+tname.n);
79497    sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
79498  }
79499}
79500
79501/*
79502** This C function implements an SQL user function that is used by SQL code
79503** generated by the ALTER TABLE ... RENAME command to modify the definition
79504** of any foreign key constraints that use the table being renamed as the
79505** parent table. It is passed three arguments:
79506**
79507**   1) The complete text of the CREATE TABLE statement being modified,
79508**   2) The old name of the table being renamed, and
79509**   3) The new name of the table being renamed.
79510**
79511** It returns the new CREATE TABLE statement. For example:
79512**
79513**   sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
79514**       -> 'CREATE TABLE t1(a REFERENCES t3)'
79515*/
79516#ifndef SQLITE_OMIT_FOREIGN_KEY
79517static void renameParentFunc(
79518  sqlite3_context *context,
79519  int NotUsed,
79520  sqlite3_value **argv
79521){
79522  sqlite3 *db = sqlite3_context_db_handle(context);
79523  char *zOutput = 0;
79524  char *zResult;
79525  unsigned char const *zInput = sqlite3_value_text(argv[0]);
79526  unsigned char const *zOld = sqlite3_value_text(argv[1]);
79527  unsigned char const *zNew = sqlite3_value_text(argv[2]);
79528
79529  unsigned const char *z;         /* Pointer to token */
79530  int n;                          /* Length of token z */
79531  int token;                      /* Type of token */
79532
79533  UNUSED_PARAMETER(NotUsed);
79534  for(z=zInput; *z; z=z+n){
79535    n = sqlite3GetToken(z, &token);
79536    if( token==TK_REFERENCES ){
79537      char *zParent;
79538      do {
79539        z += n;
79540        n = sqlite3GetToken(z, &token);
79541      }while( token==TK_SPACE );
79542
79543      zParent = sqlite3DbStrNDup(db, (const char *)z, n);
79544      if( zParent==0 ) break;
79545      sqlite3Dequote(zParent);
79546      if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
79547        char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
79548            (zOutput?zOutput:""), z-zInput, zInput, (const char *)zNew
79549        );
79550        sqlite3DbFree(db, zOutput);
79551        zOutput = zOut;
79552        zInput = &z[n];
79553      }
79554      sqlite3DbFree(db, zParent);
79555    }
79556  }
79557
79558  zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
79559  sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
79560  sqlite3DbFree(db, zOutput);
79561}
79562#endif
79563
79564#ifndef SQLITE_OMIT_TRIGGER
79565/* This function is used by SQL generated to implement the
79566** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
79567** statement. The second is a table name. The table name in the CREATE
79568** TRIGGER statement is replaced with the third argument and the result
79569** returned. This is analagous to renameTableFunc() above, except for CREATE
79570** TRIGGER, not CREATE INDEX and CREATE TABLE.
79571*/
79572static void renameTriggerFunc(
79573  sqlite3_context *context,
79574  int NotUsed,
79575  sqlite3_value **argv
79576){
79577  unsigned char const *zSql = sqlite3_value_text(argv[0]);
79578  unsigned char const *zTableName = sqlite3_value_text(argv[1]);
79579
79580  int token;
79581  Token tname;
79582  int dist = 3;
79583  unsigned char const *zCsr = zSql;
79584  int len = 0;
79585  char *zRet;
79586  sqlite3 *db = sqlite3_context_db_handle(context);
79587
79588  UNUSED_PARAMETER(NotUsed);
79589
79590  /* The principle used to locate the table name in the CREATE TRIGGER
79591  ** statement is that the table name is the first token that is immediatedly
79592  ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
79593  ** of TK_WHEN, TK_BEGIN or TK_FOR.
79594  */
79595  if( zSql ){
79596    do {
79597
79598      if( !*zCsr ){
79599        /* Ran out of input before finding the table name. Return NULL. */
79600        return;
79601      }
79602
79603      /* Store the token that zCsr points to in tname. */
79604      tname.z = (char*)zCsr;
79605      tname.n = len;
79606
79607      /* Advance zCsr to the next token. Store that token type in 'token',
79608      ** and its length in 'len' (to be used next iteration of this loop).
79609      */
79610      do {
79611        zCsr += len;
79612        len = sqlite3GetToken(zCsr, &token);
79613      }while( token==TK_SPACE );
79614      assert( len>0 );
79615
79616      /* Variable 'dist' stores the number of tokens read since the most
79617      ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
79618      ** token is read and 'dist' equals 2, the condition stated above
79619      ** to be met.
79620      **
79621      ** Note that ON cannot be a database, table or column name, so
79622      ** there is no need to worry about syntax like
79623      ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
79624      */
79625      dist++;
79626      if( token==TK_DOT || token==TK_ON ){
79627        dist = 0;
79628      }
79629    } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
79630
79631    /* Variable tname now contains the token that is the old table-name
79632    ** in the CREATE TRIGGER statement.
79633    */
79634    zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
79635       zTableName, tname.z+tname.n);
79636    sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
79637  }
79638}
79639#endif   /* !SQLITE_OMIT_TRIGGER */
79640
79641/*
79642** Register built-in functions used to help implement ALTER TABLE
79643*/
79644SQLITE_PRIVATE void sqlite3AlterFunctions(void){
79645  static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
79646    FUNCTION(sqlite_rename_table,   2, 0, 0, renameTableFunc),
79647#ifndef SQLITE_OMIT_TRIGGER
79648    FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
79649#endif
79650#ifndef SQLITE_OMIT_FOREIGN_KEY
79651    FUNCTION(sqlite_rename_parent,  3, 0, 0, renameParentFunc),
79652#endif
79653  };
79654  int i;
79655  FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
79656  FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
79657
79658  for(i=0; i<ArraySize(aAlterTableFuncs); i++){
79659    sqlite3FuncDefInsert(pHash, &aFunc[i]);
79660  }
79661}
79662
79663/*
79664** This function is used to create the text of expressions of the form:
79665**
79666**   name=<constant1> OR name=<constant2> OR ...
79667**
79668** If argument zWhere is NULL, then a pointer string containing the text
79669** "name=<constant>" is returned, where <constant> is the quoted version
79670** of the string passed as argument zConstant. The returned buffer is
79671** allocated using sqlite3DbMalloc(). It is the responsibility of the
79672** caller to ensure that it is eventually freed.
79673**
79674** If argument zWhere is not NULL, then the string returned is
79675** "<where> OR name=<constant>", where <where> is the contents of zWhere.
79676** In this case zWhere is passed to sqlite3DbFree() before returning.
79677**
79678*/
79679static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
79680  char *zNew;
79681  if( !zWhere ){
79682    zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
79683  }else{
79684    zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
79685    sqlite3DbFree(db, zWhere);
79686  }
79687  return zNew;
79688}
79689
79690#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
79691/*
79692** Generate the text of a WHERE expression which can be used to select all
79693** tables that have foreign key constraints that refer to table pTab (i.e.
79694** constraints for which pTab is the parent table) from the sqlite_master
79695** table.
79696*/
79697static char *whereForeignKeys(Parse *pParse, Table *pTab){
79698  FKey *p;
79699  char *zWhere = 0;
79700  for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
79701    zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
79702  }
79703  return zWhere;
79704}
79705#endif
79706
79707/*
79708** Generate the text of a WHERE expression which can be used to select all
79709** temporary triggers on table pTab from the sqlite_temp_master table. If
79710** table pTab has no temporary triggers, or is itself stored in the
79711** temporary database, NULL is returned.
79712*/
79713static char *whereTempTriggers(Parse *pParse, Table *pTab){
79714  Trigger *pTrig;
79715  char *zWhere = 0;
79716  const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
79717
79718  /* If the table is not located in the temp-db (in which case NULL is
79719  ** returned, loop through the tables list of triggers. For each trigger
79720  ** that is not part of the temp-db schema, add a clause to the WHERE
79721  ** expression being built up in zWhere.
79722  */
79723  if( pTab->pSchema!=pTempSchema ){
79724    sqlite3 *db = pParse->db;
79725    for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
79726      if( pTrig->pSchema==pTempSchema ){
79727        zWhere = whereOrName(db, zWhere, pTrig->zName);
79728      }
79729    }
79730  }
79731  if( zWhere ){
79732    char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
79733    sqlite3DbFree(pParse->db, zWhere);
79734    zWhere = zNew;
79735  }
79736  return zWhere;
79737}
79738
79739/*
79740** Generate code to drop and reload the internal representation of table
79741** pTab from the database, including triggers and temporary triggers.
79742** Argument zName is the name of the table in the database schema at
79743** the time the generated code is executed. This can be different from
79744** pTab->zName if this function is being called to code part of an
79745** "ALTER TABLE RENAME TO" statement.
79746*/
79747static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
79748  Vdbe *v;
79749  char *zWhere;
79750  int iDb;                   /* Index of database containing pTab */
79751#ifndef SQLITE_OMIT_TRIGGER
79752  Trigger *pTrig;
79753#endif
79754
79755  v = sqlite3GetVdbe(pParse);
79756  if( NEVER(v==0) ) return;
79757  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
79758  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
79759  assert( iDb>=0 );
79760
79761#ifndef SQLITE_OMIT_TRIGGER
79762  /* Drop any table triggers from the internal schema. */
79763  for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
79764    int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
79765    assert( iTrigDb==iDb || iTrigDb==1 );
79766    sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
79767  }
79768#endif
79769
79770  /* Drop the table and index from the internal schema.  */
79771  sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
79772
79773  /* Reload the table, index and permanent trigger schemas. */
79774  zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
79775  if( !zWhere ) return;
79776  sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
79777
79778#ifndef SQLITE_OMIT_TRIGGER
79779  /* Now, if the table is not stored in the temp database, reload any temp
79780  ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
79781  */
79782  if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
79783    sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
79784  }
79785#endif
79786}
79787
79788/*
79789** Parameter zName is the name of a table that is about to be altered
79790** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
79791** If the table is a system table, this function leaves an error message
79792** in pParse->zErr (system tables may not be altered) and returns non-zero.
79793**
79794** Or, if zName is not a system table, zero is returned.
79795*/
79796static int isSystemTable(Parse *pParse, const char *zName){
79797  if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
79798    sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
79799    return 1;
79800  }
79801  return 0;
79802}
79803
79804/*
79805** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
79806** command.
79807*/
79808SQLITE_PRIVATE void sqlite3AlterRenameTable(
79809  Parse *pParse,            /* Parser context. */
79810  SrcList *pSrc,            /* The table to rename. */
79811  Token *pName              /* The new table name. */
79812){
79813  int iDb;                  /* Database that contains the table */
79814  char *zDb;                /* Name of database iDb */
79815  Table *pTab;              /* Table being renamed */
79816  char *zName = 0;          /* NULL-terminated version of pName */
79817  sqlite3 *db = pParse->db; /* Database connection */
79818  int nTabName;             /* Number of UTF-8 characters in zTabName */
79819  const char *zTabName;     /* Original name of the table */
79820  Vdbe *v;
79821#ifndef SQLITE_OMIT_TRIGGER
79822  char *zWhere = 0;         /* Where clause to locate temp triggers */
79823#endif
79824  VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
79825  int savedDbFlags;         /* Saved value of db->flags */
79826
79827  savedDbFlags = db->flags;
79828  if( NEVER(db->mallocFailed) ) goto exit_rename_table;
79829  assert( pSrc->nSrc==1 );
79830  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
79831
79832  pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
79833  if( !pTab ) goto exit_rename_table;
79834  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
79835  zDb = db->aDb[iDb].zName;
79836  db->flags |= SQLITE_PreferBuiltin;
79837
79838  /* Get a NULL terminated version of the new table name. */
79839  zName = sqlite3NameFromToken(db, pName);
79840  if( !zName ) goto exit_rename_table;
79841
79842  /* Check that a table or index named 'zName' does not already exist
79843  ** in database iDb. If so, this is an error.
79844  */
79845  if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
79846    sqlite3ErrorMsg(pParse,
79847        "there is already another table or index with this name: %s", zName);
79848    goto exit_rename_table;
79849  }
79850
79851  /* Make sure it is not a system table being altered, or a reserved name
79852  ** that the table is being renamed to.
79853  */
79854  if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
79855    goto exit_rename_table;
79856  }
79857  if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
79858    exit_rename_table;
79859  }
79860
79861#ifndef SQLITE_OMIT_VIEW
79862  if( pTab->pSelect ){
79863    sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
79864    goto exit_rename_table;
79865  }
79866#endif
79867
79868#ifndef SQLITE_OMIT_AUTHORIZATION
79869  /* Invoke the authorization callback. */
79870  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
79871    goto exit_rename_table;
79872  }
79873#endif
79874
79875#ifndef SQLITE_OMIT_VIRTUALTABLE
79876  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
79877    goto exit_rename_table;
79878  }
79879  if( IsVirtual(pTab) ){
79880    pVTab = sqlite3GetVTable(db, pTab);
79881    if( pVTab->pVtab->pModule->xRename==0 ){
79882      pVTab = 0;
79883    }
79884  }
79885#endif
79886
79887  /* Begin a transaction and code the VerifyCookie for database iDb.
79888  ** Then modify the schema cookie (since the ALTER TABLE modifies the
79889  ** schema). Open a statement transaction if the table is a virtual
79890  ** table.
79891  */
79892  v = sqlite3GetVdbe(pParse);
79893  if( v==0 ){
79894    goto exit_rename_table;
79895  }
79896  sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
79897  sqlite3ChangeCookie(pParse, iDb);
79898
79899  /* If this is a virtual table, invoke the xRename() function if
79900  ** one is defined. The xRename() callback will modify the names
79901  ** of any resources used by the v-table implementation (including other
79902  ** SQLite tables) that are identified by the name of the virtual table.
79903  */
79904#ifndef SQLITE_OMIT_VIRTUALTABLE
79905  if( pVTab ){
79906    int i = ++pParse->nMem;
79907    sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
79908    sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
79909    sqlite3MayAbort(pParse);
79910  }
79911#endif
79912
79913  /* figure out how many UTF-8 characters are in zName */
79914  zTabName = pTab->zName;
79915  nTabName = sqlite3Utf8CharLen(zTabName, -1);
79916
79917#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
79918  if( db->flags&SQLITE_ForeignKeys ){
79919    /* If foreign-key support is enabled, rewrite the CREATE TABLE
79920    ** statements corresponding to all child tables of foreign key constraints
79921    ** for which the renamed table is the parent table.  */
79922    if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
79923      sqlite3NestedParse(pParse,
79924          "UPDATE \"%w\".%s SET "
79925              "sql = sqlite_rename_parent(sql, %Q, %Q) "
79926              "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
79927      sqlite3DbFree(db, zWhere);
79928    }
79929  }
79930#endif
79931
79932  /* Modify the sqlite_master table to use the new table name. */
79933  sqlite3NestedParse(pParse,
79934      "UPDATE %Q.%s SET "
79935#ifdef SQLITE_OMIT_TRIGGER
79936          "sql = sqlite_rename_table(sql, %Q), "
79937#else
79938          "sql = CASE "
79939            "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
79940            "ELSE sqlite_rename_table(sql, %Q) END, "
79941#endif
79942          "tbl_name = %Q, "
79943          "name = CASE "
79944            "WHEN type='table' THEN %Q "
79945            "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
79946             "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
79947            "ELSE name END "
79948      "WHERE tbl_name=%Q COLLATE nocase AND "
79949          "(type='table' OR type='index' OR type='trigger');",
79950      zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
79951#ifndef SQLITE_OMIT_TRIGGER
79952      zName,
79953#endif
79954      zName, nTabName, zTabName
79955  );
79956
79957#ifndef SQLITE_OMIT_AUTOINCREMENT
79958  /* If the sqlite_sequence table exists in this database, then update
79959  ** it with the new table name.
79960  */
79961  if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
79962    sqlite3NestedParse(pParse,
79963        "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
79964        zDb, zName, pTab->zName);
79965  }
79966#endif
79967
79968#ifndef SQLITE_OMIT_TRIGGER
79969  /* If there are TEMP triggers on this table, modify the sqlite_temp_master
79970  ** table. Don't do this if the table being ALTERed is itself located in
79971  ** the temp database.
79972  */
79973  if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
79974    sqlite3NestedParse(pParse,
79975        "UPDATE sqlite_temp_master SET "
79976            "sql = sqlite_rename_trigger(sql, %Q), "
79977            "tbl_name = %Q "
79978            "WHERE %s;", zName, zName, zWhere);
79979    sqlite3DbFree(db, zWhere);
79980  }
79981#endif
79982
79983#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
79984  if( db->flags&SQLITE_ForeignKeys ){
79985    FKey *p;
79986    for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
79987      Table *pFrom = p->pFrom;
79988      if( pFrom!=pTab ){
79989        reloadTableSchema(pParse, p->pFrom, pFrom->zName);
79990      }
79991    }
79992  }
79993#endif
79994
79995  /* Drop and reload the internal table schema. */
79996  reloadTableSchema(pParse, pTab, zName);
79997
79998exit_rename_table:
79999  sqlite3SrcListDelete(db, pSrc);
80000  sqlite3DbFree(db, zName);
80001  db->flags = savedDbFlags;
80002}
80003
80004
80005/*
80006** Generate code to make sure the file format number is at least minFormat.
80007** The generated code will increase the file format number if necessary.
80008*/
80009SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
80010  Vdbe *v;
80011  v = sqlite3GetVdbe(pParse);
80012  /* The VDBE should have been allocated before this routine is called.
80013  ** If that allocation failed, we would have quit before reaching this
80014  ** point */
80015  if( ALWAYS(v) ){
80016    int r1 = sqlite3GetTempReg(pParse);
80017    int r2 = sqlite3GetTempReg(pParse);
80018    int j1;
80019    sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
80020    sqlite3VdbeUsesBtree(v, iDb);
80021    sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
80022    j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
80023    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
80024    sqlite3VdbeJumpHere(v, j1);
80025    sqlite3ReleaseTempReg(pParse, r1);
80026    sqlite3ReleaseTempReg(pParse, r2);
80027  }
80028}
80029
80030/*
80031** This function is called after an "ALTER TABLE ... ADD" statement
80032** has been parsed. Argument pColDef contains the text of the new
80033** column definition.
80034**
80035** The Table structure pParse->pNewTable was extended to include
80036** the new column during parsing.
80037*/
80038SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
80039  Table *pNew;              /* Copy of pParse->pNewTable */
80040  Table *pTab;              /* Table being altered */
80041  int iDb;                  /* Database number */
80042  const char *zDb;          /* Database name */
80043  const char *zTab;         /* Table name */
80044  char *zCol;               /* Null-terminated column definition */
80045  Column *pCol;             /* The new column */
80046  Expr *pDflt;              /* Default value for the new column */
80047  sqlite3 *db;              /* The database connection; */
80048
80049  db = pParse->db;
80050  if( pParse->nErr || db->mallocFailed ) return;
80051  pNew = pParse->pNewTable;
80052  assert( pNew );
80053
80054  assert( sqlite3BtreeHoldsAllMutexes(db) );
80055  iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
80056  zDb = db->aDb[iDb].zName;
80057  zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
80058  pCol = &pNew->aCol[pNew->nCol-1];
80059  pDflt = pCol->pDflt;
80060  pTab = sqlite3FindTable(db, zTab, zDb);
80061  assert( pTab );
80062
80063#ifndef SQLITE_OMIT_AUTHORIZATION
80064  /* Invoke the authorization callback. */
80065  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
80066    return;
80067  }
80068#endif
80069
80070  /* If the default value for the new column was specified with a
80071  ** literal NULL, then set pDflt to 0. This simplifies checking
80072  ** for an SQL NULL default below.
80073  */
80074  if( pDflt && pDflt->op==TK_NULL ){
80075    pDflt = 0;
80076  }
80077
80078  /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
80079  ** If there is a NOT NULL constraint, then the default value for the
80080  ** column must not be NULL.
80081  */
80082  if( pCol->colFlags & COLFLAG_PRIMKEY ){
80083    sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
80084    return;
80085  }
80086  if( pNew->pIndex ){
80087    sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
80088    return;
80089  }
80090  if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
80091    sqlite3ErrorMsg(pParse,
80092        "Cannot add a REFERENCES column with non-NULL default value");
80093    return;
80094  }
80095  if( pCol->notNull && !pDflt ){
80096    sqlite3ErrorMsg(pParse,
80097        "Cannot add a NOT NULL column with default value NULL");
80098    return;
80099  }
80100
80101  /* Ensure the default expression is something that sqlite3ValueFromExpr()
80102  ** can handle (i.e. not CURRENT_TIME etc.)
80103  */
80104  if( pDflt ){
80105    sqlite3_value *pVal;
80106    if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
80107      db->mallocFailed = 1;
80108      return;
80109    }
80110    if( !pVal ){
80111      sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
80112      return;
80113    }
80114    sqlite3ValueFree(pVal);
80115  }
80116
80117  /* Modify the CREATE TABLE statement. */
80118  zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
80119  if( zCol ){
80120    char *zEnd = &zCol[pColDef->n-1];
80121    int savedDbFlags = db->flags;
80122    while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
80123      *zEnd-- = '\0';
80124    }
80125    db->flags |= SQLITE_PreferBuiltin;
80126    sqlite3NestedParse(pParse,
80127        "UPDATE \"%w\".%s SET "
80128          "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
80129        "WHERE type = 'table' AND name = %Q",
80130      zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
80131      zTab
80132    );
80133    sqlite3DbFree(db, zCol);
80134    db->flags = savedDbFlags;
80135  }
80136
80137  /* If the default value of the new column is NULL, then set the file
80138  ** format to 2. If the default value of the new column is not NULL,
80139  ** the file format becomes 3.
80140  */
80141  sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
80142
80143  /* Reload the schema of the modified table. */
80144  reloadTableSchema(pParse, pTab, pTab->zName);
80145}
80146
80147/*
80148** This function is called by the parser after the table-name in
80149** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
80150** pSrc is the full-name of the table being altered.
80151**
80152** This routine makes a (partial) copy of the Table structure
80153** for the table being altered and sets Parse.pNewTable to point
80154** to it. Routines called by the parser as the column definition
80155** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
80156** the copy. The copy of the Table structure is deleted by tokenize.c
80157** after parsing is finished.
80158**
80159** Routine sqlite3AlterFinishAddColumn() will be called to complete
80160** coding the "ALTER TABLE ... ADD" statement.
80161*/
80162SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
80163  Table *pNew;
80164  Table *pTab;
80165  Vdbe *v;
80166  int iDb;
80167  int i;
80168  int nAlloc;
80169  sqlite3 *db = pParse->db;
80170
80171  /* Look up the table being altered. */
80172  assert( pParse->pNewTable==0 );
80173  assert( sqlite3BtreeHoldsAllMutexes(db) );
80174  if( db->mallocFailed ) goto exit_begin_add_column;
80175  pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
80176  if( !pTab ) goto exit_begin_add_column;
80177
80178#ifndef SQLITE_OMIT_VIRTUALTABLE
80179  if( IsVirtual(pTab) ){
80180    sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
80181    goto exit_begin_add_column;
80182  }
80183#endif
80184
80185  /* Make sure this is not an attempt to ALTER a view. */
80186  if( pTab->pSelect ){
80187    sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
80188    goto exit_begin_add_column;
80189  }
80190  if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
80191    goto exit_begin_add_column;
80192  }
80193
80194  assert( pTab->addColOffset>0 );
80195  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
80196
80197  /* Put a copy of the Table struct in Parse.pNewTable for the
80198  ** sqlite3AddColumn() function and friends to modify.  But modify
80199  ** the name by adding an "sqlite_altertab_" prefix.  By adding this
80200  ** prefix, we insure that the name will not collide with an existing
80201  ** table because user table are not allowed to have the "sqlite_"
80202  ** prefix on their name.
80203  */
80204  pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
80205  if( !pNew ) goto exit_begin_add_column;
80206  pParse->pNewTable = pNew;
80207  pNew->nRef = 1;
80208  pNew->nCol = pTab->nCol;
80209  assert( pNew->nCol>0 );
80210  nAlloc = (((pNew->nCol-1)/8)*8)+8;
80211  assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
80212  pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
80213  pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
80214  if( !pNew->aCol || !pNew->zName ){
80215    db->mallocFailed = 1;
80216    goto exit_begin_add_column;
80217  }
80218  memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
80219  for(i=0; i<pNew->nCol; i++){
80220    Column *pCol = &pNew->aCol[i];
80221    pCol->zName = sqlite3DbStrDup(db, pCol->zName);
80222    pCol->zColl = 0;
80223    pCol->zType = 0;
80224    pCol->pDflt = 0;
80225    pCol->zDflt = 0;
80226  }
80227  pNew->pSchema = db->aDb[iDb].pSchema;
80228  pNew->addColOffset = pTab->addColOffset;
80229  pNew->nRef = 1;
80230
80231  /* Begin a transaction and increment the schema cookie.  */
80232  sqlite3BeginWriteOperation(pParse, 0, iDb);
80233  v = sqlite3GetVdbe(pParse);
80234  if( !v ) goto exit_begin_add_column;
80235  sqlite3ChangeCookie(pParse, iDb);
80236
80237exit_begin_add_column:
80238  sqlite3SrcListDelete(db, pSrc);
80239  return;
80240}
80241#endif  /* SQLITE_ALTER_TABLE */
80242
80243/************** End of alter.c ***********************************************/
80244/************** Begin file analyze.c *****************************************/
80245/*
80246** 2005 July 8
80247**
80248** The author disclaims copyright to this source code.  In place of
80249** a legal notice, here is a blessing:
80250**
80251**    May you do good and not evil.
80252**    May you find forgiveness for yourself and forgive others.
80253**    May you share freely, never taking more than you give.
80254**
80255*************************************************************************
80256** This file contains code associated with the ANALYZE command.
80257**
80258** The ANALYZE command gather statistics about the content of tables
80259** and indices.  These statistics are made available to the query planner
80260** to help it make better decisions about how to perform queries.
80261**
80262** The following system tables are or have been supported:
80263**
80264**    CREATE TABLE sqlite_stat1(tbl, idx, stat);
80265**    CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
80266**    CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
80267**
80268** Additional tables might be added in future releases of SQLite.
80269** The sqlite_stat2 table is not created or used unless the SQLite version
80270** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
80271** with SQLITE_ENABLE_STAT2.  The sqlite_stat2 table is deprecated.
80272** The sqlite_stat2 table is superceded by sqlite_stat3, which is only
80273** created and used by SQLite versions 3.7.9 and later and with
80274** SQLITE_ENABLE_STAT3 defined.  The fucntionality of sqlite_stat3
80275** is a superset of sqlite_stat2.
80276**
80277** Format of sqlite_stat1:
80278**
80279** There is normally one row per index, with the index identified by the
80280** name in the idx column.  The tbl column is the name of the table to
80281** which the index belongs.  In each such row, the stat column will be
80282** a string consisting of a list of integers.  The first integer in this
80283** list is the number of rows in the index and in the table.  The second
80284** integer is the average number of rows in the index that have the same
80285** value in the first column of the index.  The third integer is the average
80286** number of rows in the index that have the same value for the first two
80287** columns.  The N-th integer (for N>1) is the average number of rows in
80288** the index which have the same value for the first N-1 columns.  For
80289** a K-column index, there will be K+1 integers in the stat column.  If
80290** the index is unique, then the last integer will be 1.
80291**
80292** The list of integers in the stat column can optionally be followed
80293** by the keyword "unordered".  The "unordered" keyword, if it is present,
80294** must be separated from the last integer by a single space.  If the
80295** "unordered" keyword is present, then the query planner assumes that
80296** the index is unordered and will not use the index for a range query.
80297**
80298** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
80299** column contains a single integer which is the (estimated) number of
80300** rows in the table identified by sqlite_stat1.tbl.
80301**
80302** Format of sqlite_stat2:
80303**
80304** The sqlite_stat2 is only created and is only used if SQLite is compiled
80305** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
80306** 3.6.18 and 3.7.8.  The "stat2" table contains additional information
80307** about the distribution of keys within an index.  The index is identified by
80308** the "idx" column and the "tbl" column is the name of the table to which
80309** the index belongs.  There are usually 10 rows in the sqlite_stat2
80310** table for each index.
80311**
80312** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
80313** inclusive are samples of the left-most key value in the index taken at
80314** evenly spaced points along the index.  Let the number of samples be S
80315** (10 in the standard build) and let C be the number of rows in the index.
80316** Then the sampled rows are given by:
80317**
80318**     rownumber = (i*C*2 + C)/(S*2)
80319**
80320** For i between 0 and S-1.  Conceptually, the index space is divided into
80321** S uniform buckets and the samples are the middle row from each bucket.
80322**
80323** The format for sqlite_stat2 is recorded here for legacy reference.  This
80324** version of SQLite does not support sqlite_stat2.  It neither reads nor
80325** writes the sqlite_stat2 table.  This version of SQLite only supports
80326** sqlite_stat3.
80327**
80328** Format for sqlite_stat3:
80329**
80330** The sqlite_stat3 is an enhancement to sqlite_stat2.  A new name is
80331** used to avoid compatibility problems.
80332**
80333** The format of the sqlite_stat3 table is similar to the format of
80334** the sqlite_stat2 table.  There are multiple entries for each index.
80335** The idx column names the index and the tbl column is the table of the
80336** index.  If the idx and tbl columns are the same, then the sample is
80337** of the INTEGER PRIMARY KEY.  The sample column is a value taken from
80338** the left-most column of the index.  The nEq column is the approximate
80339** number of entires in the index whose left-most column exactly matches
80340** the sample.  nLt is the approximate number of entires whose left-most
80341** column is less than the sample.  The nDLt column is the approximate
80342** number of distinct left-most entries in the index that are less than
80343** the sample.
80344**
80345** Future versions of SQLite might change to store a string containing
80346** multiple integers values in the nDLt column of sqlite_stat3.  The first
80347** integer will be the number of prior index entires that are distinct in
80348** the left-most column.  The second integer will be the number of prior index
80349** entries that are distinct in the first two columns.  The third integer
80350** will be the number of prior index entries that are distinct in the first
80351** three columns.  And so forth.  With that extension, the nDLt field is
80352** similar in function to the sqlite_stat1.stat field.
80353**
80354** There can be an arbitrary number of sqlite_stat3 entries per index.
80355** The ANALYZE command will typically generate sqlite_stat3 tables
80356** that contain between 10 and 40 samples which are distributed across
80357** the key space, though not uniformly, and which include samples with
80358** largest possible nEq values.
80359*/
80360#ifndef SQLITE_OMIT_ANALYZE
80361
80362/*
80363** This routine generates code that opens the sqlite_stat1 table for
80364** writing with cursor iStatCur. If the library was built with the
80365** SQLITE_ENABLE_STAT3 macro defined, then the sqlite_stat3 table is
80366** opened for writing using cursor (iStatCur+1)
80367**
80368** If the sqlite_stat1 tables does not previously exist, it is created.
80369** Similarly, if the sqlite_stat3 table does not exist and the library
80370** is compiled with SQLITE_ENABLE_STAT3 defined, it is created.
80371**
80372** Argument zWhere may be a pointer to a buffer containing a table name,
80373** or it may be a NULL pointer. If it is not NULL, then all entries in
80374** the sqlite_stat1 and (if applicable) sqlite_stat3 tables associated
80375** with the named table are deleted. If zWhere==0, then code is generated
80376** to delete all stat table entries.
80377*/
80378static void openStatTable(
80379  Parse *pParse,          /* Parsing context */
80380  int iDb,                /* The database we are looking in */
80381  int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
80382  const char *zWhere,     /* Delete entries for this table or index */
80383  const char *zWhereType  /* Either "tbl" or "idx" */
80384){
80385  static const struct {
80386    const char *zName;
80387    const char *zCols;
80388  } aTable[] = {
80389    { "sqlite_stat1", "tbl,idx,stat" },
80390#ifdef SQLITE_ENABLE_STAT3
80391    { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
80392#endif
80393  };
80394
80395  int aRoot[] = {0, 0};
80396  u8 aCreateTbl[] = {0, 0};
80397
80398  int i;
80399  sqlite3 *db = pParse->db;
80400  Db *pDb;
80401  Vdbe *v = sqlite3GetVdbe(pParse);
80402  if( v==0 ) return;
80403  assert( sqlite3BtreeHoldsAllMutexes(db) );
80404  assert( sqlite3VdbeDb(v)==db );
80405  pDb = &db->aDb[iDb];
80406
80407  /* Create new statistic tables if they do not exist, or clear them
80408  ** if they do already exist.
80409  */
80410  for(i=0; i<ArraySize(aTable); i++){
80411    const char *zTab = aTable[i].zName;
80412    Table *pStat;
80413    if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
80414      /* The sqlite_stat[12] table does not exist. Create it. Note that a
80415      ** side-effect of the CREATE TABLE statement is to leave the rootpage
80416      ** of the new table in register pParse->regRoot. This is important
80417      ** because the OpenWrite opcode below will be needing it. */
80418      sqlite3NestedParse(pParse,
80419          "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
80420      );
80421      aRoot[i] = pParse->regRoot;
80422      aCreateTbl[i] = OPFLAG_P2ISREG;
80423    }else{
80424      /* The table already exists. If zWhere is not NULL, delete all entries
80425      ** associated with the table zWhere. If zWhere is NULL, delete the
80426      ** entire contents of the table. */
80427      aRoot[i] = pStat->tnum;
80428      sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
80429      if( zWhere ){
80430        sqlite3NestedParse(pParse,
80431           "DELETE FROM %Q.%s WHERE %s=%Q", pDb->zName, zTab, zWhereType, zWhere
80432        );
80433      }else{
80434        /* The sqlite_stat[12] table already exists.  Delete all rows. */
80435        sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
80436      }
80437    }
80438  }
80439
80440  /* Open the sqlite_stat[13] tables for writing. */
80441  for(i=0; i<ArraySize(aTable); i++){
80442    sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb);
80443    sqlite3VdbeChangeP4(v, -1, (char *)3, P4_INT32);
80444    sqlite3VdbeChangeP5(v, aCreateTbl[i]);
80445  }
80446}
80447
80448/*
80449** Recommended number of samples for sqlite_stat3
80450*/
80451#ifndef SQLITE_STAT3_SAMPLES
80452# define SQLITE_STAT3_SAMPLES 24
80453#endif
80454
80455/*
80456** Three SQL functions - stat3_init(), stat3_push(), and stat3_pop() -
80457** share an instance of the following structure to hold their state
80458** information.
80459*/
80460typedef struct Stat3Accum Stat3Accum;
80461struct Stat3Accum {
80462  tRowcnt nRow;             /* Number of rows in the entire table */
80463  tRowcnt nPSample;         /* How often to do a periodic sample */
80464  int iMin;                 /* Index of entry with minimum nEq and hash */
80465  int mxSample;             /* Maximum number of samples to accumulate */
80466  int nSample;              /* Current number of samples */
80467  u32 iPrn;                 /* Pseudo-random number used for sampling */
80468  struct Stat3Sample {
80469    i64 iRowid;                /* Rowid in main table of the key */
80470    tRowcnt nEq;               /* sqlite_stat3.nEq */
80471    tRowcnt nLt;               /* sqlite_stat3.nLt */
80472    tRowcnt nDLt;              /* sqlite_stat3.nDLt */
80473    u8 isPSample;              /* True if a periodic sample */
80474    u32 iHash;                 /* Tiebreaker hash */
80475  } *a;                     /* An array of samples */
80476};
80477
80478#ifdef SQLITE_ENABLE_STAT3
80479/*
80480** Implementation of the stat3_init(C,S) SQL function.  The two parameters
80481** are the number of rows in the table or index (C) and the number of samples
80482** to accumulate (S).
80483**
80484** This routine allocates the Stat3Accum object.
80485**
80486** The return value is the Stat3Accum object (P).
80487*/
80488static void stat3Init(
80489  sqlite3_context *context,
80490  int argc,
80491  sqlite3_value **argv
80492){
80493  Stat3Accum *p;
80494  tRowcnt nRow;
80495  int mxSample;
80496  int n;
80497
80498  UNUSED_PARAMETER(argc);
80499  nRow = (tRowcnt)sqlite3_value_int64(argv[0]);
80500  mxSample = sqlite3_value_int(argv[1]);
80501  n = sizeof(*p) + sizeof(p->a[0])*mxSample;
80502  p = sqlite3MallocZero( n );
80503  if( p==0 ){
80504    sqlite3_result_error_nomem(context);
80505    return;
80506  }
80507  p->a = (struct Stat3Sample*)&p[1];
80508  p->nRow = nRow;
80509  p->mxSample = mxSample;
80510  p->nPSample = p->nRow/(mxSample/3+1) + 1;
80511  sqlite3_randomness(sizeof(p->iPrn), &p->iPrn);
80512  sqlite3_result_blob(context, p, sizeof(p), sqlite3_free);
80513}
80514static const FuncDef stat3InitFuncdef = {
80515  2,                /* nArg */
80516  SQLITE_UTF8,      /* iPrefEnc */
80517  0,                /* flags */
80518  0,                /* pUserData */
80519  0,                /* pNext */
80520  stat3Init,        /* xFunc */
80521  0,                /* xStep */
80522  0,                /* xFinalize */
80523  "stat3_init",     /* zName */
80524  0,                /* pHash */
80525  0                 /* pDestructor */
80526};
80527
80528
80529/*
80530** Implementation of the stat3_push(nEq,nLt,nDLt,rowid,P) SQL function.  The
80531** arguments describe a single key instance.  This routine makes the
80532** decision about whether or not to retain this key for the sqlite_stat3
80533** table.
80534**
80535** The return value is NULL.
80536*/
80537static void stat3Push(
80538  sqlite3_context *context,
80539  int argc,
80540  sqlite3_value **argv
80541){
80542  Stat3Accum *p = (Stat3Accum*)sqlite3_value_blob(argv[4]);
80543  tRowcnt nEq = sqlite3_value_int64(argv[0]);
80544  tRowcnt nLt = sqlite3_value_int64(argv[1]);
80545  tRowcnt nDLt = sqlite3_value_int64(argv[2]);
80546  i64 rowid = sqlite3_value_int64(argv[3]);
80547  u8 isPSample = 0;
80548  u8 doInsert = 0;
80549  int iMin = p->iMin;
80550  struct Stat3Sample *pSample;
80551  int i;
80552  u32 h;
80553
80554  UNUSED_PARAMETER(context);
80555  UNUSED_PARAMETER(argc);
80556  if( nEq==0 ) return;
80557  h = p->iPrn = p->iPrn*1103515245 + 12345;
80558  if( (nLt/p->nPSample)!=((nEq+nLt)/p->nPSample) ){
80559    doInsert = isPSample = 1;
80560  }else if( p->nSample<p->mxSample ){
80561    doInsert = 1;
80562  }else{
80563    if( nEq>p->a[iMin].nEq || (nEq==p->a[iMin].nEq && h>p->a[iMin].iHash) ){
80564      doInsert = 1;
80565    }
80566  }
80567  if( !doInsert ) return;
80568  if( p->nSample==p->mxSample ){
80569    assert( p->nSample - iMin - 1 >= 0 );
80570    memmove(&p->a[iMin], &p->a[iMin+1], sizeof(p->a[0])*(p->nSample-iMin-1));
80571    pSample = &p->a[p->nSample-1];
80572  }else{
80573    pSample = &p->a[p->nSample++];
80574  }
80575  pSample->iRowid = rowid;
80576  pSample->nEq = nEq;
80577  pSample->nLt = nLt;
80578  pSample->nDLt = nDLt;
80579  pSample->iHash = h;
80580  pSample->isPSample = isPSample;
80581
80582  /* Find the new minimum */
80583  if( p->nSample==p->mxSample ){
80584    pSample = p->a;
80585    i = 0;
80586    while( pSample->isPSample ){
80587      i++;
80588      pSample++;
80589      assert( i<p->nSample );
80590    }
80591    nEq = pSample->nEq;
80592    h = pSample->iHash;
80593    iMin = i;
80594    for(i++, pSample++; i<p->nSample; i++, pSample++){
80595      if( pSample->isPSample ) continue;
80596      if( pSample->nEq<nEq
80597       || (pSample->nEq==nEq && pSample->iHash<h)
80598      ){
80599        iMin = i;
80600        nEq = pSample->nEq;
80601        h = pSample->iHash;
80602      }
80603    }
80604    p->iMin = iMin;
80605  }
80606}
80607static const FuncDef stat3PushFuncdef = {
80608  5,                /* nArg */
80609  SQLITE_UTF8,      /* iPrefEnc */
80610  0,                /* flags */
80611  0,                /* pUserData */
80612  0,                /* pNext */
80613  stat3Push,        /* xFunc */
80614  0,                /* xStep */
80615  0,                /* xFinalize */
80616  "stat3_push",     /* zName */
80617  0,                /* pHash */
80618  0                 /* pDestructor */
80619};
80620
80621/*
80622** Implementation of the stat3_get(P,N,...) SQL function.  This routine is
80623** used to query the results.  Content is returned for the Nth sqlite_stat3
80624** row where N is between 0 and S-1 and S is the number of samples.  The
80625** value returned depends on the number of arguments.
80626**
80627**   argc==2    result:  rowid
80628**   argc==3    result:  nEq
80629**   argc==4    result:  nLt
80630**   argc==5    result:  nDLt
80631*/
80632static void stat3Get(
80633  sqlite3_context *context,
80634  int argc,
80635  sqlite3_value **argv
80636){
80637  int n = sqlite3_value_int(argv[1]);
80638  Stat3Accum *p = (Stat3Accum*)sqlite3_value_blob(argv[0]);
80639
80640  assert( p!=0 );
80641  if( p->nSample<=n ) return;
80642  switch( argc ){
80643    case 2:  sqlite3_result_int64(context, p->a[n].iRowid); break;
80644    case 3:  sqlite3_result_int64(context, p->a[n].nEq);    break;
80645    case 4:  sqlite3_result_int64(context, p->a[n].nLt);    break;
80646    default: sqlite3_result_int64(context, p->a[n].nDLt);   break;
80647  }
80648}
80649static const FuncDef stat3GetFuncdef = {
80650  -1,               /* nArg */
80651  SQLITE_UTF8,      /* iPrefEnc */
80652  0,                /* flags */
80653  0,                /* pUserData */
80654  0,                /* pNext */
80655  stat3Get,         /* xFunc */
80656  0,                /* xStep */
80657  0,                /* xFinalize */
80658  "stat3_get",     /* zName */
80659  0,                /* pHash */
80660  0                 /* pDestructor */
80661};
80662#endif /* SQLITE_ENABLE_STAT3 */
80663
80664
80665
80666
80667/*
80668** Generate code to do an analysis of all indices associated with
80669** a single table.
80670*/
80671static void analyzeOneTable(
80672  Parse *pParse,   /* Parser context */
80673  Table *pTab,     /* Table whose indices are to be analyzed */
80674  Index *pOnlyIdx, /* If not NULL, only analyze this one index */
80675  int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
80676  int iMem         /* Available memory locations begin here */
80677){
80678  sqlite3 *db = pParse->db;    /* Database handle */
80679  Index *pIdx;                 /* An index to being analyzed */
80680  int iIdxCur;                 /* Cursor open on index being analyzed */
80681  Vdbe *v;                     /* The virtual machine being built up */
80682  int i;                       /* Loop counter */
80683  int topOfLoop;               /* The top of the loop */
80684  int endOfLoop;               /* The end of the loop */
80685  int jZeroRows = -1;          /* Jump from here if number of rows is zero */
80686  int iDb;                     /* Index of database containing pTab */
80687  int regTabname = iMem++;     /* Register containing table name */
80688  int regIdxname = iMem++;     /* Register containing index name */
80689  int regStat1 = iMem++;       /* The stat column of sqlite_stat1 */
80690#ifdef SQLITE_ENABLE_STAT3
80691  int regNumEq = regStat1;     /* Number of instances.  Same as regStat1 */
80692  int regNumLt = iMem++;       /* Number of keys less than regSample */
80693  int regNumDLt = iMem++;      /* Number of distinct keys less than regSample */
80694  int regSample = iMem++;      /* The next sample value */
80695  int regRowid = regSample;    /* Rowid of a sample */
80696  int regAccum = iMem++;       /* Register to hold Stat3Accum object */
80697  int regLoop = iMem++;        /* Loop counter */
80698  int regCount = iMem++;       /* Number of rows in the table or index */
80699  int regTemp1 = iMem++;       /* Intermediate register */
80700  int regTemp2 = iMem++;       /* Intermediate register */
80701  int once = 1;                /* One-time initialization */
80702  int shortJump = 0;           /* Instruction address */
80703  int iTabCur = pParse->nTab++; /* Table cursor */
80704#endif
80705  int regCol = iMem++;         /* Content of a column in analyzed table */
80706  int regRec = iMem++;         /* Register holding completed record */
80707  int regTemp = iMem++;        /* Temporary use register */
80708  int regNewRowid = iMem++;    /* Rowid for the inserted record */
80709
80710
80711  v = sqlite3GetVdbe(pParse);
80712  if( v==0 || NEVER(pTab==0) ){
80713    return;
80714  }
80715  if( pTab->tnum==0 ){
80716    /* Do not gather statistics on views or virtual tables */
80717    return;
80718  }
80719  if( sqlite3_strnicmp(pTab->zName, "sqlite_", 7)==0 ){
80720    /* Do not gather statistics on system tables */
80721    return;
80722  }
80723  assert( sqlite3BtreeHoldsAllMutexes(db) );
80724  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
80725  assert( iDb>=0 );
80726  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
80727#ifndef SQLITE_OMIT_AUTHORIZATION
80728  if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
80729      db->aDb[iDb].zName ) ){
80730    return;
80731  }
80732#endif
80733
80734  /* Establish a read-lock on the table at the shared-cache level. */
80735  sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
80736
80737  iIdxCur = pParse->nTab++;
80738  sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
80739  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
80740    int nCol;
80741    KeyInfo *pKey;
80742    int addrIfNot = 0;           /* address of OP_IfNot */
80743    int *aChngAddr;              /* Array of jump instruction addresses */
80744
80745    if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
80746    VdbeNoopComment((v, "Begin analysis of %s", pIdx->zName));
80747    nCol = pIdx->nColumn;
80748    aChngAddr = sqlite3DbMallocRaw(db, sizeof(int)*nCol);
80749    if( aChngAddr==0 ) continue;
80750    pKey = sqlite3IndexKeyinfo(pParse, pIdx);
80751    if( iMem+1+(nCol*2)>pParse->nMem ){
80752      pParse->nMem = iMem+1+(nCol*2);
80753    }
80754
80755    /* Open a cursor to the index to be analyzed. */
80756    assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
80757    sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
80758        (char *)pKey, P4_KEYINFO_HANDOFF);
80759    VdbeComment((v, "%s", pIdx->zName));
80760
80761    /* Populate the register containing the index name. */
80762    sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0);
80763
80764#ifdef SQLITE_ENABLE_STAT3
80765    if( once ){
80766      once = 0;
80767      sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
80768    }
80769    sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regCount);
80770    sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_STAT3_SAMPLES, regTemp1);
80771    sqlite3VdbeAddOp2(v, OP_Integer, 0, regNumEq);
80772    sqlite3VdbeAddOp2(v, OP_Integer, 0, regNumLt);
80773    sqlite3VdbeAddOp2(v, OP_Integer, -1, regNumDLt);
80774    sqlite3VdbeAddOp3(v, OP_Null, 0, regSample, regAccum);
80775    sqlite3VdbeAddOp4(v, OP_Function, 1, regCount, regAccum,
80776                      (char*)&stat3InitFuncdef, P4_FUNCDEF);
80777    sqlite3VdbeChangeP5(v, 2);
80778#endif /* SQLITE_ENABLE_STAT3 */
80779
80780    /* The block of memory cells initialized here is used as follows.
80781    **
80782    **    iMem:
80783    **        The total number of rows in the table.
80784    **
80785    **    iMem+1 .. iMem+nCol:
80786    **        Number of distinct entries in index considering the
80787    **        left-most N columns only, where N is between 1 and nCol,
80788    **        inclusive.
80789    **
80790    **    iMem+nCol+1 .. Mem+2*nCol:
80791    **        Previous value of indexed columns, from left to right.
80792    **
80793    ** Cells iMem through iMem+nCol are initialized to 0. The others are
80794    ** initialized to contain an SQL NULL.
80795    */
80796    for(i=0; i<=nCol; i++){
80797      sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem+i);
80798    }
80799    for(i=0; i<nCol; i++){
80800      sqlite3VdbeAddOp2(v, OP_Null, 0, iMem+nCol+i+1);
80801    }
80802
80803    /* Start the analysis loop. This loop runs through all the entries in
80804    ** the index b-tree.  */
80805    endOfLoop = sqlite3VdbeMakeLabel(v);
80806    sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
80807    topOfLoop = sqlite3VdbeCurrentAddr(v);
80808    sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1);  /* Increment row counter */
80809
80810    for(i=0; i<nCol; i++){
80811      CollSeq *pColl;
80812      sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
80813      if( i==0 ){
80814        /* Always record the very first row */
80815        addrIfNot = sqlite3VdbeAddOp1(v, OP_IfNot, iMem+1);
80816      }
80817      assert( pIdx->azColl!=0 );
80818      assert( pIdx->azColl[i]!=0 );
80819      pColl = sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
80820      aChngAddr[i] = sqlite3VdbeAddOp4(v, OP_Ne, regCol, 0, iMem+nCol+i+1,
80821                                      (char*)pColl, P4_COLLSEQ);
80822      sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
80823      VdbeComment((v, "jump if column %d changed", i));
80824#ifdef SQLITE_ENABLE_STAT3
80825      if( i==0 ){
80826        sqlite3VdbeAddOp2(v, OP_AddImm, regNumEq, 1);
80827        VdbeComment((v, "incr repeat count"));
80828      }
80829#endif
80830    }
80831    sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
80832    for(i=0; i<nCol; i++){
80833      sqlite3VdbeJumpHere(v, aChngAddr[i]);  /* Set jump dest for the OP_Ne */
80834      if( i==0 ){
80835        sqlite3VdbeJumpHere(v, addrIfNot);   /* Jump dest for OP_IfNot */
80836#ifdef SQLITE_ENABLE_STAT3
80837        sqlite3VdbeAddOp4(v, OP_Function, 1, regNumEq, regTemp2,
80838                          (char*)&stat3PushFuncdef, P4_FUNCDEF);
80839        sqlite3VdbeChangeP5(v, 5);
80840        sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, pIdx->nColumn, regRowid);
80841        sqlite3VdbeAddOp3(v, OP_Add, regNumEq, regNumLt, regNumLt);
80842        sqlite3VdbeAddOp2(v, OP_AddImm, regNumDLt, 1);
80843        sqlite3VdbeAddOp2(v, OP_Integer, 1, regNumEq);
80844#endif
80845      }
80846      sqlite3VdbeAddOp2(v, OP_AddImm, iMem+i+1, 1);
80847      sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem+nCol+i+1);
80848    }
80849    sqlite3DbFree(db, aChngAddr);
80850
80851    /* Always jump here after updating the iMem+1...iMem+1+nCol counters */
80852    sqlite3VdbeResolveLabel(v, endOfLoop);
80853
80854    sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
80855    sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
80856#ifdef SQLITE_ENABLE_STAT3
80857    sqlite3VdbeAddOp4(v, OP_Function, 1, regNumEq, regTemp2,
80858                      (char*)&stat3PushFuncdef, P4_FUNCDEF);
80859    sqlite3VdbeChangeP5(v, 5);
80860    sqlite3VdbeAddOp2(v, OP_Integer, -1, regLoop);
80861    shortJump =
80862    sqlite3VdbeAddOp2(v, OP_AddImm, regLoop, 1);
80863    sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regTemp1,
80864                      (char*)&stat3GetFuncdef, P4_FUNCDEF);
80865    sqlite3VdbeChangeP5(v, 2);
80866    sqlite3VdbeAddOp1(v, OP_IsNull, regTemp1);
80867    sqlite3VdbeAddOp3(v, OP_NotExists, iTabCur, shortJump, regTemp1);
80868    sqlite3VdbeAddOp3(v, OP_Column, iTabCur, pIdx->aiColumn[0], regSample);
80869    sqlite3ColumnDefault(v, pTab, pIdx->aiColumn[0], regSample);
80870    sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumEq,
80871                      (char*)&stat3GetFuncdef, P4_FUNCDEF);
80872    sqlite3VdbeChangeP5(v, 3);
80873    sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumLt,
80874                      (char*)&stat3GetFuncdef, P4_FUNCDEF);
80875    sqlite3VdbeChangeP5(v, 4);
80876    sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumDLt,
80877                      (char*)&stat3GetFuncdef, P4_FUNCDEF);
80878    sqlite3VdbeChangeP5(v, 5);
80879    sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 6, regRec, "bbbbbb", 0);
80880    sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
80881    sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regRec, regNewRowid);
80882    sqlite3VdbeAddOp2(v, OP_Goto, 0, shortJump);
80883    sqlite3VdbeJumpHere(v, shortJump+2);
80884#endif
80885
80886    /* Store the results in sqlite_stat1.
80887    **
80888    ** The result is a single row of the sqlite_stat1 table.  The first
80889    ** two columns are the names of the table and index.  The third column
80890    ** is a string composed of a list of integer statistics about the
80891    ** index.  The first integer in the list is the total number of entries
80892    ** in the index.  There is one additional integer in the list for each
80893    ** column of the table.  This additional integer is a guess of how many
80894    ** rows of the table the index will select.  If D is the count of distinct
80895    ** values and K is the total number of rows, then the integer is computed
80896    ** as:
80897    **
80898    **        I = (K+D-1)/D
80899    **
80900    ** If K==0 then no entry is made into the sqlite_stat1 table.
80901    ** If K>0 then it is always the case the D>0 so division by zero
80902    ** is never possible.
80903    */
80904    sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regStat1);
80905    if( jZeroRows<0 ){
80906      jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
80907    }
80908    for(i=0; i<nCol; i++){
80909      sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
80910      sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regStat1, regStat1);
80911      sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
80912      sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
80913      sqlite3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp);
80914      sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);
80915      sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regStat1, regStat1);
80916    }
80917    sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
80918    sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
80919    sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regNewRowid);
80920    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
80921  }
80922
80923  /* If the table has no indices, create a single sqlite_stat1 entry
80924  ** containing NULL as the index name and the row count as the content.
80925  */
80926  if( pTab->pIndex==0 ){
80927    sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pTab->tnum, iDb);
80928    VdbeComment((v, "%s", pTab->zName));
80929    sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat1);
80930    sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
80931    jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1);
80932  }else{
80933    sqlite3VdbeJumpHere(v, jZeroRows);
80934    jZeroRows = sqlite3VdbeAddOp0(v, OP_Goto);
80935  }
80936  sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
80937  sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
80938  sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
80939  sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regNewRowid);
80940  sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
80941  if( pParse->nMem<regRec ) pParse->nMem = regRec;
80942  sqlite3VdbeJumpHere(v, jZeroRows);
80943}
80944
80945
80946/*
80947** Generate code that will cause the most recent index analysis to
80948** be loaded into internal hash tables where is can be used.
80949*/
80950static void loadAnalysis(Parse *pParse, int iDb){
80951  Vdbe *v = sqlite3GetVdbe(pParse);
80952  if( v ){
80953    sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
80954  }
80955}
80956
80957/*
80958** Generate code that will do an analysis of an entire database
80959*/
80960static void analyzeDatabase(Parse *pParse, int iDb){
80961  sqlite3 *db = pParse->db;
80962  Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
80963  HashElem *k;
80964  int iStatCur;
80965  int iMem;
80966
80967  sqlite3BeginWriteOperation(pParse, 0, iDb);
80968  iStatCur = pParse->nTab;
80969  pParse->nTab += 3;
80970  openStatTable(pParse, iDb, iStatCur, 0, 0);
80971  iMem = pParse->nMem+1;
80972  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
80973  for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
80974    Table *pTab = (Table*)sqliteHashData(k);
80975    analyzeOneTable(pParse, pTab, 0, iStatCur, iMem);
80976  }
80977  loadAnalysis(pParse, iDb);
80978}
80979
80980/*
80981** Generate code that will do an analysis of a single table in
80982** a database.  If pOnlyIdx is not NULL then it is a single index
80983** in pTab that should be analyzed.
80984*/
80985static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
80986  int iDb;
80987  int iStatCur;
80988
80989  assert( pTab!=0 );
80990  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
80991  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
80992  sqlite3BeginWriteOperation(pParse, 0, iDb);
80993  iStatCur = pParse->nTab;
80994  pParse->nTab += 3;
80995  if( pOnlyIdx ){
80996    openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
80997  }else{
80998    openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
80999  }
81000  analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur, pParse->nMem+1);
81001  loadAnalysis(pParse, iDb);
81002}
81003
81004/*
81005** Generate code for the ANALYZE command.  The parser calls this routine
81006** when it recognizes an ANALYZE command.
81007**
81008**        ANALYZE                            -- 1
81009**        ANALYZE  <database>                -- 2
81010**        ANALYZE  ?<database>.?<tablename>  -- 3
81011**
81012** Form 1 causes all indices in all attached databases to be analyzed.
81013** Form 2 analyzes all indices the single database named.
81014** Form 3 analyzes all indices associated with the named table.
81015*/
81016SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
81017  sqlite3 *db = pParse->db;
81018  int iDb;
81019  int i;
81020  char *z, *zDb;
81021  Table *pTab;
81022  Index *pIdx;
81023  Token *pTableName;
81024
81025  /* Read the database schema. If an error occurs, leave an error message
81026  ** and code in pParse and return NULL. */
81027  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
81028  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
81029    return;
81030  }
81031
81032  assert( pName2!=0 || pName1==0 );
81033  if( pName1==0 ){
81034    /* Form 1:  Analyze everything */
81035    for(i=0; i<db->nDb; i++){
81036      if( i==1 ) continue;  /* Do not analyze the TEMP database */
81037      analyzeDatabase(pParse, i);
81038    }
81039  }else if( pName2->n==0 ){
81040    /* Form 2:  Analyze the database or table named */
81041    iDb = sqlite3FindDb(db, pName1);
81042    if( iDb>=0 ){
81043      analyzeDatabase(pParse, iDb);
81044    }else{
81045      z = sqlite3NameFromToken(db, pName1);
81046      if( z ){
81047        if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
81048          analyzeTable(pParse, pIdx->pTable, pIdx);
81049        }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
81050          analyzeTable(pParse, pTab, 0);
81051        }
81052        sqlite3DbFree(db, z);
81053      }
81054    }
81055  }else{
81056    /* Form 3: Analyze the fully qualified table name */
81057    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
81058    if( iDb>=0 ){
81059      zDb = db->aDb[iDb].zName;
81060      z = sqlite3NameFromToken(db, pTableName);
81061      if( z ){
81062        if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
81063          analyzeTable(pParse, pIdx->pTable, pIdx);
81064        }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
81065          analyzeTable(pParse, pTab, 0);
81066        }
81067        sqlite3DbFree(db, z);
81068      }
81069    }
81070  }
81071}
81072
81073/*
81074** Used to pass information from the analyzer reader through to the
81075** callback routine.
81076*/
81077typedef struct analysisInfo analysisInfo;
81078struct analysisInfo {
81079  sqlite3 *db;
81080  const char *zDatabase;
81081};
81082
81083/*
81084** This callback is invoked once for each index when reading the
81085** sqlite_stat1 table.
81086**
81087**     argv[0] = name of the table
81088**     argv[1] = name of the index (might be NULL)
81089**     argv[2] = results of analysis - on integer for each column
81090**
81091** Entries for which argv[1]==NULL simply record the number of rows in
81092** the table.
81093*/
81094static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
81095  analysisInfo *pInfo = (analysisInfo*)pData;
81096  Index *pIndex;
81097  Table *pTable;
81098  int i, c, n;
81099  tRowcnt v;
81100  const char *z;
81101
81102  assert( argc==3 );
81103  UNUSED_PARAMETER2(NotUsed, argc);
81104
81105  if( argv==0 || argv[0]==0 || argv[2]==0 ){
81106    return 0;
81107  }
81108  pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
81109  if( pTable==0 ){
81110    return 0;
81111  }
81112  if( argv[1] ){
81113    pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
81114  }else{
81115    pIndex = 0;
81116  }
81117  n = pIndex ? pIndex->nColumn : 0;
81118  z = argv[2];
81119  for(i=0; *z && i<=n; i++){
81120    v = 0;
81121    while( (c=z[0])>='0' && c<='9' ){
81122      v = v*10 + c - '0';
81123      z++;
81124    }
81125    if( i==0 ) pTable->nRowEst = v;
81126    if( pIndex==0 ) break;
81127    pIndex->aiRowEst[i] = v;
81128    if( *z==' ' ) z++;
81129    if( strcmp(z, "unordered")==0 ){
81130      pIndex->bUnordered = 1;
81131      break;
81132    }
81133  }
81134  return 0;
81135}
81136
81137/*
81138** If the Index.aSample variable is not NULL, delete the aSample[] array
81139** and its contents.
81140*/
81141SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
81142#ifdef SQLITE_ENABLE_STAT3
81143  if( pIdx->aSample ){
81144    int j;
81145    for(j=0; j<pIdx->nSample; j++){
81146      IndexSample *p = &pIdx->aSample[j];
81147      if( p->eType==SQLITE_TEXT || p->eType==SQLITE_BLOB ){
81148        sqlite3DbFree(db, p->u.z);
81149      }
81150    }
81151    sqlite3DbFree(db, pIdx->aSample);
81152  }
81153  if( db && db->pnBytesFreed==0 ){
81154    pIdx->nSample = 0;
81155    pIdx->aSample = 0;
81156  }
81157#else
81158  UNUSED_PARAMETER(db);
81159  UNUSED_PARAMETER(pIdx);
81160#endif
81161}
81162
81163#ifdef SQLITE_ENABLE_STAT3
81164/*
81165** Load content from the sqlite_stat3 table into the Index.aSample[]
81166** arrays of all indices.
81167*/
81168static int loadStat3(sqlite3 *db, const char *zDb){
81169  int rc;                       /* Result codes from subroutines */
81170  sqlite3_stmt *pStmt = 0;      /* An SQL statement being run */
81171  char *zSql;                   /* Text of the SQL statement */
81172  Index *pPrevIdx = 0;          /* Previous index in the loop */
81173  int idx = 0;                  /* slot in pIdx->aSample[] for next sample */
81174  int eType;                    /* Datatype of a sample */
81175  IndexSample *pSample;         /* A slot in pIdx->aSample[] */
81176
81177  assert( db->lookaside.bEnabled==0 );
81178  if( !sqlite3FindTable(db, "sqlite_stat3", zDb) ){
81179    return SQLITE_OK;
81180  }
81181
81182  zSql = sqlite3MPrintf(db,
81183      "SELECT idx,count(*) FROM %Q.sqlite_stat3"
81184      " GROUP BY idx", zDb);
81185  if( !zSql ){
81186    return SQLITE_NOMEM;
81187  }
81188  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
81189  sqlite3DbFree(db, zSql);
81190  if( rc ) return rc;
81191
81192  while( sqlite3_step(pStmt)==SQLITE_ROW ){
81193    char *zIndex;   /* Index name */
81194    Index *pIdx;    /* Pointer to the index object */
81195    int nSample;    /* Number of samples */
81196
81197    zIndex = (char *)sqlite3_column_text(pStmt, 0);
81198    if( zIndex==0 ) continue;
81199    nSample = sqlite3_column_int(pStmt, 1);
81200    pIdx = sqlite3FindIndex(db, zIndex, zDb);
81201    if( pIdx==0 ) continue;
81202    assert( pIdx->nSample==0 );
81203    pIdx->nSample = nSample;
81204    pIdx->aSample = sqlite3DbMallocZero(db, nSample*sizeof(IndexSample));
81205    pIdx->avgEq = pIdx->aiRowEst[1];
81206    if( pIdx->aSample==0 ){
81207      db->mallocFailed = 1;
81208      sqlite3_finalize(pStmt);
81209      return SQLITE_NOMEM;
81210    }
81211  }
81212  rc = sqlite3_finalize(pStmt);
81213  if( rc ) return rc;
81214
81215  zSql = sqlite3MPrintf(db,
81216      "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat3", zDb);
81217  if( !zSql ){
81218    return SQLITE_NOMEM;
81219  }
81220  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
81221  sqlite3DbFree(db, zSql);
81222  if( rc ) return rc;
81223
81224  while( sqlite3_step(pStmt)==SQLITE_ROW ){
81225    char *zIndex;   /* Index name */
81226    Index *pIdx;    /* Pointer to the index object */
81227    int i;          /* Loop counter */
81228    tRowcnt sumEq;  /* Sum of the nEq values */
81229
81230    zIndex = (char *)sqlite3_column_text(pStmt, 0);
81231    if( zIndex==0 ) continue;
81232    pIdx = sqlite3FindIndex(db, zIndex, zDb);
81233    if( pIdx==0 ) continue;
81234    if( pIdx==pPrevIdx ){
81235      idx++;
81236    }else{
81237      pPrevIdx = pIdx;
81238      idx = 0;
81239    }
81240    assert( idx<pIdx->nSample );
81241    pSample = &pIdx->aSample[idx];
81242    pSample->nEq = (tRowcnt)sqlite3_column_int64(pStmt, 1);
81243    pSample->nLt = (tRowcnt)sqlite3_column_int64(pStmt, 2);
81244    pSample->nDLt = (tRowcnt)sqlite3_column_int64(pStmt, 3);
81245    if( idx==pIdx->nSample-1 ){
81246      if( pSample->nDLt>0 ){
81247        for(i=0, sumEq=0; i<=idx-1; i++) sumEq += pIdx->aSample[i].nEq;
81248        pIdx->avgEq = (pSample->nLt - sumEq)/pSample->nDLt;
81249      }
81250      if( pIdx->avgEq<=0 ) pIdx->avgEq = 1;
81251    }
81252    eType = sqlite3_column_type(pStmt, 4);
81253    pSample->eType = (u8)eType;
81254    switch( eType ){
81255      case SQLITE_INTEGER: {
81256        pSample->u.i = sqlite3_column_int64(pStmt, 4);
81257        break;
81258      }
81259      case SQLITE_FLOAT: {
81260        pSample->u.r = sqlite3_column_double(pStmt, 4);
81261        break;
81262      }
81263      case SQLITE_NULL: {
81264        break;
81265      }
81266      default: assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB ); {
81267        const char *z = (const char *)(
81268              (eType==SQLITE_BLOB) ?
81269              sqlite3_column_blob(pStmt, 4):
81270              sqlite3_column_text(pStmt, 4)
81271           );
81272        int n = z ? sqlite3_column_bytes(pStmt, 4) : 0;
81273        pSample->nByte = n;
81274        if( n < 1){
81275          pSample->u.z = 0;
81276        }else{
81277          pSample->u.z = sqlite3DbMallocRaw(db, n);
81278          if( pSample->u.z==0 ){
81279            db->mallocFailed = 1;
81280            sqlite3_finalize(pStmt);
81281            return SQLITE_NOMEM;
81282          }
81283          memcpy(pSample->u.z, z, n);
81284        }
81285      }
81286    }
81287  }
81288  return sqlite3_finalize(pStmt);
81289}
81290#endif /* SQLITE_ENABLE_STAT3 */
81291
81292/*
81293** Load the content of the sqlite_stat1 and sqlite_stat3 tables. The
81294** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
81295** arrays. The contents of sqlite_stat3 are used to populate the
81296** Index.aSample[] arrays.
81297**
81298** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
81299** is returned. In this case, even if SQLITE_ENABLE_STAT3 was defined
81300** during compilation and the sqlite_stat3 table is present, no data is
81301** read from it.
81302**
81303** If SQLITE_ENABLE_STAT3 was defined during compilation and the
81304** sqlite_stat3 table is not present in the database, SQLITE_ERROR is
81305** returned. However, in this case, data is read from the sqlite_stat1
81306** table (if it is present) before returning.
81307**
81308** If an OOM error occurs, this function always sets db->mallocFailed.
81309** This means if the caller does not care about other errors, the return
81310** code may be ignored.
81311*/
81312SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
81313  analysisInfo sInfo;
81314  HashElem *i;
81315  char *zSql;
81316  int rc;
81317
81318  assert( iDb>=0 && iDb<db->nDb );
81319  assert( db->aDb[iDb].pBt!=0 );
81320
81321  /* Clear any prior statistics */
81322  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
81323  for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
81324    Index *pIdx = sqliteHashData(i);
81325    sqlite3DefaultRowEst(pIdx);
81326#ifdef SQLITE_ENABLE_STAT3
81327    sqlite3DeleteIndexSamples(db, pIdx);
81328    pIdx->aSample = 0;
81329#endif
81330  }
81331
81332  /* Check to make sure the sqlite_stat1 table exists */
81333  sInfo.db = db;
81334  sInfo.zDatabase = db->aDb[iDb].zName;
81335  if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
81336    return SQLITE_ERROR;
81337  }
81338
81339  /* Load new statistics out of the sqlite_stat1 table */
81340  zSql = sqlite3MPrintf(db,
81341      "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
81342  if( zSql==0 ){
81343    rc = SQLITE_NOMEM;
81344  }else{
81345    rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
81346    sqlite3DbFree(db, zSql);
81347  }
81348
81349
81350  /* Load the statistics from the sqlite_stat3 table. */
81351#ifdef SQLITE_ENABLE_STAT3
81352  if( rc==SQLITE_OK ){
81353    int lookasideEnabled = db->lookaside.bEnabled;
81354    db->lookaside.bEnabled = 0;
81355    rc = loadStat3(db, sInfo.zDatabase);
81356    db->lookaside.bEnabled = lookasideEnabled;
81357  }
81358#endif
81359
81360  if( rc==SQLITE_NOMEM ){
81361    db->mallocFailed = 1;
81362  }
81363  return rc;
81364}
81365
81366
81367#endif /* SQLITE_OMIT_ANALYZE */
81368
81369/************** End of analyze.c *********************************************/
81370/************** Begin file attach.c ******************************************/
81371/*
81372** 2003 April 6
81373**
81374** The author disclaims copyright to this source code.  In place of
81375** a legal notice, here is a blessing:
81376**
81377**    May you do good and not evil.
81378**    May you find forgiveness for yourself and forgive others.
81379**    May you share freely, never taking more than you give.
81380**
81381*************************************************************************
81382** This file contains code used to implement the ATTACH and DETACH commands.
81383*/
81384
81385#ifndef SQLITE_OMIT_ATTACH
81386/*
81387** Resolve an expression that was part of an ATTACH or DETACH statement. This
81388** is slightly different from resolving a normal SQL expression, because simple
81389** identifiers are treated as strings, not possible column names or aliases.
81390**
81391** i.e. if the parser sees:
81392**
81393**     ATTACH DATABASE abc AS def
81394**
81395** it treats the two expressions as literal strings 'abc' and 'def' instead of
81396** looking for columns of the same name.
81397**
81398** This only applies to the root node of pExpr, so the statement:
81399**
81400**     ATTACH DATABASE abc||def AS 'db2'
81401**
81402** will fail because neither abc or def can be resolved.
81403*/
81404static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
81405{
81406  int rc = SQLITE_OK;
81407  if( pExpr ){
81408    if( pExpr->op!=TK_ID ){
81409      rc = sqlite3ResolveExprNames(pName, pExpr);
81410      if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
81411        sqlite3ErrorMsg(pName->pParse, "invalid name: \"%s\"", pExpr->u.zToken);
81412        return SQLITE_ERROR;
81413      }
81414    }else{
81415      pExpr->op = TK_STRING;
81416    }
81417  }
81418  return rc;
81419}
81420
81421/*
81422** An SQL user-function registered to do the work of an ATTACH statement. The
81423** three arguments to the function come directly from an attach statement:
81424**
81425**     ATTACH DATABASE x AS y KEY z
81426**
81427**     SELECT sqlite_attach(x, y, z)
81428**
81429** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
81430** third argument.
81431*/
81432static void attachFunc(
81433  sqlite3_context *context,
81434  int NotUsed,
81435  sqlite3_value **argv
81436){
81437  int i;
81438  int rc = 0;
81439  sqlite3 *db = sqlite3_context_db_handle(context);
81440  const char *zName;
81441  const char *zFile;
81442  char *zPath = 0;
81443  char *zErr = 0;
81444  unsigned int flags;
81445  Db *aNew;
81446  char *zErrDyn = 0;
81447  sqlite3_vfs *pVfs;
81448
81449  UNUSED_PARAMETER(NotUsed);
81450
81451  zFile = (const char *)sqlite3_value_text(argv[0]);
81452  zName = (const char *)sqlite3_value_text(argv[1]);
81453  if( zFile==0 ) zFile = "";
81454  if( zName==0 ) zName = "";
81455
81456  /* Check for the following errors:
81457  **
81458  **     * Too many attached databases,
81459  **     * Transaction currently open
81460  **     * Specified database name already being used.
81461  */
81462  if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
81463    zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
81464      db->aLimit[SQLITE_LIMIT_ATTACHED]
81465    );
81466    goto attach_error;
81467  }
81468  if( !db->autoCommit ){
81469    zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
81470    goto attach_error;
81471  }
81472  for(i=0; i<db->nDb; i++){
81473    char *z = db->aDb[i].zName;
81474    assert( z && zName );
81475    if( sqlite3StrICmp(z, zName)==0 ){
81476      zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
81477      goto attach_error;
81478    }
81479  }
81480
81481  /* Allocate the new entry in the db->aDb[] array and initialize the schema
81482  ** hash tables.
81483  */
81484  if( db->aDb==db->aDbStatic ){
81485    aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
81486    if( aNew==0 ) return;
81487    memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
81488  }else{
81489    aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
81490    if( aNew==0 ) return;
81491  }
81492  db->aDb = aNew;
81493  aNew = &db->aDb[db->nDb];
81494  memset(aNew, 0, sizeof(*aNew));
81495
81496  /* Open the database file. If the btree is successfully opened, use
81497  ** it to obtain the database schema. At this point the schema may
81498  ** or may not be initialized.
81499  */
81500  flags = db->openFlags;
81501  rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
81502  if( rc!=SQLITE_OK ){
81503    if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
81504    sqlite3_result_error(context, zErr, -1);
81505    sqlite3_free(zErr);
81506    return;
81507  }
81508  assert( pVfs );
81509  flags |= SQLITE_OPEN_MAIN_DB;
81510  rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);
81511  sqlite3_free( zPath );
81512  db->nDb++;
81513  if( rc==SQLITE_CONSTRAINT ){
81514    rc = SQLITE_ERROR;
81515    zErrDyn = sqlite3MPrintf(db, "database is already attached");
81516  }else if( rc==SQLITE_OK ){
81517    Pager *pPager;
81518    aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
81519    if( !aNew->pSchema ){
81520      rc = SQLITE_NOMEM;
81521    }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
81522      zErrDyn = sqlite3MPrintf(db,
81523        "attached databases must use the same text encoding as main database");
81524      rc = SQLITE_ERROR;
81525    }
81526    pPager = sqlite3BtreePager(aNew->pBt);
81527    sqlite3PagerLockingMode(pPager, db->dfltLockMode);
81528    sqlite3BtreeSecureDelete(aNew->pBt,
81529                             sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
81530  }
81531  aNew->safety_level = 3;
81532  aNew->zName = sqlite3DbStrDup(db, zName);
81533  if( rc==SQLITE_OK && aNew->zName==0 ){
81534    rc = SQLITE_NOMEM;
81535  }
81536
81537
81538#ifdef SQLITE_HAS_CODEC
81539  if( rc==SQLITE_OK ){
81540    extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
81541    extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
81542    int nKey;
81543    char *zKey;
81544    int t = sqlite3_value_type(argv[2]);
81545    switch( t ){
81546      case SQLITE_INTEGER:
81547      case SQLITE_FLOAT:
81548        zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
81549        rc = SQLITE_ERROR;
81550        break;
81551
81552      case SQLITE_TEXT:
81553      case SQLITE_BLOB:
81554        nKey = sqlite3_value_bytes(argv[2]);
81555        zKey = (char *)sqlite3_value_blob(argv[2]);
81556        rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
81557        break;
81558
81559      case SQLITE_NULL:
81560        /* No key specified.  Use the key from the main database */
81561        sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
81562        if( nKey>0 || sqlite3BtreeGetReserve(db->aDb[0].pBt)>0 ){
81563          rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
81564        }
81565        break;
81566    }
81567  }
81568#endif
81569
81570  /* If the file was opened successfully, read the schema for the new database.
81571  ** If this fails, or if opening the file failed, then close the file and
81572  ** remove the entry from the db->aDb[] array. i.e. put everything back the way
81573  ** we found it.
81574  */
81575  if( rc==SQLITE_OK ){
81576    sqlite3BtreeEnterAll(db);
81577    rc = sqlite3Init(db, &zErrDyn);
81578    sqlite3BtreeLeaveAll(db);
81579  }
81580  if( rc ){
81581    int iDb = db->nDb - 1;
81582    assert( iDb>=2 );
81583    if( db->aDb[iDb].pBt ){
81584      sqlite3BtreeClose(db->aDb[iDb].pBt);
81585      db->aDb[iDb].pBt = 0;
81586      db->aDb[iDb].pSchema = 0;
81587    }
81588    sqlite3ResetAllSchemasOfConnection(db);
81589    db->nDb = iDb;
81590    if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
81591      db->mallocFailed = 1;
81592      sqlite3DbFree(db, zErrDyn);
81593      zErrDyn = sqlite3MPrintf(db, "out of memory");
81594    }else if( zErrDyn==0 ){
81595      zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
81596    }
81597    goto attach_error;
81598  }
81599
81600  return;
81601
81602attach_error:
81603  /* Return an error if we get here */
81604  if( zErrDyn ){
81605    sqlite3_result_error(context, zErrDyn, -1);
81606    sqlite3DbFree(db, zErrDyn);
81607  }
81608  if( rc ) sqlite3_result_error_code(context, rc);
81609}
81610
81611/*
81612** An SQL user-function registered to do the work of an DETACH statement. The
81613** three arguments to the function come directly from a detach statement:
81614**
81615**     DETACH DATABASE x
81616**
81617**     SELECT sqlite_detach(x)
81618*/
81619static void detachFunc(
81620  sqlite3_context *context,
81621  int NotUsed,
81622  sqlite3_value **argv
81623){
81624  const char *zName = (const char *)sqlite3_value_text(argv[0]);
81625  sqlite3 *db = sqlite3_context_db_handle(context);
81626  int i;
81627  Db *pDb = 0;
81628  char zErr[128];
81629
81630  UNUSED_PARAMETER(NotUsed);
81631
81632  if( zName==0 ) zName = "";
81633  for(i=0; i<db->nDb; i++){
81634    pDb = &db->aDb[i];
81635    if( pDb->pBt==0 ) continue;
81636    if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
81637  }
81638
81639  if( i>=db->nDb ){
81640    sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
81641    goto detach_error;
81642  }
81643  if( i<2 ){
81644    sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
81645    goto detach_error;
81646  }
81647  if( !db->autoCommit ){
81648    sqlite3_snprintf(sizeof(zErr), zErr,
81649                     "cannot DETACH database within transaction");
81650    goto detach_error;
81651  }
81652  if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
81653    sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
81654    goto detach_error;
81655  }
81656
81657  sqlite3BtreeClose(pDb->pBt);
81658  pDb->pBt = 0;
81659  pDb->pSchema = 0;
81660  sqlite3ResetAllSchemasOfConnection(db);
81661  return;
81662
81663detach_error:
81664  sqlite3_result_error(context, zErr, -1);
81665}
81666
81667/*
81668** This procedure generates VDBE code for a single invocation of either the
81669** sqlite_detach() or sqlite_attach() SQL user functions.
81670*/
81671static void codeAttach(
81672  Parse *pParse,       /* The parser context */
81673  int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
81674  FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
81675  Expr *pAuthArg,      /* Expression to pass to authorization callback */
81676  Expr *pFilename,     /* Name of database file */
81677  Expr *pDbname,       /* Name of the database to use internally */
81678  Expr *pKey           /* Database key for encryption extension */
81679){
81680  int rc;
81681  NameContext sName;
81682  Vdbe *v;
81683  sqlite3* db = pParse->db;
81684  int regArgs;
81685
81686  memset(&sName, 0, sizeof(NameContext));
81687  sName.pParse = pParse;
81688
81689  if(
81690      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
81691      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
81692      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
81693  ){
81694    pParse->nErr++;
81695    goto attach_end;
81696  }
81697
81698#ifndef SQLITE_OMIT_AUTHORIZATION
81699  if( pAuthArg ){
81700    char *zAuthArg;
81701    if( pAuthArg->op==TK_STRING ){
81702      zAuthArg = pAuthArg->u.zToken;
81703    }else{
81704      zAuthArg = 0;
81705    }
81706    rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
81707    if(rc!=SQLITE_OK ){
81708      goto attach_end;
81709    }
81710  }
81711#endif /* SQLITE_OMIT_AUTHORIZATION */
81712
81713
81714  v = sqlite3GetVdbe(pParse);
81715  regArgs = sqlite3GetTempRange(pParse, 4);
81716  sqlite3ExprCode(pParse, pFilename, regArgs);
81717  sqlite3ExprCode(pParse, pDbname, regArgs+1);
81718  sqlite3ExprCode(pParse, pKey, regArgs+2);
81719
81720  assert( v || db->mallocFailed );
81721  if( v ){
81722    sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
81723    assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
81724    sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
81725    sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
81726
81727    /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
81728    ** statement only). For DETACH, set it to false (expire all existing
81729    ** statements).
81730    */
81731    sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
81732  }
81733
81734attach_end:
81735  sqlite3ExprDelete(db, pFilename);
81736  sqlite3ExprDelete(db, pDbname);
81737  sqlite3ExprDelete(db, pKey);
81738}
81739
81740/*
81741** Called by the parser to compile a DETACH statement.
81742**
81743**     DETACH pDbname
81744*/
81745SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
81746  static const FuncDef detach_func = {
81747    1,                /* nArg */
81748    SQLITE_UTF8,      /* iPrefEnc */
81749    0,                /* flags */
81750    0,                /* pUserData */
81751    0,                /* pNext */
81752    detachFunc,       /* xFunc */
81753    0,                /* xStep */
81754    0,                /* xFinalize */
81755    "sqlite_detach",  /* zName */
81756    0,                /* pHash */
81757    0                 /* pDestructor */
81758  };
81759  codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
81760}
81761
81762/*
81763** Called by the parser to compile an ATTACH statement.
81764**
81765**     ATTACH p AS pDbname KEY pKey
81766*/
81767SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
81768  static const FuncDef attach_func = {
81769    3,                /* nArg */
81770    SQLITE_UTF8,      /* iPrefEnc */
81771    0,                /* flags */
81772    0,                /* pUserData */
81773    0,                /* pNext */
81774    attachFunc,       /* xFunc */
81775    0,                /* xStep */
81776    0,                /* xFinalize */
81777    "sqlite_attach",  /* zName */
81778    0,                /* pHash */
81779    0                 /* pDestructor */
81780  };
81781  codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
81782}
81783#endif /* SQLITE_OMIT_ATTACH */
81784
81785/*
81786** Initialize a DbFixer structure.  This routine must be called prior
81787** to passing the structure to one of the sqliteFixAAAA() routines below.
81788**
81789** The return value indicates whether or not fixation is required.  TRUE
81790** means we do need to fix the database references, FALSE means we do not.
81791*/
81792SQLITE_PRIVATE int sqlite3FixInit(
81793  DbFixer *pFix,      /* The fixer to be initialized */
81794  Parse *pParse,      /* Error messages will be written here */
81795  int iDb,            /* This is the database that must be used */
81796  const char *zType,  /* "view", "trigger", or "index" */
81797  const Token *pName  /* Name of the view, trigger, or index */
81798){
81799  sqlite3 *db;
81800
81801  if( NEVER(iDb<0) || iDb==1 ) return 0;
81802  db = pParse->db;
81803  assert( db->nDb>iDb );
81804  pFix->pParse = pParse;
81805  pFix->zDb = db->aDb[iDb].zName;
81806  pFix->pSchema = db->aDb[iDb].pSchema;
81807  pFix->zType = zType;
81808  pFix->pName = pName;
81809  return 1;
81810}
81811
81812/*
81813** The following set of routines walk through the parse tree and assign
81814** a specific database to all table references where the database name
81815** was left unspecified in the original SQL statement.  The pFix structure
81816** must have been initialized by a prior call to sqlite3FixInit().
81817**
81818** These routines are used to make sure that an index, trigger, or
81819** view in one database does not refer to objects in a different database.
81820** (Exception: indices, triggers, and views in the TEMP database are
81821** allowed to refer to anything.)  If a reference is explicitly made
81822** to an object in a different database, an error message is added to
81823** pParse->zErrMsg and these routines return non-zero.  If everything
81824** checks out, these routines return 0.
81825*/
81826SQLITE_PRIVATE int sqlite3FixSrcList(
81827  DbFixer *pFix,       /* Context of the fixation */
81828  SrcList *pList       /* The Source list to check and modify */
81829){
81830  int i;
81831  const char *zDb;
81832  struct SrcList_item *pItem;
81833
81834  if( NEVER(pList==0) ) return 0;
81835  zDb = pFix->zDb;
81836  for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
81837    if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
81838      sqlite3ErrorMsg(pFix->pParse,
81839         "%s %T cannot reference objects in database %s",
81840         pFix->zType, pFix->pName, pItem->zDatabase);
81841      return 1;
81842    }
81843    sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
81844    pItem->zDatabase = 0;
81845    pItem->pSchema = pFix->pSchema;
81846#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
81847    if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
81848    if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
81849#endif
81850  }
81851  return 0;
81852}
81853#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
81854SQLITE_PRIVATE int sqlite3FixSelect(
81855  DbFixer *pFix,       /* Context of the fixation */
81856  Select *pSelect      /* The SELECT statement to be fixed to one database */
81857){
81858  while( pSelect ){
81859    if( sqlite3FixExprList(pFix, pSelect->pEList) ){
81860      return 1;
81861    }
81862    if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
81863      return 1;
81864    }
81865    if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
81866      return 1;
81867    }
81868    if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
81869      return 1;
81870    }
81871    pSelect = pSelect->pPrior;
81872  }
81873  return 0;
81874}
81875SQLITE_PRIVATE int sqlite3FixExpr(
81876  DbFixer *pFix,     /* Context of the fixation */
81877  Expr *pExpr        /* The expression to be fixed to one database */
81878){
81879  while( pExpr ){
81880    if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ) break;
81881    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
81882      if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
81883    }else{
81884      if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
81885    }
81886    if( sqlite3FixExpr(pFix, pExpr->pRight) ){
81887      return 1;
81888    }
81889    pExpr = pExpr->pLeft;
81890  }
81891  return 0;
81892}
81893SQLITE_PRIVATE int sqlite3FixExprList(
81894  DbFixer *pFix,     /* Context of the fixation */
81895  ExprList *pList    /* The expression to be fixed to one database */
81896){
81897  int i;
81898  struct ExprList_item *pItem;
81899  if( pList==0 ) return 0;
81900  for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
81901    if( sqlite3FixExpr(pFix, pItem->pExpr) ){
81902      return 1;
81903    }
81904  }
81905  return 0;
81906}
81907#endif
81908
81909#ifndef SQLITE_OMIT_TRIGGER
81910SQLITE_PRIVATE int sqlite3FixTriggerStep(
81911  DbFixer *pFix,     /* Context of the fixation */
81912  TriggerStep *pStep /* The trigger step be fixed to one database */
81913){
81914  while( pStep ){
81915    if( sqlite3FixSelect(pFix, pStep->pSelect) ){
81916      return 1;
81917    }
81918    if( sqlite3FixExpr(pFix, pStep->pWhere) ){
81919      return 1;
81920    }
81921    if( sqlite3FixExprList(pFix, pStep->pExprList) ){
81922      return 1;
81923    }
81924    pStep = pStep->pNext;
81925  }
81926  return 0;
81927}
81928#endif
81929
81930/************** End of attach.c **********************************************/
81931/************** Begin file auth.c ********************************************/
81932/*
81933** 2003 January 11
81934**
81935** The author disclaims copyright to this source code.  In place of
81936** a legal notice, here is a blessing:
81937**
81938**    May you do good and not evil.
81939**    May you find forgiveness for yourself and forgive others.
81940**    May you share freely, never taking more than you give.
81941**
81942*************************************************************************
81943** This file contains code used to implement the sqlite3_set_authorizer()
81944** API.  This facility is an optional feature of the library.  Embedded
81945** systems that do not need this facility may omit it by recompiling
81946** the library with -DSQLITE_OMIT_AUTHORIZATION=1
81947*/
81948
81949/*
81950** All of the code in this file may be omitted by defining a single
81951** macro.
81952*/
81953#ifndef SQLITE_OMIT_AUTHORIZATION
81954
81955/*
81956** Set or clear the access authorization function.
81957**
81958** The access authorization function is be called during the compilation
81959** phase to verify that the user has read and/or write access permission on
81960** various fields of the database.  The first argument to the auth function
81961** is a copy of the 3rd argument to this routine.  The second argument
81962** to the auth function is one of these constants:
81963**
81964**       SQLITE_CREATE_INDEX
81965**       SQLITE_CREATE_TABLE
81966**       SQLITE_CREATE_TEMP_INDEX
81967**       SQLITE_CREATE_TEMP_TABLE
81968**       SQLITE_CREATE_TEMP_TRIGGER
81969**       SQLITE_CREATE_TEMP_VIEW
81970**       SQLITE_CREATE_TRIGGER
81971**       SQLITE_CREATE_VIEW
81972**       SQLITE_DELETE
81973**       SQLITE_DROP_INDEX
81974**       SQLITE_DROP_TABLE
81975**       SQLITE_DROP_TEMP_INDEX
81976**       SQLITE_DROP_TEMP_TABLE
81977**       SQLITE_DROP_TEMP_TRIGGER
81978**       SQLITE_DROP_TEMP_VIEW
81979**       SQLITE_DROP_TRIGGER
81980**       SQLITE_DROP_VIEW
81981**       SQLITE_INSERT
81982**       SQLITE_PRAGMA
81983**       SQLITE_READ
81984**       SQLITE_SELECT
81985**       SQLITE_TRANSACTION
81986**       SQLITE_UPDATE
81987**
81988** The third and fourth arguments to the auth function are the name of
81989** the table and the column that are being accessed.  The auth function
81990** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
81991** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
81992** means that the SQL statement will never-run - the sqlite3_exec() call
81993** will return with an error.  SQLITE_IGNORE means that the SQL statement
81994** should run but attempts to read the specified column will return NULL
81995** and attempts to write the column will be ignored.
81996**
81997** Setting the auth function to NULL disables this hook.  The default
81998** setting of the auth function is NULL.
81999*/
82000SQLITE_API int sqlite3_set_authorizer(
82001  sqlite3 *db,
82002  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
82003  void *pArg
82004){
82005  sqlite3_mutex_enter(db->mutex);
82006  db->xAuth = xAuth;
82007  db->pAuthArg = pArg;
82008  sqlite3ExpirePreparedStatements(db);
82009  sqlite3_mutex_leave(db->mutex);
82010  return SQLITE_OK;
82011}
82012
82013/*
82014** Write an error message into pParse->zErrMsg that explains that the
82015** user-supplied authorization function returned an illegal value.
82016*/
82017static void sqliteAuthBadReturnCode(Parse *pParse){
82018  sqlite3ErrorMsg(pParse, "authorizer malfunction");
82019  pParse->rc = SQLITE_ERROR;
82020}
82021
82022/*
82023** Invoke the authorization callback for permission to read column zCol from
82024** table zTab in database zDb. This function assumes that an authorization
82025** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
82026**
82027** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
82028** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
82029** is treated as SQLITE_DENY. In this case an error is left in pParse.
82030*/
82031SQLITE_PRIVATE int sqlite3AuthReadCol(
82032  Parse *pParse,                  /* The parser context */
82033  const char *zTab,               /* Table name */
82034  const char *zCol,               /* Column name */
82035  int iDb                         /* Index of containing database. */
82036){
82037  sqlite3 *db = pParse->db;       /* Database handle */
82038  char *zDb = db->aDb[iDb].zName; /* Name of attached database */
82039  int rc;                         /* Auth callback return code */
82040
82041  rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext);
82042  if( rc==SQLITE_DENY ){
82043    if( db->nDb>2 || iDb!=0 ){
82044      sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
82045    }else{
82046      sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
82047    }
82048    pParse->rc = SQLITE_AUTH;
82049  }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
82050    sqliteAuthBadReturnCode(pParse);
82051  }
82052  return rc;
82053}
82054
82055/*
82056** The pExpr should be a TK_COLUMN expression.  The table referred to
82057** is in pTabList or else it is the NEW or OLD table of a trigger.
82058** Check to see if it is OK to read this particular column.
82059**
82060** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
82061** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
82062** then generate an error.
82063*/
82064SQLITE_PRIVATE void sqlite3AuthRead(
82065  Parse *pParse,        /* The parser context */
82066  Expr *pExpr,          /* The expression to check authorization on */
82067  Schema *pSchema,      /* The schema of the expression */
82068  SrcList *pTabList     /* All table that pExpr might refer to */
82069){
82070  sqlite3 *db = pParse->db;
82071  Table *pTab = 0;      /* The table being read */
82072  const char *zCol;     /* Name of the column of the table */
82073  int iSrc;             /* Index in pTabList->a[] of table being read */
82074  int iDb;              /* The index of the database the expression refers to */
82075  int iCol;             /* Index of column in table */
82076
82077  if( db->xAuth==0 ) return;
82078  iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
82079  if( iDb<0 ){
82080    /* An attempt to read a column out of a subquery or other
82081    ** temporary table. */
82082    return;
82083  }
82084
82085  assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
82086  if( pExpr->op==TK_TRIGGER ){
82087    pTab = pParse->pTriggerTab;
82088  }else{
82089    assert( pTabList );
82090    for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
82091      if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
82092        pTab = pTabList->a[iSrc].pTab;
82093        break;
82094      }
82095    }
82096  }
82097  iCol = pExpr->iColumn;
82098  if( NEVER(pTab==0) ) return;
82099
82100  if( iCol>=0 ){
82101    assert( iCol<pTab->nCol );
82102    zCol = pTab->aCol[iCol].zName;
82103  }else if( pTab->iPKey>=0 ){
82104    assert( pTab->iPKey<pTab->nCol );
82105    zCol = pTab->aCol[pTab->iPKey].zName;
82106  }else{
82107    zCol = "ROWID";
82108  }
82109  assert( iDb>=0 && iDb<db->nDb );
82110  if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
82111    pExpr->op = TK_NULL;
82112  }
82113}
82114
82115/*
82116** Do an authorization check using the code and arguments given.  Return
82117** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
82118** is returned, then the error count and error message in pParse are
82119** modified appropriately.
82120*/
82121SQLITE_PRIVATE int sqlite3AuthCheck(
82122  Parse *pParse,
82123  int code,
82124  const char *zArg1,
82125  const char *zArg2,
82126  const char *zArg3
82127){
82128  sqlite3 *db = pParse->db;
82129  int rc;
82130
82131  /* Don't do any authorization checks if the database is initialising
82132  ** or if the parser is being invoked from within sqlite3_declare_vtab.
82133  */
82134  if( db->init.busy || IN_DECLARE_VTAB ){
82135    return SQLITE_OK;
82136  }
82137
82138  if( db->xAuth==0 ){
82139    return SQLITE_OK;
82140  }
82141  rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
82142  if( rc==SQLITE_DENY ){
82143    sqlite3ErrorMsg(pParse, "not authorized");
82144    pParse->rc = SQLITE_AUTH;
82145  }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
82146    rc = SQLITE_DENY;
82147    sqliteAuthBadReturnCode(pParse);
82148  }
82149  return rc;
82150}
82151
82152/*
82153** Push an authorization context.  After this routine is called, the
82154** zArg3 argument to authorization callbacks will be zContext until
82155** popped.  Or if pParse==0, this routine is a no-op.
82156*/
82157SQLITE_PRIVATE void sqlite3AuthContextPush(
82158  Parse *pParse,
82159  AuthContext *pContext,
82160  const char *zContext
82161){
82162  assert( pParse );
82163  pContext->pParse = pParse;
82164  pContext->zAuthContext = pParse->zAuthContext;
82165  pParse->zAuthContext = zContext;
82166}
82167
82168/*
82169** Pop an authorization context that was previously pushed
82170** by sqlite3AuthContextPush
82171*/
82172SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
82173  if( pContext->pParse ){
82174    pContext->pParse->zAuthContext = pContext->zAuthContext;
82175    pContext->pParse = 0;
82176  }
82177}
82178
82179#endif /* SQLITE_OMIT_AUTHORIZATION */
82180
82181/************** End of auth.c ************************************************/
82182/************** Begin file build.c *******************************************/
82183/*
82184** 2001 September 15
82185**
82186** The author disclaims copyright to this source code.  In place of
82187** a legal notice, here is a blessing:
82188**
82189**    May you do good and not evil.
82190**    May you find forgiveness for yourself and forgive others.
82191**    May you share freely, never taking more than you give.
82192**
82193*************************************************************************
82194** This file contains C code routines that are called by the SQLite parser
82195** when syntax rules are reduced.  The routines in this file handle the
82196** following kinds of SQL syntax:
82197**
82198**     CREATE TABLE
82199**     DROP TABLE
82200**     CREATE INDEX
82201**     DROP INDEX
82202**     creating ID lists
82203**     BEGIN TRANSACTION
82204**     COMMIT
82205**     ROLLBACK
82206*/
82207
82208/*
82209** This routine is called when a new SQL statement is beginning to
82210** be parsed.  Initialize the pParse structure as needed.
82211*/
82212SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
82213  pParse->explain = (u8)explainFlag;
82214  pParse->nVar = 0;
82215}
82216
82217#ifndef SQLITE_OMIT_SHARED_CACHE
82218/*
82219** The TableLock structure is only used by the sqlite3TableLock() and
82220** codeTableLocks() functions.
82221*/
82222struct TableLock {
82223  int iDb;             /* The database containing the table to be locked */
82224  int iTab;            /* The root page of the table to be locked */
82225  u8 isWriteLock;      /* True for write lock.  False for a read lock */
82226  const char *zName;   /* Name of the table */
82227};
82228
82229/*
82230** Record the fact that we want to lock a table at run-time.
82231**
82232** The table to be locked has root page iTab and is found in database iDb.
82233** A read or a write lock can be taken depending on isWritelock.
82234**
82235** This routine just records the fact that the lock is desired.  The
82236** code to make the lock occur is generated by a later call to
82237** codeTableLocks() which occurs during sqlite3FinishCoding().
82238*/
82239SQLITE_PRIVATE void sqlite3TableLock(
82240  Parse *pParse,     /* Parsing context */
82241  int iDb,           /* Index of the database containing the table to lock */
82242  int iTab,          /* Root page number of the table to be locked */
82243  u8 isWriteLock,    /* True for a write lock */
82244  const char *zName  /* Name of the table to be locked */
82245){
82246  Parse *pToplevel = sqlite3ParseToplevel(pParse);
82247  int i;
82248  int nBytes;
82249  TableLock *p;
82250  assert( iDb>=0 );
82251
82252  for(i=0; i<pToplevel->nTableLock; i++){
82253    p = &pToplevel->aTableLock[i];
82254    if( p->iDb==iDb && p->iTab==iTab ){
82255      p->isWriteLock = (p->isWriteLock || isWriteLock);
82256      return;
82257    }
82258  }
82259
82260  nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
82261  pToplevel->aTableLock =
82262      sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
82263  if( pToplevel->aTableLock ){
82264    p = &pToplevel->aTableLock[pToplevel->nTableLock++];
82265    p->iDb = iDb;
82266    p->iTab = iTab;
82267    p->isWriteLock = isWriteLock;
82268    p->zName = zName;
82269  }else{
82270    pToplevel->nTableLock = 0;
82271    pToplevel->db->mallocFailed = 1;
82272  }
82273}
82274
82275/*
82276** Code an OP_TableLock instruction for each table locked by the
82277** statement (configured by calls to sqlite3TableLock()).
82278*/
82279static void codeTableLocks(Parse *pParse){
82280  int i;
82281  Vdbe *pVdbe;
82282
82283  pVdbe = sqlite3GetVdbe(pParse);
82284  assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
82285
82286  for(i=0; i<pParse->nTableLock; i++){
82287    TableLock *p = &pParse->aTableLock[i];
82288    int p1 = p->iDb;
82289    sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
82290                      p->zName, P4_STATIC);
82291  }
82292}
82293#else
82294  #define codeTableLocks(x)
82295#endif
82296
82297/*
82298** This routine is called after a single SQL statement has been
82299** parsed and a VDBE program to execute that statement has been
82300** prepared.  This routine puts the finishing touches on the
82301** VDBE program and resets the pParse structure for the next
82302** parse.
82303**
82304** Note that if an error occurred, it might be the case that
82305** no VDBE code was generated.
82306*/
82307SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
82308  sqlite3 *db;
82309  Vdbe *v;
82310
82311  assert( pParse->pToplevel==0 );
82312  db = pParse->db;
82313  if( db->mallocFailed ) return;
82314  if( pParse->nested ) return;
82315  if( pParse->nErr ) return;
82316
82317  /* Begin by generating some termination code at the end of the
82318  ** vdbe program
82319  */
82320  v = sqlite3GetVdbe(pParse);
82321  assert( !pParse->isMultiWrite
82322       || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
82323  if( v ){
82324    sqlite3VdbeAddOp0(v, OP_Halt);
82325
82326    /* The cookie mask contains one bit for each database file open.
82327    ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
82328    ** set for each database that is used.  Generate code to start a
82329    ** transaction on each used database and to verify the schema cookie
82330    ** on each used database.
82331    */
82332    if( pParse->cookieGoto>0 ){
82333      yDbMask mask;
82334      int iDb;
82335      sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
82336      for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
82337        if( (mask & pParse->cookieMask)==0 ) continue;
82338        sqlite3VdbeUsesBtree(v, iDb);
82339        sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
82340        if( db->init.busy==0 ){
82341          assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
82342          sqlite3VdbeAddOp3(v, OP_VerifyCookie,
82343                            iDb, pParse->cookieValue[iDb],
82344                            db->aDb[iDb].pSchema->iGeneration);
82345        }
82346      }
82347#ifndef SQLITE_OMIT_VIRTUALTABLE
82348      {
82349        int i;
82350        for(i=0; i<pParse->nVtabLock; i++){
82351          char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
82352          sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
82353        }
82354        pParse->nVtabLock = 0;
82355      }
82356#endif
82357
82358      /* Once all the cookies have been verified and transactions opened,
82359      ** obtain the required table-locks. This is a no-op unless the
82360      ** shared-cache feature is enabled.
82361      */
82362      codeTableLocks(pParse);
82363
82364      /* Initialize any AUTOINCREMENT data structures required.
82365      */
82366      sqlite3AutoincrementBegin(pParse);
82367
82368      /* Finally, jump back to the beginning of the executable code. */
82369      sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
82370    }
82371  }
82372
82373
82374  /* Get the VDBE program ready for execution
82375  */
82376  if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
82377#ifdef SQLITE_DEBUG
82378    FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
82379    sqlite3VdbeTrace(v, trace);
82380#endif
82381    assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
82382    /* A minimum of one cursor is required if autoincrement is used
82383    *  See ticket [a696379c1f08866] */
82384    if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
82385    sqlite3VdbeMakeReady(v, pParse);
82386    pParse->rc = SQLITE_DONE;
82387    pParse->colNamesSet = 0;
82388  }else{
82389    pParse->rc = SQLITE_ERROR;
82390  }
82391  pParse->nTab = 0;
82392  pParse->nMem = 0;
82393  pParse->nSet = 0;
82394  pParse->nVar = 0;
82395  pParse->cookieMask = 0;
82396  pParse->cookieGoto = 0;
82397}
82398
82399/*
82400** Run the parser and code generator recursively in order to generate
82401** code for the SQL statement given onto the end of the pParse context
82402** currently under construction.  When the parser is run recursively
82403** this way, the final OP_Halt is not appended and other initialization
82404** and finalization steps are omitted because those are handling by the
82405** outermost parser.
82406**
82407** Not everything is nestable.  This facility is designed to permit
82408** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
82409** care if you decide to try to use this routine for some other purposes.
82410*/
82411SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
82412  va_list ap;
82413  char *zSql;
82414  char *zErrMsg = 0;
82415  sqlite3 *db = pParse->db;
82416# define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
82417  char saveBuf[SAVE_SZ];
82418
82419  if( pParse->nErr ) return;
82420  assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
82421  va_start(ap, zFormat);
82422  zSql = sqlite3VMPrintf(db, zFormat, ap);
82423  va_end(ap);
82424  if( zSql==0 ){
82425    return;   /* A malloc must have failed */
82426  }
82427  pParse->nested++;
82428  memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
82429  memset(&pParse->nVar, 0, SAVE_SZ);
82430  sqlite3RunParser(pParse, zSql, &zErrMsg);
82431  sqlite3DbFree(db, zErrMsg);
82432  sqlite3DbFree(db, zSql);
82433  memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
82434  pParse->nested--;
82435}
82436
82437/*
82438** Locate the in-memory structure that describes a particular database
82439** table given the name of that table and (optionally) the name of the
82440** database containing the table.  Return NULL if not found.
82441**
82442** If zDatabase is 0, all databases are searched for the table and the
82443** first matching table is returned.  (No checking for duplicate table
82444** names is done.)  The search order is TEMP first, then MAIN, then any
82445** auxiliary databases added using the ATTACH command.
82446**
82447** See also sqlite3LocateTable().
82448*/
82449SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
82450  Table *p = 0;
82451  int i;
82452  int nName;
82453  assert( zName!=0 );
82454  nName = sqlite3Strlen30(zName);
82455  /* All mutexes are required for schema access.  Make sure we hold them. */
82456  assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
82457  for(i=OMIT_TEMPDB; i<db->nDb; i++){
82458    int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
82459    if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
82460    assert( sqlite3SchemaMutexHeld(db, j, 0) );
82461    p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
82462    if( p ) break;
82463  }
82464  return p;
82465}
82466
82467/*
82468** Locate the in-memory structure that describes a particular database
82469** table given the name of that table and (optionally) the name of the
82470** database containing the table.  Return NULL if not found.  Also leave an
82471** error message in pParse->zErrMsg.
82472**
82473** The difference between this routine and sqlite3FindTable() is that this
82474** routine leaves an error message in pParse->zErrMsg where
82475** sqlite3FindTable() does not.
82476*/
82477SQLITE_PRIVATE Table *sqlite3LocateTable(
82478  Parse *pParse,         /* context in which to report errors */
82479  int isView,            /* True if looking for a VIEW rather than a TABLE */
82480  const char *zName,     /* Name of the table we are looking for */
82481  const char *zDbase     /* Name of the database.  Might be NULL */
82482){
82483  Table *p;
82484
82485  /* Read the database schema. If an error occurs, leave an error message
82486  ** and code in pParse and return NULL. */
82487  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
82488    return 0;
82489  }
82490
82491  p = sqlite3FindTable(pParse->db, zName, zDbase);
82492  if( p==0 ){
82493    const char *zMsg = isView ? "no such view" : "no such table";
82494    if( zDbase ){
82495      sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
82496    }else{
82497      sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
82498    }
82499    pParse->checkSchema = 1;
82500  }
82501  return p;
82502}
82503
82504/*
82505** Locate the table identified by *p.
82506**
82507** This is a wrapper around sqlite3LocateTable(). The difference between
82508** sqlite3LocateTable() and this function is that this function restricts
82509** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
82510** non-NULL if it is part of a view or trigger program definition. See
82511** sqlite3FixSrcList() for details.
82512*/
82513SQLITE_PRIVATE Table *sqlite3LocateTableItem(
82514  Parse *pParse,
82515  int isView,
82516  struct SrcList_item *p
82517){
82518  const char *zDb;
82519  assert( p->pSchema==0 || p->zDatabase==0 );
82520  if( p->pSchema ){
82521    int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
82522    zDb = pParse->db->aDb[iDb].zName;
82523  }else{
82524    zDb = p->zDatabase;
82525  }
82526  return sqlite3LocateTable(pParse, isView, p->zName, zDb);
82527}
82528
82529/*
82530** Locate the in-memory structure that describes
82531** a particular index given the name of that index
82532** and the name of the database that contains the index.
82533** Return NULL if not found.
82534**
82535** If zDatabase is 0, all databases are searched for the
82536** table and the first matching index is returned.  (No checking
82537** for duplicate index names is done.)  The search order is
82538** TEMP first, then MAIN, then any auxiliary databases added
82539** using the ATTACH command.
82540*/
82541SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
82542  Index *p = 0;
82543  int i;
82544  int nName = sqlite3Strlen30(zName);
82545  /* All mutexes are required for schema access.  Make sure we hold them. */
82546  assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
82547  for(i=OMIT_TEMPDB; i<db->nDb; i++){
82548    int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
82549    Schema *pSchema = db->aDb[j].pSchema;
82550    assert( pSchema );
82551    if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
82552    assert( sqlite3SchemaMutexHeld(db, j, 0) );
82553    p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
82554    if( p ) break;
82555  }
82556  return p;
82557}
82558
82559/*
82560** Reclaim the memory used by an index
82561*/
82562static void freeIndex(sqlite3 *db, Index *p){
82563#ifndef SQLITE_OMIT_ANALYZE
82564  sqlite3DeleteIndexSamples(db, p);
82565#endif
82566  sqlite3DbFree(db, p->zColAff);
82567  sqlite3DbFree(db, p);
82568}
82569
82570/*
82571** For the index called zIdxName which is found in the database iDb,
82572** unlike that index from its Table then remove the index from
82573** the index hash table and free all memory structures associated
82574** with the index.
82575*/
82576SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
82577  Index *pIndex;
82578  int len;
82579  Hash *pHash;
82580
82581  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
82582  pHash = &db->aDb[iDb].pSchema->idxHash;
82583  len = sqlite3Strlen30(zIdxName);
82584  pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
82585  if( ALWAYS(pIndex) ){
82586    if( pIndex->pTable->pIndex==pIndex ){
82587      pIndex->pTable->pIndex = pIndex->pNext;
82588    }else{
82589      Index *p;
82590      /* Justification of ALWAYS();  The index must be on the list of
82591      ** indices. */
82592      p = pIndex->pTable->pIndex;
82593      while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
82594      if( ALWAYS(p && p->pNext==pIndex) ){
82595        p->pNext = pIndex->pNext;
82596      }
82597    }
82598    freeIndex(db, pIndex);
82599  }
82600  db->flags |= SQLITE_InternChanges;
82601}
82602
82603/*
82604** Look through the list of open database files in db->aDb[] and if
82605** any have been closed, remove them from the list.  Reallocate the
82606** db->aDb[] structure to a smaller size, if possible.
82607**
82608** Entry 0 (the "main" database) and entry 1 (the "temp" database)
82609** are never candidates for being collapsed.
82610*/
82611SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
82612  int i, j;
82613  for(i=j=2; i<db->nDb; i++){
82614    struct Db *pDb = &db->aDb[i];
82615    if( pDb->pBt==0 ){
82616      sqlite3DbFree(db, pDb->zName);
82617      pDb->zName = 0;
82618      continue;
82619    }
82620    if( j<i ){
82621      db->aDb[j] = db->aDb[i];
82622    }
82623    j++;
82624  }
82625  memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
82626  db->nDb = j;
82627  if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
82628    memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
82629    sqlite3DbFree(db, db->aDb);
82630    db->aDb = db->aDbStatic;
82631  }
82632}
82633
82634/*
82635** Reset the schema for the database at index iDb.  Also reset the
82636** TEMP schema.
82637*/
82638SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
82639  Db *pDb;
82640  assert( iDb<db->nDb );
82641
82642  /* Case 1:  Reset the single schema identified by iDb */
82643  pDb = &db->aDb[iDb];
82644  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
82645  assert( pDb->pSchema!=0 );
82646  sqlite3SchemaClear(pDb->pSchema);
82647
82648  /* If any database other than TEMP is reset, then also reset TEMP
82649  ** since TEMP might be holding triggers that reference tables in the
82650  ** other database.
82651  */
82652  if( iDb!=1 ){
82653    pDb = &db->aDb[1];
82654    assert( pDb->pSchema!=0 );
82655    sqlite3SchemaClear(pDb->pSchema);
82656  }
82657  return;
82658}
82659
82660/*
82661** Erase all schema information from all attached databases (including
82662** "main" and "temp") for a single database connection.
82663*/
82664SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
82665  int i;
82666  sqlite3BtreeEnterAll(db);
82667  for(i=0; i<db->nDb; i++){
82668    Db *pDb = &db->aDb[i];
82669    if( pDb->pSchema ){
82670      sqlite3SchemaClear(pDb->pSchema);
82671    }
82672  }
82673  db->flags &= ~SQLITE_InternChanges;
82674  sqlite3VtabUnlockList(db);
82675  sqlite3BtreeLeaveAll(db);
82676  sqlite3CollapseDatabaseArray(db);
82677}
82678
82679/*
82680** This routine is called when a commit occurs.
82681*/
82682SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
82683  db->flags &= ~SQLITE_InternChanges;
82684}
82685
82686/*
82687** Delete memory allocated for the column names of a table or view (the
82688** Table.aCol[] array).
82689*/
82690static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
82691  int i;
82692  Column *pCol;
82693  assert( pTable!=0 );
82694  if( (pCol = pTable->aCol)!=0 ){
82695    for(i=0; i<pTable->nCol; i++, pCol++){
82696      sqlite3DbFree(db, pCol->zName);
82697      sqlite3ExprDelete(db, pCol->pDflt);
82698      sqlite3DbFree(db, pCol->zDflt);
82699      sqlite3DbFree(db, pCol->zType);
82700      sqlite3DbFree(db, pCol->zColl);
82701    }
82702    sqlite3DbFree(db, pTable->aCol);
82703  }
82704}
82705
82706/*
82707** Remove the memory data structures associated with the given
82708** Table.  No changes are made to disk by this routine.
82709**
82710** This routine just deletes the data structure.  It does not unlink
82711** the table data structure from the hash table.  But it does destroy
82712** memory structures of the indices and foreign keys associated with
82713** the table.
82714**
82715** The db parameter is optional.  It is needed if the Table object
82716** contains lookaside memory.  (Table objects in the schema do not use
82717** lookaside memory, but some ephemeral Table objects do.)  Or the
82718** db parameter can be used with db->pnBytesFreed to measure the memory
82719** used by the Table object.
82720*/
82721SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
82722  Index *pIndex, *pNext;
82723  TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
82724
82725  assert( !pTable || pTable->nRef>0 );
82726
82727  /* Do not delete the table until the reference count reaches zero. */
82728  if( !pTable ) return;
82729  if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
82730
82731  /* Record the number of outstanding lookaside allocations in schema Tables
82732  ** prior to doing any free() operations.  Since schema Tables do not use
82733  ** lookaside, this number should not change. */
82734  TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
82735                         db->lookaside.nOut : 0 );
82736
82737  /* Delete all indices associated with this table. */
82738  for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
82739    pNext = pIndex->pNext;
82740    assert( pIndex->pSchema==pTable->pSchema );
82741    if( !db || db->pnBytesFreed==0 ){
82742      char *zName = pIndex->zName;
82743      TESTONLY ( Index *pOld = ) sqlite3HashInsert(
82744         &pIndex->pSchema->idxHash, zName, sqlite3Strlen30(zName), 0
82745      );
82746      assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
82747      assert( pOld==pIndex || pOld==0 );
82748    }
82749    freeIndex(db, pIndex);
82750  }
82751
82752  /* Delete any foreign keys attached to this table. */
82753  sqlite3FkDelete(db, pTable);
82754
82755  /* Delete the Table structure itself.
82756  */
82757  sqliteDeleteColumnNames(db, pTable);
82758  sqlite3DbFree(db, pTable->zName);
82759  sqlite3DbFree(db, pTable->zColAff);
82760  sqlite3SelectDelete(db, pTable->pSelect);
82761#ifndef SQLITE_OMIT_CHECK
82762  sqlite3ExprListDelete(db, pTable->pCheck);
82763#endif
82764#ifndef SQLITE_OMIT_VIRTUALTABLE
82765  sqlite3VtabClear(db, pTable);
82766#endif
82767  sqlite3DbFree(db, pTable);
82768
82769  /* Verify that no lookaside memory was used by schema tables */
82770  assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
82771}
82772
82773/*
82774** Unlink the given table from the hash tables and the delete the
82775** table structure with all its indices and foreign keys.
82776*/
82777SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
82778  Table *p;
82779  Db *pDb;
82780
82781  assert( db!=0 );
82782  assert( iDb>=0 && iDb<db->nDb );
82783  assert( zTabName );
82784  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
82785  testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
82786  pDb = &db->aDb[iDb];
82787  p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
82788                        sqlite3Strlen30(zTabName),0);
82789  sqlite3DeleteTable(db, p);
82790  db->flags |= SQLITE_InternChanges;
82791}
82792
82793/*
82794** Given a token, return a string that consists of the text of that
82795** token.  Space to hold the returned string
82796** is obtained from sqliteMalloc() and must be freed by the calling
82797** function.
82798**
82799** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
82800** surround the body of the token are removed.
82801**
82802** Tokens are often just pointers into the original SQL text and so
82803** are not \000 terminated and are not persistent.  The returned string
82804** is \000 terminated and is persistent.
82805*/
82806SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
82807  char *zName;
82808  if( pName ){
82809    zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
82810    sqlite3Dequote(zName);
82811  }else{
82812    zName = 0;
82813  }
82814  return zName;
82815}
82816
82817/*
82818** Open the sqlite_master table stored in database number iDb for
82819** writing. The table is opened using cursor 0.
82820*/
82821SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
82822  Vdbe *v = sqlite3GetVdbe(p);
82823  sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
82824  sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
82825  sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32);  /* 5 column table */
82826  if( p->nTab==0 ){
82827    p->nTab = 1;
82828  }
82829}
82830
82831/*
82832** Parameter zName points to a nul-terminated buffer containing the name
82833** of a database ("main", "temp" or the name of an attached db). This
82834** function returns the index of the named database in db->aDb[], or
82835** -1 if the named db cannot be found.
82836*/
82837SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
82838  int i = -1;         /* Database number */
82839  if( zName ){
82840    Db *pDb;
82841    int n = sqlite3Strlen30(zName);
82842    for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
82843      if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
82844          0==sqlite3StrICmp(pDb->zName, zName) ){
82845        break;
82846      }
82847    }
82848  }
82849  return i;
82850}
82851
82852/*
82853** The token *pName contains the name of a database (either "main" or
82854** "temp" or the name of an attached db). This routine returns the
82855** index of the named database in db->aDb[], or -1 if the named db
82856** does not exist.
82857*/
82858SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
82859  int i;                               /* Database number */
82860  char *zName;                         /* Name we are searching for */
82861  zName = sqlite3NameFromToken(db, pName);
82862  i = sqlite3FindDbName(db, zName);
82863  sqlite3DbFree(db, zName);
82864  return i;
82865}
82866
82867/* The table or view or trigger name is passed to this routine via tokens
82868** pName1 and pName2. If the table name was fully qualified, for example:
82869**
82870** CREATE TABLE xxx.yyy (...);
82871**
82872** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
82873** the table name is not fully qualified, i.e.:
82874**
82875** CREATE TABLE yyy(...);
82876**
82877** Then pName1 is set to "yyy" and pName2 is "".
82878**
82879** This routine sets the *ppUnqual pointer to point at the token (pName1 or
82880** pName2) that stores the unqualified table name.  The index of the
82881** database "xxx" is returned.
82882*/
82883SQLITE_PRIVATE int sqlite3TwoPartName(
82884  Parse *pParse,      /* Parsing and code generating context */
82885  Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
82886  Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
82887  Token **pUnqual     /* Write the unqualified object name here */
82888){
82889  int iDb;                    /* Database holding the object */
82890  sqlite3 *db = pParse->db;
82891
82892  if( ALWAYS(pName2!=0) && pName2->n>0 ){
82893    if( db->init.busy ) {
82894      sqlite3ErrorMsg(pParse, "corrupt database");
82895      pParse->nErr++;
82896      return -1;
82897    }
82898    *pUnqual = pName2;
82899    iDb = sqlite3FindDb(db, pName1);
82900    if( iDb<0 ){
82901      sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
82902      pParse->nErr++;
82903      return -1;
82904    }
82905  }else{
82906    assert( db->init.iDb==0 || db->init.busy );
82907    iDb = db->init.iDb;
82908    *pUnqual = pName1;
82909  }
82910  return iDb;
82911}
82912
82913/*
82914** This routine is used to check if the UTF-8 string zName is a legal
82915** unqualified name for a new schema object (table, index, view or
82916** trigger). All names are legal except those that begin with the string
82917** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
82918** is reserved for internal use.
82919*/
82920SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
82921  if( !pParse->db->init.busy && pParse->nested==0
82922          && (pParse->db->flags & SQLITE_WriteSchema)==0
82923          && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
82924    sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
82925    return SQLITE_ERROR;
82926  }
82927  return SQLITE_OK;
82928}
82929
82930/*
82931** Begin constructing a new table representation in memory.  This is
82932** the first of several action routines that get called in response
82933** to a CREATE TABLE statement.  In particular, this routine is called
82934** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
82935** flag is true if the table should be stored in the auxiliary database
82936** file instead of in the main database file.  This is normally the case
82937** when the "TEMP" or "TEMPORARY" keyword occurs in between
82938** CREATE and TABLE.
82939**
82940** The new table record is initialized and put in pParse->pNewTable.
82941** As more of the CREATE TABLE statement is parsed, additional action
82942** routines will be called to add more information to this record.
82943** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
82944** is called to complete the construction of the new table record.
82945*/
82946SQLITE_PRIVATE void sqlite3StartTable(
82947  Parse *pParse,   /* Parser context */
82948  Token *pName1,   /* First part of the name of the table or view */
82949  Token *pName2,   /* Second part of the name of the table or view */
82950  int isTemp,      /* True if this is a TEMP table */
82951  int isView,      /* True if this is a VIEW */
82952  int isVirtual,   /* True if this is a VIRTUAL table */
82953  int noErr        /* Do nothing if table already exists */
82954){
82955  Table *pTable;
82956  char *zName = 0; /* The name of the new table */
82957  sqlite3 *db = pParse->db;
82958  Vdbe *v;
82959  int iDb;         /* Database number to create the table in */
82960  Token *pName;    /* Unqualified name of the table to create */
82961
82962  /* The table or view name to create is passed to this routine via tokens
82963  ** pName1 and pName2. If the table name was fully qualified, for example:
82964  **
82965  ** CREATE TABLE xxx.yyy (...);
82966  **
82967  ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
82968  ** the table name is not fully qualified, i.e.:
82969  **
82970  ** CREATE TABLE yyy(...);
82971  **
82972  ** Then pName1 is set to "yyy" and pName2 is "".
82973  **
82974  ** The call below sets the pName pointer to point at the token (pName1 or
82975  ** pName2) that stores the unqualified table name. The variable iDb is
82976  ** set to the index of the database that the table or view is to be
82977  ** created in.
82978  */
82979  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
82980  if( iDb<0 ) return;
82981  if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
82982    /* If creating a temp table, the name may not be qualified. Unless
82983    ** the database name is "temp" anyway.  */
82984    sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
82985    return;
82986  }
82987  if( !OMIT_TEMPDB && isTemp ) iDb = 1;
82988
82989  pParse->sNameToken = *pName;
82990  zName = sqlite3NameFromToken(db, pName);
82991  if( zName==0 ) return;
82992  if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
82993    goto begin_table_error;
82994  }
82995  if( db->init.iDb==1 ) isTemp = 1;
82996#ifndef SQLITE_OMIT_AUTHORIZATION
82997  assert( (isTemp & 1)==isTemp );
82998  {
82999    int code;
83000    char *zDb = db->aDb[iDb].zName;
83001    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
83002      goto begin_table_error;
83003    }
83004    if( isView ){
83005      if( !OMIT_TEMPDB && isTemp ){
83006        code = SQLITE_CREATE_TEMP_VIEW;
83007      }else{
83008        code = SQLITE_CREATE_VIEW;
83009      }
83010    }else{
83011      if( !OMIT_TEMPDB && isTemp ){
83012        code = SQLITE_CREATE_TEMP_TABLE;
83013      }else{
83014        code = SQLITE_CREATE_TABLE;
83015      }
83016    }
83017    if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
83018      goto begin_table_error;
83019    }
83020  }
83021#endif
83022
83023  /* Make sure the new table name does not collide with an existing
83024  ** index or table name in the same database.  Issue an error message if
83025  ** it does. The exception is if the statement being parsed was passed
83026  ** to an sqlite3_declare_vtab() call. In that case only the column names
83027  ** and types will be used, so there is no need to test for namespace
83028  ** collisions.
83029  */
83030  if( !IN_DECLARE_VTAB ){
83031    char *zDb = db->aDb[iDb].zName;
83032    if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
83033      goto begin_table_error;
83034    }
83035    pTable = sqlite3FindTable(db, zName, zDb);
83036    if( pTable ){
83037      if( !noErr ){
83038        sqlite3ErrorMsg(pParse, "table %T already exists", pName);
83039      }else{
83040        assert( !db->init.busy );
83041        sqlite3CodeVerifySchema(pParse, iDb);
83042      }
83043      goto begin_table_error;
83044    }
83045    if( sqlite3FindIndex(db, zName, zDb)!=0 ){
83046      sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
83047      goto begin_table_error;
83048    }
83049  }
83050
83051  pTable = sqlite3DbMallocZero(db, sizeof(Table));
83052  if( pTable==0 ){
83053    db->mallocFailed = 1;
83054    pParse->rc = SQLITE_NOMEM;
83055    pParse->nErr++;
83056    goto begin_table_error;
83057  }
83058  pTable->zName = zName;
83059  pTable->iPKey = -1;
83060  pTable->pSchema = db->aDb[iDb].pSchema;
83061  pTable->nRef = 1;
83062  pTable->nRowEst = 1000000;
83063  assert( pParse->pNewTable==0 );
83064  pParse->pNewTable = pTable;
83065
83066  /* If this is the magic sqlite_sequence table used by autoincrement,
83067  ** then record a pointer to this table in the main database structure
83068  ** so that INSERT can find the table easily.
83069  */
83070#ifndef SQLITE_OMIT_AUTOINCREMENT
83071  if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
83072    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
83073    pTable->pSchema->pSeqTab = pTable;
83074  }
83075#endif
83076
83077  /* Begin generating the code that will insert the table record into
83078  ** the SQLITE_MASTER table.  Note in particular that we must go ahead
83079  ** and allocate the record number for the table entry now.  Before any
83080  ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
83081  ** indices to be created and the table record must come before the
83082  ** indices.  Hence, the record number for the table must be allocated
83083  ** now.
83084  */
83085  if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
83086    int j1;
83087    int fileFormat;
83088    int reg1, reg2, reg3;
83089    sqlite3BeginWriteOperation(pParse, 0, iDb);
83090
83091#ifndef SQLITE_OMIT_VIRTUALTABLE
83092    if( isVirtual ){
83093      sqlite3VdbeAddOp0(v, OP_VBegin);
83094    }
83095#endif
83096
83097    /* If the file format and encoding in the database have not been set,
83098    ** set them now.
83099    */
83100    reg1 = pParse->regRowid = ++pParse->nMem;
83101    reg2 = pParse->regRoot = ++pParse->nMem;
83102    reg3 = ++pParse->nMem;
83103    sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
83104    sqlite3VdbeUsesBtree(v, iDb);
83105    j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
83106    fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
83107                  1 : SQLITE_MAX_FILE_FORMAT;
83108    sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
83109    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
83110    sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
83111    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
83112    sqlite3VdbeJumpHere(v, j1);
83113
83114    /* This just creates a place-holder record in the sqlite_master table.
83115    ** The record created does not contain anything yet.  It will be replaced
83116    ** by the real entry in code generated at sqlite3EndTable().
83117    **
83118    ** The rowid for the new entry is left in register pParse->regRowid.
83119    ** The root page number of the new table is left in reg pParse->regRoot.
83120    ** The rowid and root page number values are needed by the code that
83121    ** sqlite3EndTable will generate.
83122    */
83123#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
83124    if( isView || isVirtual ){
83125      sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
83126    }else
83127#endif
83128    {
83129      sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
83130    }
83131    sqlite3OpenMasterTable(pParse, iDb);
83132    sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
83133    sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
83134    sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
83135    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
83136    sqlite3VdbeAddOp0(v, OP_Close);
83137  }
83138
83139  /* Normal (non-error) return. */
83140  return;
83141
83142  /* If an error occurs, we jump here */
83143begin_table_error:
83144  sqlite3DbFree(db, zName);
83145  return;
83146}
83147
83148/*
83149** This macro is used to compare two strings in a case-insensitive manner.
83150** It is slightly faster than calling sqlite3StrICmp() directly, but
83151** produces larger code.
83152**
83153** WARNING: This macro is not compatible with the strcmp() family. It
83154** returns true if the two strings are equal, otherwise false.
83155*/
83156#define STRICMP(x, y) (\
83157sqlite3UpperToLower[*(unsigned char *)(x)]==   \
83158sqlite3UpperToLower[*(unsigned char *)(y)]     \
83159&& sqlite3StrICmp((x)+1,(y)+1)==0 )
83160
83161/*
83162** Add a new column to the table currently being constructed.
83163**
83164** The parser calls this routine once for each column declaration
83165** in a CREATE TABLE statement.  sqlite3StartTable() gets called
83166** first to get things going.  Then this routine is called for each
83167** column.
83168*/
83169SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
83170  Table *p;
83171  int i;
83172  char *z;
83173  Column *pCol;
83174  sqlite3 *db = pParse->db;
83175  if( (p = pParse->pNewTable)==0 ) return;
83176#if SQLITE_MAX_COLUMN
83177  if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
83178    sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
83179    return;
83180  }
83181#endif
83182  z = sqlite3NameFromToken(db, pName);
83183  if( z==0 ) return;
83184  for(i=0; i<p->nCol; i++){
83185    if( STRICMP(z, p->aCol[i].zName) ){
83186      sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
83187      sqlite3DbFree(db, z);
83188      return;
83189    }
83190  }
83191  if( (p->nCol & 0x7)==0 ){
83192    Column *aNew;
83193    aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
83194    if( aNew==0 ){
83195      sqlite3DbFree(db, z);
83196      return;
83197    }
83198    p->aCol = aNew;
83199  }
83200  pCol = &p->aCol[p->nCol];
83201  memset(pCol, 0, sizeof(p->aCol[0]));
83202  pCol->zName = z;
83203
83204  /* If there is no type specified, columns have the default affinity
83205  ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
83206  ** be called next to set pCol->affinity correctly.
83207  */
83208  pCol->affinity = SQLITE_AFF_NONE;
83209  p->nCol++;
83210}
83211
83212/*
83213** This routine is called by the parser while in the middle of
83214** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
83215** been seen on a column.  This routine sets the notNull flag on
83216** the column currently under construction.
83217*/
83218SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
83219  Table *p;
83220  p = pParse->pNewTable;
83221  if( p==0 || NEVER(p->nCol<1) ) return;
83222  p->aCol[p->nCol-1].notNull = (u8)onError;
83223}
83224
83225/*
83226** Scan the column type name zType (length nType) and return the
83227** associated affinity type.
83228**
83229** This routine does a case-independent search of zType for the
83230** substrings in the following table. If one of the substrings is
83231** found, the corresponding affinity is returned. If zType contains
83232** more than one of the substrings, entries toward the top of
83233** the table take priority. For example, if zType is 'BLOBINT',
83234** SQLITE_AFF_INTEGER is returned.
83235**
83236** Substring     | Affinity
83237** --------------------------------
83238** 'INT'         | SQLITE_AFF_INTEGER
83239** 'CHAR'        | SQLITE_AFF_TEXT
83240** 'CLOB'        | SQLITE_AFF_TEXT
83241** 'TEXT'        | SQLITE_AFF_TEXT
83242** 'BLOB'        | SQLITE_AFF_NONE
83243** 'REAL'        | SQLITE_AFF_REAL
83244** 'FLOA'        | SQLITE_AFF_REAL
83245** 'DOUB'        | SQLITE_AFF_REAL
83246**
83247** If none of the substrings in the above table are found,
83248** SQLITE_AFF_NUMERIC is returned.
83249*/
83250SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn){
83251  u32 h = 0;
83252  char aff = SQLITE_AFF_NUMERIC;
83253
83254  if( zIn ) while( zIn[0] ){
83255    h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
83256    zIn++;
83257    if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
83258      aff = SQLITE_AFF_TEXT;
83259    }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
83260      aff = SQLITE_AFF_TEXT;
83261    }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
83262      aff = SQLITE_AFF_TEXT;
83263    }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
83264        && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
83265      aff = SQLITE_AFF_NONE;
83266#ifndef SQLITE_OMIT_FLOATING_POINT
83267    }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
83268        && aff==SQLITE_AFF_NUMERIC ){
83269      aff = SQLITE_AFF_REAL;
83270    }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
83271        && aff==SQLITE_AFF_NUMERIC ){
83272      aff = SQLITE_AFF_REAL;
83273    }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
83274        && aff==SQLITE_AFF_NUMERIC ){
83275      aff = SQLITE_AFF_REAL;
83276#endif
83277    }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
83278      aff = SQLITE_AFF_INTEGER;
83279      break;
83280    }
83281  }
83282
83283  return aff;
83284}
83285
83286/*
83287** This routine is called by the parser while in the middle of
83288** parsing a CREATE TABLE statement.  The pFirst token is the first
83289** token in the sequence of tokens that describe the type of the
83290** column currently under construction.   pLast is the last token
83291** in the sequence.  Use this information to construct a string
83292** that contains the typename of the column and store that string
83293** in zType.
83294*/
83295SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
83296  Table *p;
83297  Column *pCol;
83298
83299  p = pParse->pNewTable;
83300  if( p==0 || NEVER(p->nCol<1) ) return;
83301  pCol = &p->aCol[p->nCol-1];
83302  assert( pCol->zType==0 );
83303  pCol->zType = sqlite3NameFromToken(pParse->db, pType);
83304  pCol->affinity = sqlite3AffinityType(pCol->zType);
83305}
83306
83307/*
83308** The expression is the default value for the most recently added column
83309** of the table currently under construction.
83310**
83311** Default value expressions must be constant.  Raise an exception if this
83312** is not the case.
83313**
83314** This routine is called by the parser while in the middle of
83315** parsing a CREATE TABLE statement.
83316*/
83317SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
83318  Table *p;
83319  Column *pCol;
83320  sqlite3 *db = pParse->db;
83321  p = pParse->pNewTable;
83322  if( p!=0 ){
83323    pCol = &(p->aCol[p->nCol-1]);
83324    if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
83325      sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
83326          pCol->zName);
83327    }else{
83328      /* A copy of pExpr is used instead of the original, as pExpr contains
83329      ** tokens that point to volatile memory. The 'span' of the expression
83330      ** is required by pragma table_info.
83331      */
83332      sqlite3ExprDelete(db, pCol->pDflt);
83333      pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
83334      sqlite3DbFree(db, pCol->zDflt);
83335      pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
83336                                     (int)(pSpan->zEnd - pSpan->zStart));
83337    }
83338  }
83339  sqlite3ExprDelete(db, pSpan->pExpr);
83340}
83341
83342/*
83343** Designate the PRIMARY KEY for the table.  pList is a list of names
83344** of columns that form the primary key.  If pList is NULL, then the
83345** most recently added column of the table is the primary key.
83346**
83347** A table can have at most one primary key.  If the table already has
83348** a primary key (and this is the second primary key) then create an
83349** error.
83350**
83351** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
83352** then we will try to use that column as the rowid.  Set the Table.iPKey
83353** field of the table under construction to be the index of the
83354** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
83355** no INTEGER PRIMARY KEY.
83356**
83357** If the key is not an INTEGER PRIMARY KEY, then create a unique
83358** index for the key.  No index is created for INTEGER PRIMARY KEYs.
83359*/
83360SQLITE_PRIVATE void sqlite3AddPrimaryKey(
83361  Parse *pParse,    /* Parsing context */
83362  ExprList *pList,  /* List of field names to be indexed */
83363  int onError,      /* What to do with a uniqueness conflict */
83364  int autoInc,      /* True if the AUTOINCREMENT keyword is present */
83365  int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
83366){
83367  Table *pTab = pParse->pNewTable;
83368  char *zType = 0;
83369  int iCol = -1, i;
83370  if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
83371  if( pTab->tabFlags & TF_HasPrimaryKey ){
83372    sqlite3ErrorMsg(pParse,
83373      "table \"%s\" has more than one primary key", pTab->zName);
83374    goto primary_key_exit;
83375  }
83376  pTab->tabFlags |= TF_HasPrimaryKey;
83377  if( pList==0 ){
83378    iCol = pTab->nCol - 1;
83379    pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
83380  }else{
83381    for(i=0; i<pList->nExpr; i++){
83382      for(iCol=0; iCol<pTab->nCol; iCol++){
83383        if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
83384          break;
83385        }
83386      }
83387      if( iCol<pTab->nCol ){
83388        pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
83389      }
83390    }
83391    if( pList->nExpr>1 ) iCol = -1;
83392  }
83393  if( iCol>=0 && iCol<pTab->nCol ){
83394    zType = pTab->aCol[iCol].zType;
83395  }
83396  if( zType && sqlite3StrICmp(zType, "INTEGER")==0
83397        && sortOrder==SQLITE_SO_ASC ){
83398    pTab->iPKey = iCol;
83399    pTab->keyConf = (u8)onError;
83400    assert( autoInc==0 || autoInc==1 );
83401    pTab->tabFlags |= autoInc*TF_Autoincrement;
83402  }else if( autoInc ){
83403#ifndef SQLITE_OMIT_AUTOINCREMENT
83404    sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
83405       "INTEGER PRIMARY KEY");
83406#endif
83407  }else{
83408    Index *p;
83409    p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
83410    if( p ){
83411      p->autoIndex = 2;
83412    }
83413    pList = 0;
83414  }
83415
83416primary_key_exit:
83417  sqlite3ExprListDelete(pParse->db, pList);
83418  return;
83419}
83420
83421/*
83422** Add a new CHECK constraint to the table currently under construction.
83423*/
83424SQLITE_PRIVATE void sqlite3AddCheckConstraint(
83425  Parse *pParse,    /* Parsing context */
83426  Expr *pCheckExpr  /* The check expression */
83427){
83428#ifndef SQLITE_OMIT_CHECK
83429  Table *pTab = pParse->pNewTable;
83430  if( pTab && !IN_DECLARE_VTAB ){
83431    pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
83432    if( pParse->constraintName.n ){
83433      sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
83434    }
83435  }else
83436#endif
83437  {
83438    sqlite3ExprDelete(pParse->db, pCheckExpr);
83439  }
83440}
83441
83442/*
83443** Set the collation function of the most recently parsed table column
83444** to the CollSeq given.
83445*/
83446SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
83447  Table *p;
83448  int i;
83449  char *zColl;              /* Dequoted name of collation sequence */
83450  sqlite3 *db;
83451
83452  if( (p = pParse->pNewTable)==0 ) return;
83453  i = p->nCol-1;
83454  db = pParse->db;
83455  zColl = sqlite3NameFromToken(db, pToken);
83456  if( !zColl ) return;
83457
83458  if( sqlite3LocateCollSeq(pParse, zColl) ){
83459    Index *pIdx;
83460    p->aCol[i].zColl = zColl;
83461
83462    /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
83463    ** then an index may have been created on this column before the
83464    ** collation type was added. Correct this if it is the case.
83465    */
83466    for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
83467      assert( pIdx->nColumn==1 );
83468      if( pIdx->aiColumn[0]==i ){
83469        pIdx->azColl[0] = p->aCol[i].zColl;
83470      }
83471    }
83472  }else{
83473    sqlite3DbFree(db, zColl);
83474  }
83475}
83476
83477/*
83478** This function returns the collation sequence for database native text
83479** encoding identified by the string zName, length nName.
83480**
83481** If the requested collation sequence is not available, or not available
83482** in the database native encoding, the collation factory is invoked to
83483** request it. If the collation factory does not supply such a sequence,
83484** and the sequence is available in another text encoding, then that is
83485** returned instead.
83486**
83487** If no versions of the requested collations sequence are available, or
83488** another error occurs, NULL is returned and an error message written into
83489** pParse.
83490**
83491** This routine is a wrapper around sqlite3FindCollSeq().  This routine
83492** invokes the collation factory if the named collation cannot be found
83493** and generates an error message.
83494**
83495** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
83496*/
83497SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
83498  sqlite3 *db = pParse->db;
83499  u8 enc = ENC(db);
83500  u8 initbusy = db->init.busy;
83501  CollSeq *pColl;
83502
83503  pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
83504  if( !initbusy && (!pColl || !pColl->xCmp) ){
83505    pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
83506  }
83507
83508  return pColl;
83509}
83510
83511
83512/*
83513** Generate code that will increment the schema cookie.
83514**
83515** The schema cookie is used to determine when the schema for the
83516** database changes.  After each schema change, the cookie value
83517** changes.  When a process first reads the schema it records the
83518** cookie.  Thereafter, whenever it goes to access the database,
83519** it checks the cookie to make sure the schema has not changed
83520** since it was last read.
83521**
83522** This plan is not completely bullet-proof.  It is possible for
83523** the schema to change multiple times and for the cookie to be
83524** set back to prior value.  But schema changes are infrequent
83525** and the probability of hitting the same cookie value is only
83526** 1 chance in 2^32.  So we're safe enough.
83527*/
83528SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
83529  int r1 = sqlite3GetTempReg(pParse);
83530  sqlite3 *db = pParse->db;
83531  Vdbe *v = pParse->pVdbe;
83532  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
83533  sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
83534  sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
83535  sqlite3ReleaseTempReg(pParse, r1);
83536}
83537
83538/*
83539** Measure the number of characters needed to output the given
83540** identifier.  The number returned includes any quotes used
83541** but does not include the null terminator.
83542**
83543** The estimate is conservative.  It might be larger that what is
83544** really needed.
83545*/
83546static int identLength(const char *z){
83547  int n;
83548  for(n=0; *z; n++, z++){
83549    if( *z=='"' ){ n++; }
83550  }
83551  return n + 2;
83552}
83553
83554/*
83555** The first parameter is a pointer to an output buffer. The second
83556** parameter is a pointer to an integer that contains the offset at
83557** which to write into the output buffer. This function copies the
83558** nul-terminated string pointed to by the third parameter, zSignedIdent,
83559** to the specified offset in the buffer and updates *pIdx to refer
83560** to the first byte after the last byte written before returning.
83561**
83562** If the string zSignedIdent consists entirely of alpha-numeric
83563** characters, does not begin with a digit and is not an SQL keyword,
83564** then it is copied to the output buffer exactly as it is. Otherwise,
83565** it is quoted using double-quotes.
83566*/
83567static void identPut(char *z, int *pIdx, char *zSignedIdent){
83568  unsigned char *zIdent = (unsigned char*)zSignedIdent;
83569  int i, j, needQuote;
83570  i = *pIdx;
83571
83572  for(j=0; zIdent[j]; j++){
83573    if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
83574  }
83575  needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
83576  if( !needQuote ){
83577    needQuote = zIdent[j];
83578  }
83579
83580  if( needQuote ) z[i++] = '"';
83581  for(j=0; zIdent[j]; j++){
83582    z[i++] = zIdent[j];
83583    if( zIdent[j]=='"' ) z[i++] = '"';
83584  }
83585  if( needQuote ) z[i++] = '"';
83586  z[i] = 0;
83587  *pIdx = i;
83588}
83589
83590/*
83591** Generate a CREATE TABLE statement appropriate for the given
83592** table.  Memory to hold the text of the statement is obtained
83593** from sqliteMalloc() and must be freed by the calling function.
83594*/
83595static char *createTableStmt(sqlite3 *db, Table *p){
83596  int i, k, n;
83597  char *zStmt;
83598  char *zSep, *zSep2, *zEnd;
83599  Column *pCol;
83600  n = 0;
83601  for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
83602    n += identLength(pCol->zName) + 5;
83603  }
83604  n += identLength(p->zName);
83605  if( n<50 ){
83606    zSep = "";
83607    zSep2 = ",";
83608    zEnd = ")";
83609  }else{
83610    zSep = "\n  ";
83611    zSep2 = ",\n  ";
83612    zEnd = "\n)";
83613  }
83614  n += 35 + 6*p->nCol;
83615  zStmt = sqlite3DbMallocRaw(0, n);
83616  if( zStmt==0 ){
83617    db->mallocFailed = 1;
83618    return 0;
83619  }
83620  sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
83621  k = sqlite3Strlen30(zStmt);
83622  identPut(zStmt, &k, p->zName);
83623  zStmt[k++] = '(';
83624  for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
83625    static const char * const azType[] = {
83626        /* SQLITE_AFF_TEXT    */ " TEXT",
83627        /* SQLITE_AFF_NONE    */ "",
83628        /* SQLITE_AFF_NUMERIC */ " NUM",
83629        /* SQLITE_AFF_INTEGER */ " INT",
83630        /* SQLITE_AFF_REAL    */ " REAL"
83631    };
83632    int len;
83633    const char *zType;
83634
83635    sqlite3_snprintf(n-k, &zStmt[k], zSep);
83636    k += sqlite3Strlen30(&zStmt[k]);
83637    zSep = zSep2;
83638    identPut(zStmt, &k, pCol->zName);
83639    assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
83640    assert( pCol->affinity-SQLITE_AFF_TEXT < ArraySize(azType) );
83641    testcase( pCol->affinity==SQLITE_AFF_TEXT );
83642    testcase( pCol->affinity==SQLITE_AFF_NONE );
83643    testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
83644    testcase( pCol->affinity==SQLITE_AFF_INTEGER );
83645    testcase( pCol->affinity==SQLITE_AFF_REAL );
83646
83647    zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
83648    len = sqlite3Strlen30(zType);
83649    assert( pCol->affinity==SQLITE_AFF_NONE
83650            || pCol->affinity==sqlite3AffinityType(zType) );
83651    memcpy(&zStmt[k], zType, len);
83652    k += len;
83653    assert( k<=n );
83654  }
83655  sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
83656  return zStmt;
83657}
83658
83659/*
83660** This routine is called to report the final ")" that terminates
83661** a CREATE TABLE statement.
83662**
83663** The table structure that other action routines have been building
83664** is added to the internal hash tables, assuming no errors have
83665** occurred.
83666**
83667** An entry for the table is made in the master table on disk, unless
83668** this is a temporary table or db->init.busy==1.  When db->init.busy==1
83669** it means we are reading the sqlite_master table because we just
83670** connected to the database or because the sqlite_master table has
83671** recently changed, so the entry for this table already exists in
83672** the sqlite_master table.  We do not want to create it again.
83673**
83674** If the pSelect argument is not NULL, it means that this routine
83675** was called to create a table generated from a
83676** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
83677** the new table will match the result set of the SELECT.
83678*/
83679SQLITE_PRIVATE void sqlite3EndTable(
83680  Parse *pParse,          /* Parse context */
83681  Token *pCons,           /* The ',' token after the last column defn. */
83682  Token *pEnd,            /* The final ')' token in the CREATE TABLE */
83683  Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
83684){
83685  Table *p;
83686  sqlite3 *db = pParse->db;
83687  int iDb;
83688
83689  if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
83690    return;
83691  }
83692  p = pParse->pNewTable;
83693  if( p==0 ) return;
83694
83695  assert( !db->init.busy || !pSelect );
83696
83697  iDb = sqlite3SchemaToIndex(db, p->pSchema);
83698
83699#ifndef SQLITE_OMIT_CHECK
83700  /* Resolve names in all CHECK constraint expressions.
83701  */
83702  if( p->pCheck ){
83703    SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
83704    NameContext sNC;                /* Name context for pParse->pNewTable */
83705    ExprList *pList;                /* List of all CHECK constraints */
83706    int i;                          /* Loop counter */
83707
83708    memset(&sNC, 0, sizeof(sNC));
83709    memset(&sSrc, 0, sizeof(sSrc));
83710    sSrc.nSrc = 1;
83711    sSrc.a[0].zName = p->zName;
83712    sSrc.a[0].pTab = p;
83713    sSrc.a[0].iCursor = -1;
83714    sNC.pParse = pParse;
83715    sNC.pSrcList = &sSrc;
83716    sNC.ncFlags = NC_IsCheck;
83717    pList = p->pCheck;
83718    for(i=0; i<pList->nExpr; i++){
83719      if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
83720        return;
83721      }
83722    }
83723  }
83724#endif /* !defined(SQLITE_OMIT_CHECK) */
83725
83726  /* If the db->init.busy is 1 it means we are reading the SQL off the
83727  ** "sqlite_master" or "sqlite_temp_master" table on the disk.
83728  ** So do not write to the disk again.  Extract the root page number
83729  ** for the table from the db->init.newTnum field.  (The page number
83730  ** should have been put there by the sqliteOpenCb routine.)
83731  */
83732  if( db->init.busy ){
83733    p->tnum = db->init.newTnum;
83734  }
83735
83736  /* If not initializing, then create a record for the new table
83737  ** in the SQLITE_MASTER table of the database.
83738  **
83739  ** If this is a TEMPORARY table, write the entry into the auxiliary
83740  ** file instead of into the main database file.
83741  */
83742  if( !db->init.busy ){
83743    int n;
83744    Vdbe *v;
83745    char *zType;    /* "view" or "table" */
83746    char *zType2;   /* "VIEW" or "TABLE" */
83747    char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
83748
83749    v = sqlite3GetVdbe(pParse);
83750    if( NEVER(v==0) ) return;
83751
83752    sqlite3VdbeAddOp1(v, OP_Close, 0);
83753
83754    /*
83755    ** Initialize zType for the new view or table.
83756    */
83757    if( p->pSelect==0 ){
83758      /* A regular table */
83759      zType = "table";
83760      zType2 = "TABLE";
83761#ifndef SQLITE_OMIT_VIEW
83762    }else{
83763      /* A view */
83764      zType = "view";
83765      zType2 = "VIEW";
83766#endif
83767    }
83768
83769    /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
83770    ** statement to populate the new table. The root-page number for the
83771    ** new table is in register pParse->regRoot.
83772    **
83773    ** Once the SELECT has been coded by sqlite3Select(), it is in a
83774    ** suitable state to query for the column names and types to be used
83775    ** by the new table.
83776    **
83777    ** A shared-cache write-lock is not required to write to the new table,
83778    ** as a schema-lock must have already been obtained to create it. Since
83779    ** a schema-lock excludes all other database users, the write-lock would
83780    ** be redundant.
83781    */
83782    if( pSelect ){
83783      SelectDest dest;
83784      Table *pSelTab;
83785
83786      assert(pParse->nTab==1);
83787      sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
83788      sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
83789      pParse->nTab = 2;
83790      sqlite3SelectDestInit(&dest, SRT_Table, 1);
83791      sqlite3Select(pParse, pSelect, &dest);
83792      sqlite3VdbeAddOp1(v, OP_Close, 1);
83793      if( pParse->nErr==0 ){
83794        pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
83795        if( pSelTab==0 ) return;
83796        assert( p->aCol==0 );
83797        p->nCol = pSelTab->nCol;
83798        p->aCol = pSelTab->aCol;
83799        pSelTab->nCol = 0;
83800        pSelTab->aCol = 0;
83801        sqlite3DeleteTable(db, pSelTab);
83802      }
83803    }
83804
83805    /* Compute the complete text of the CREATE statement */
83806    if( pSelect ){
83807      zStmt = createTableStmt(db, p);
83808    }else{
83809      n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
83810      zStmt = sqlite3MPrintf(db,
83811          "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
83812      );
83813    }
83814
83815    /* A slot for the record has already been allocated in the
83816    ** SQLITE_MASTER table.  We just need to update that slot with all
83817    ** the information we've collected.
83818    */
83819    sqlite3NestedParse(pParse,
83820      "UPDATE %Q.%s "
83821         "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
83822       "WHERE rowid=#%d",
83823      db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
83824      zType,
83825      p->zName,
83826      p->zName,
83827      pParse->regRoot,
83828      zStmt,
83829      pParse->regRowid
83830    );
83831    sqlite3DbFree(db, zStmt);
83832    sqlite3ChangeCookie(pParse, iDb);
83833
83834#ifndef SQLITE_OMIT_AUTOINCREMENT
83835    /* Check to see if we need to create an sqlite_sequence table for
83836    ** keeping track of autoincrement keys.
83837    */
83838    if( p->tabFlags & TF_Autoincrement ){
83839      Db *pDb = &db->aDb[iDb];
83840      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
83841      if( pDb->pSchema->pSeqTab==0 ){
83842        sqlite3NestedParse(pParse,
83843          "CREATE TABLE %Q.sqlite_sequence(name,seq)",
83844          pDb->zName
83845        );
83846      }
83847    }
83848#endif
83849
83850    /* Reparse everything to update our internal data structures */
83851    sqlite3VdbeAddParseSchemaOp(v, iDb,
83852               sqlite3MPrintf(db, "tbl_name='%q'", p->zName));
83853  }
83854
83855
83856  /* Add the table to the in-memory representation of the database.
83857  */
83858  if( db->init.busy ){
83859    Table *pOld;
83860    Schema *pSchema = p->pSchema;
83861    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
83862    pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
83863                             sqlite3Strlen30(p->zName),p);
83864    if( pOld ){
83865      assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
83866      db->mallocFailed = 1;
83867      return;
83868    }
83869    pParse->pNewTable = 0;
83870    db->flags |= SQLITE_InternChanges;
83871
83872#ifndef SQLITE_OMIT_ALTERTABLE
83873    if( !p->pSelect ){
83874      const char *zName = (const char *)pParse->sNameToken.z;
83875      int nName;
83876      assert( !pSelect && pCons && pEnd );
83877      if( pCons->z==0 ){
83878        pCons = pEnd;
83879      }
83880      nName = (int)((const char *)pCons->z - zName);
83881      p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
83882    }
83883#endif
83884  }
83885}
83886
83887#ifndef SQLITE_OMIT_VIEW
83888/*
83889** The parser calls this routine in order to create a new VIEW
83890*/
83891SQLITE_PRIVATE void sqlite3CreateView(
83892  Parse *pParse,     /* The parsing context */
83893  Token *pBegin,     /* The CREATE token that begins the statement */
83894  Token *pName1,     /* The token that holds the name of the view */
83895  Token *pName2,     /* The token that holds the name of the view */
83896  Select *pSelect,   /* A SELECT statement that will become the new view */
83897  int isTemp,        /* TRUE for a TEMPORARY view */
83898  int noErr          /* Suppress error messages if VIEW already exists */
83899){
83900  Table *p;
83901  int n;
83902  const char *z;
83903  Token sEnd;
83904  DbFixer sFix;
83905  Token *pName = 0;
83906  int iDb;
83907  sqlite3 *db = pParse->db;
83908
83909  if( pParse->nVar>0 ){
83910    sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
83911    sqlite3SelectDelete(db, pSelect);
83912    return;
83913  }
83914  sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
83915  p = pParse->pNewTable;
83916  if( p==0 || pParse->nErr ){
83917    sqlite3SelectDelete(db, pSelect);
83918    return;
83919  }
83920  sqlite3TwoPartName(pParse, pName1, pName2, &pName);
83921  iDb = sqlite3SchemaToIndex(db, p->pSchema);
83922  if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
83923    && sqlite3FixSelect(&sFix, pSelect)
83924  ){
83925    sqlite3SelectDelete(db, pSelect);
83926    return;
83927  }
83928
83929  /* Make a copy of the entire SELECT statement that defines the view.
83930  ** This will force all the Expr.token.z values to be dynamically
83931  ** allocated rather than point to the input string - which means that
83932  ** they will persist after the current sqlite3_exec() call returns.
83933  */
83934  p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
83935  sqlite3SelectDelete(db, pSelect);
83936  if( db->mallocFailed ){
83937    return;
83938  }
83939  if( !db->init.busy ){
83940    sqlite3ViewGetColumnNames(pParse, p);
83941  }
83942
83943  /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
83944  ** the end.
83945  */
83946  sEnd = pParse->sLastToken;
83947  if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
83948    sEnd.z += sEnd.n;
83949  }
83950  sEnd.n = 0;
83951  n = (int)(sEnd.z - pBegin->z);
83952  z = pBegin->z;
83953  while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
83954  sEnd.z = &z[n-1];
83955  sEnd.n = 1;
83956
83957  /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
83958  sqlite3EndTable(pParse, 0, &sEnd, 0);
83959  return;
83960}
83961#endif /* SQLITE_OMIT_VIEW */
83962
83963#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
83964/*
83965** The Table structure pTable is really a VIEW.  Fill in the names of
83966** the columns of the view in the pTable structure.  Return the number
83967** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
83968*/
83969SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
83970  Table *pSelTab;   /* A fake table from which we get the result set */
83971  Select *pSel;     /* Copy of the SELECT that implements the view */
83972  int nErr = 0;     /* Number of errors encountered */
83973  int n;            /* Temporarily holds the number of cursors assigned */
83974  sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
83975  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
83976
83977  assert( pTable );
83978
83979#ifndef SQLITE_OMIT_VIRTUALTABLE
83980  if( sqlite3VtabCallConnect(pParse, pTable) ){
83981    return SQLITE_ERROR;
83982  }
83983  if( IsVirtual(pTable) ) return 0;
83984#endif
83985
83986#ifndef SQLITE_OMIT_VIEW
83987  /* A positive nCol means the columns names for this view are
83988  ** already known.
83989  */
83990  if( pTable->nCol>0 ) return 0;
83991
83992  /* A negative nCol is a special marker meaning that we are currently
83993  ** trying to compute the column names.  If we enter this routine with
83994  ** a negative nCol, it means two or more views form a loop, like this:
83995  **
83996  **     CREATE VIEW one AS SELECT * FROM two;
83997  **     CREATE VIEW two AS SELECT * FROM one;
83998  **
83999  ** Actually, the error above is now caught prior to reaching this point.
84000  ** But the following test is still important as it does come up
84001  ** in the following:
84002  **
84003  **     CREATE TABLE main.ex1(a);
84004  **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
84005  **     SELECT * FROM temp.ex1;
84006  */
84007  if( pTable->nCol<0 ){
84008    sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
84009    return 1;
84010  }
84011  assert( pTable->nCol>=0 );
84012
84013  /* If we get this far, it means we need to compute the table names.
84014  ** Note that the call to sqlite3ResultSetOfSelect() will expand any
84015  ** "*" elements in the results set of the view and will assign cursors
84016  ** to the elements of the FROM clause.  But we do not want these changes
84017  ** to be permanent.  So the computation is done on a copy of the SELECT
84018  ** statement that defines the view.
84019  */
84020  assert( pTable->pSelect );
84021  pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
84022  if( pSel ){
84023    u8 enableLookaside = db->lookaside.bEnabled;
84024    n = pParse->nTab;
84025    sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
84026    pTable->nCol = -1;
84027    db->lookaside.bEnabled = 0;
84028#ifndef SQLITE_OMIT_AUTHORIZATION
84029    xAuth = db->xAuth;
84030    db->xAuth = 0;
84031    pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
84032    db->xAuth = xAuth;
84033#else
84034    pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
84035#endif
84036    db->lookaside.bEnabled = enableLookaside;
84037    pParse->nTab = n;
84038    if( pSelTab ){
84039      assert( pTable->aCol==0 );
84040      pTable->nCol = pSelTab->nCol;
84041      pTable->aCol = pSelTab->aCol;
84042      pSelTab->nCol = 0;
84043      pSelTab->aCol = 0;
84044      sqlite3DeleteTable(db, pSelTab);
84045      assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
84046      pTable->pSchema->flags |= DB_UnresetViews;
84047    }else{
84048      pTable->nCol = 0;
84049      nErr++;
84050    }
84051    sqlite3SelectDelete(db, pSel);
84052  } else {
84053    nErr++;
84054  }
84055#endif /* SQLITE_OMIT_VIEW */
84056  return nErr;
84057}
84058#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
84059
84060#ifndef SQLITE_OMIT_VIEW
84061/*
84062** Clear the column names from every VIEW in database idx.
84063*/
84064static void sqliteViewResetAll(sqlite3 *db, int idx){
84065  HashElem *i;
84066  assert( sqlite3SchemaMutexHeld(db, idx, 0) );
84067  if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
84068  for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
84069    Table *pTab = sqliteHashData(i);
84070    if( pTab->pSelect ){
84071      sqliteDeleteColumnNames(db, pTab);
84072      pTab->aCol = 0;
84073      pTab->nCol = 0;
84074    }
84075  }
84076  DbClearProperty(db, idx, DB_UnresetViews);
84077}
84078#else
84079# define sqliteViewResetAll(A,B)
84080#endif /* SQLITE_OMIT_VIEW */
84081
84082/*
84083** This function is called by the VDBE to adjust the internal schema
84084** used by SQLite when the btree layer moves a table root page. The
84085** root-page of a table or index in database iDb has changed from iFrom
84086** to iTo.
84087**
84088** Ticket #1728:  The symbol table might still contain information
84089** on tables and/or indices that are the process of being deleted.
84090** If you are unlucky, one of those deleted indices or tables might
84091** have the same rootpage number as the real table or index that is
84092** being moved.  So we cannot stop searching after the first match
84093** because the first match might be for one of the deleted indices
84094** or tables and not the table/index that is actually being moved.
84095** We must continue looping until all tables and indices with
84096** rootpage==iFrom have been converted to have a rootpage of iTo
84097** in order to be certain that we got the right one.
84098*/
84099#ifndef SQLITE_OMIT_AUTOVACUUM
84100SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
84101  HashElem *pElem;
84102  Hash *pHash;
84103  Db *pDb;
84104
84105  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
84106  pDb = &db->aDb[iDb];
84107  pHash = &pDb->pSchema->tblHash;
84108  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
84109    Table *pTab = sqliteHashData(pElem);
84110    if( pTab->tnum==iFrom ){
84111      pTab->tnum = iTo;
84112    }
84113  }
84114  pHash = &pDb->pSchema->idxHash;
84115  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
84116    Index *pIdx = sqliteHashData(pElem);
84117    if( pIdx->tnum==iFrom ){
84118      pIdx->tnum = iTo;
84119    }
84120  }
84121}
84122#endif
84123
84124/*
84125** Write code to erase the table with root-page iTable from database iDb.
84126** Also write code to modify the sqlite_master table and internal schema
84127** if a root-page of another table is moved by the btree-layer whilst
84128** erasing iTable (this can happen with an auto-vacuum database).
84129*/
84130static void destroyRootPage(Parse *pParse, int iTable, int iDb){
84131  Vdbe *v = sqlite3GetVdbe(pParse);
84132  int r1 = sqlite3GetTempReg(pParse);
84133  sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
84134  sqlite3MayAbort(pParse);
84135#ifndef SQLITE_OMIT_AUTOVACUUM
84136  /* OP_Destroy stores an in integer r1. If this integer
84137  ** is non-zero, then it is the root page number of a table moved to
84138  ** location iTable. The following code modifies the sqlite_master table to
84139  ** reflect this.
84140  **
84141  ** The "#NNN" in the SQL is a special constant that means whatever value
84142  ** is in register NNN.  See grammar rules associated with the TK_REGISTER
84143  ** token for additional information.
84144  */
84145  sqlite3NestedParse(pParse,
84146     "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
84147     pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
84148#endif
84149  sqlite3ReleaseTempReg(pParse, r1);
84150}
84151
84152/*
84153** Write VDBE code to erase table pTab and all associated indices on disk.
84154** Code to update the sqlite_master tables and internal schema definitions
84155** in case a root-page belonging to another table is moved by the btree layer
84156** is also added (this can happen with an auto-vacuum database).
84157*/
84158static void destroyTable(Parse *pParse, Table *pTab){
84159#ifdef SQLITE_OMIT_AUTOVACUUM
84160  Index *pIdx;
84161  int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
84162  destroyRootPage(pParse, pTab->tnum, iDb);
84163  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
84164    destroyRootPage(pParse, pIdx->tnum, iDb);
84165  }
84166#else
84167  /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
84168  ** is not defined), then it is important to call OP_Destroy on the
84169  ** table and index root-pages in order, starting with the numerically
84170  ** largest root-page number. This guarantees that none of the root-pages
84171  ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
84172  ** following were coded:
84173  **
84174  ** OP_Destroy 4 0
84175  ** ...
84176  ** OP_Destroy 5 0
84177  **
84178  ** and root page 5 happened to be the largest root-page number in the
84179  ** database, then root page 5 would be moved to page 4 by the
84180  ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
84181  ** a free-list page.
84182  */
84183  int iTab = pTab->tnum;
84184  int iDestroyed = 0;
84185
84186  while( 1 ){
84187    Index *pIdx;
84188    int iLargest = 0;
84189
84190    if( iDestroyed==0 || iTab<iDestroyed ){
84191      iLargest = iTab;
84192    }
84193    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
84194      int iIdx = pIdx->tnum;
84195      assert( pIdx->pSchema==pTab->pSchema );
84196      if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
84197        iLargest = iIdx;
84198      }
84199    }
84200    if( iLargest==0 ){
84201      return;
84202    }else{
84203      int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
84204      assert( iDb>=0 && iDb<pParse->db->nDb );
84205      destroyRootPage(pParse, iLargest, iDb);
84206      iDestroyed = iLargest;
84207    }
84208  }
84209#endif
84210}
84211
84212/*
84213** Remove entries from the sqlite_statN tables (for N in (1,2,3))
84214** after a DROP INDEX or DROP TABLE command.
84215*/
84216static void sqlite3ClearStatTables(
84217  Parse *pParse,         /* The parsing context */
84218  int iDb,               /* The database number */
84219  const char *zType,     /* "idx" or "tbl" */
84220  const char *zName      /* Name of index or table */
84221){
84222  int i;
84223  const char *zDbName = pParse->db->aDb[iDb].zName;
84224  for(i=1; i<=3; i++){
84225    char zTab[24];
84226    sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
84227    if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
84228      sqlite3NestedParse(pParse,
84229        "DELETE FROM %Q.%s WHERE %s=%Q",
84230        zDbName, zTab, zType, zName
84231      );
84232    }
84233  }
84234}
84235
84236/*
84237** Generate code to drop a table.
84238*/
84239SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
84240  Vdbe *v;
84241  sqlite3 *db = pParse->db;
84242  Trigger *pTrigger;
84243  Db *pDb = &db->aDb[iDb];
84244
84245  v = sqlite3GetVdbe(pParse);
84246  assert( v!=0 );
84247  sqlite3BeginWriteOperation(pParse, 1, iDb);
84248
84249#ifndef SQLITE_OMIT_VIRTUALTABLE
84250  if( IsVirtual(pTab) ){
84251    sqlite3VdbeAddOp0(v, OP_VBegin);
84252  }
84253#endif
84254
84255  /* Drop all triggers associated with the table being dropped. Code
84256  ** is generated to remove entries from sqlite_master and/or
84257  ** sqlite_temp_master if required.
84258  */
84259  pTrigger = sqlite3TriggerList(pParse, pTab);
84260  while( pTrigger ){
84261    assert( pTrigger->pSchema==pTab->pSchema ||
84262        pTrigger->pSchema==db->aDb[1].pSchema );
84263    sqlite3DropTriggerPtr(pParse, pTrigger);
84264    pTrigger = pTrigger->pNext;
84265  }
84266
84267#ifndef SQLITE_OMIT_AUTOINCREMENT
84268  /* Remove any entries of the sqlite_sequence table associated with
84269  ** the table being dropped. This is done before the table is dropped
84270  ** at the btree level, in case the sqlite_sequence table needs to
84271  ** move as a result of the drop (can happen in auto-vacuum mode).
84272  */
84273  if( pTab->tabFlags & TF_Autoincrement ){
84274    sqlite3NestedParse(pParse,
84275      "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
84276      pDb->zName, pTab->zName
84277    );
84278  }
84279#endif
84280
84281  /* Drop all SQLITE_MASTER table and index entries that refer to the
84282  ** table. The program name loops through the master table and deletes
84283  ** every row that refers to a table of the same name as the one being
84284  ** dropped. Triggers are handled separately because a trigger can be
84285  ** created in the temp database that refers to a table in another
84286  ** database.
84287  */
84288  sqlite3NestedParse(pParse,
84289      "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
84290      pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
84291  if( !isView && !IsVirtual(pTab) ){
84292    destroyTable(pParse, pTab);
84293  }
84294
84295  /* Remove the table entry from SQLite's internal schema and modify
84296  ** the schema cookie.
84297  */
84298  if( IsVirtual(pTab) ){
84299    sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
84300  }
84301  sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
84302  sqlite3ChangeCookie(pParse, iDb);
84303  sqliteViewResetAll(db, iDb);
84304}
84305
84306/*
84307** This routine is called to do the work of a DROP TABLE statement.
84308** pName is the name of the table to be dropped.
84309*/
84310SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
84311  Table *pTab;
84312  Vdbe *v;
84313  sqlite3 *db = pParse->db;
84314  int iDb;
84315
84316  if( db->mallocFailed ){
84317    goto exit_drop_table;
84318  }
84319  assert( pParse->nErr==0 );
84320  assert( pName->nSrc==1 );
84321  if( noErr ) db->suppressErr++;
84322  pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
84323  if( noErr ) db->suppressErr--;
84324
84325  if( pTab==0 ){
84326    if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
84327    goto exit_drop_table;
84328  }
84329  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
84330  assert( iDb>=0 && iDb<db->nDb );
84331
84332  /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
84333  ** it is initialized.
84334  */
84335  if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
84336    goto exit_drop_table;
84337  }
84338#ifndef SQLITE_OMIT_AUTHORIZATION
84339  {
84340    int code;
84341    const char *zTab = SCHEMA_TABLE(iDb);
84342    const char *zDb = db->aDb[iDb].zName;
84343    const char *zArg2 = 0;
84344    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
84345      goto exit_drop_table;
84346    }
84347    if( isView ){
84348      if( !OMIT_TEMPDB && iDb==1 ){
84349        code = SQLITE_DROP_TEMP_VIEW;
84350      }else{
84351        code = SQLITE_DROP_VIEW;
84352      }
84353#ifndef SQLITE_OMIT_VIRTUALTABLE
84354    }else if( IsVirtual(pTab) ){
84355      code = SQLITE_DROP_VTABLE;
84356      zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
84357#endif
84358    }else{
84359      if( !OMIT_TEMPDB && iDb==1 ){
84360        code = SQLITE_DROP_TEMP_TABLE;
84361      }else{
84362        code = SQLITE_DROP_TABLE;
84363      }
84364    }
84365    if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
84366      goto exit_drop_table;
84367    }
84368    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
84369      goto exit_drop_table;
84370    }
84371  }
84372#endif
84373  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
84374    && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
84375    sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
84376    goto exit_drop_table;
84377  }
84378
84379#ifndef SQLITE_OMIT_VIEW
84380  /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
84381  ** on a table.
84382  */
84383  if( isView && pTab->pSelect==0 ){
84384    sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
84385    goto exit_drop_table;
84386  }
84387  if( !isView && pTab->pSelect ){
84388    sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
84389    goto exit_drop_table;
84390  }
84391#endif
84392
84393  /* Generate code to remove the table from the master table
84394  ** on disk.
84395  */
84396  v = sqlite3GetVdbe(pParse);
84397  if( v ){
84398    sqlite3BeginWriteOperation(pParse, 1, iDb);
84399    sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
84400    sqlite3FkDropTable(pParse, pName, pTab);
84401    sqlite3CodeDropTable(pParse, pTab, iDb, isView);
84402  }
84403
84404exit_drop_table:
84405  sqlite3SrcListDelete(db, pName);
84406}
84407
84408/*
84409** This routine is called to create a new foreign key on the table
84410** currently under construction.  pFromCol determines which columns
84411** in the current table point to the foreign key.  If pFromCol==0 then
84412** connect the key to the last column inserted.  pTo is the name of
84413** the table referred to.  pToCol is a list of tables in the other
84414** pTo table that the foreign key points to.  flags contains all
84415** information about the conflict resolution algorithms specified
84416** in the ON DELETE, ON UPDATE and ON INSERT clauses.
84417**
84418** An FKey structure is created and added to the table currently
84419** under construction in the pParse->pNewTable field.
84420**
84421** The foreign key is set for IMMEDIATE processing.  A subsequent call
84422** to sqlite3DeferForeignKey() might change this to DEFERRED.
84423*/
84424SQLITE_PRIVATE void sqlite3CreateForeignKey(
84425  Parse *pParse,       /* Parsing context */
84426  ExprList *pFromCol,  /* Columns in this table that point to other table */
84427  Token *pTo,          /* Name of the other table */
84428  ExprList *pToCol,    /* Columns in the other table */
84429  int flags            /* Conflict resolution algorithms. */
84430){
84431  sqlite3 *db = pParse->db;
84432#ifndef SQLITE_OMIT_FOREIGN_KEY
84433  FKey *pFKey = 0;
84434  FKey *pNextTo;
84435  Table *p = pParse->pNewTable;
84436  int nByte;
84437  int i;
84438  int nCol;
84439  char *z;
84440
84441  assert( pTo!=0 );
84442  if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
84443  if( pFromCol==0 ){
84444    int iCol = p->nCol-1;
84445    if( NEVER(iCol<0) ) goto fk_end;
84446    if( pToCol && pToCol->nExpr!=1 ){
84447      sqlite3ErrorMsg(pParse, "foreign key on %s"
84448         " should reference only one column of table %T",
84449         p->aCol[iCol].zName, pTo);
84450      goto fk_end;
84451    }
84452    nCol = 1;
84453  }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
84454    sqlite3ErrorMsg(pParse,
84455        "number of columns in foreign key does not match the number of "
84456        "columns in the referenced table");
84457    goto fk_end;
84458  }else{
84459    nCol = pFromCol->nExpr;
84460  }
84461  nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
84462  if( pToCol ){
84463    for(i=0; i<pToCol->nExpr; i++){
84464      nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
84465    }
84466  }
84467  pFKey = sqlite3DbMallocZero(db, nByte );
84468  if( pFKey==0 ){
84469    goto fk_end;
84470  }
84471  pFKey->pFrom = p;
84472  pFKey->pNextFrom = p->pFKey;
84473  z = (char*)&pFKey->aCol[nCol];
84474  pFKey->zTo = z;
84475  memcpy(z, pTo->z, pTo->n);
84476  z[pTo->n] = 0;
84477  sqlite3Dequote(z);
84478  z += pTo->n+1;
84479  pFKey->nCol = nCol;
84480  if( pFromCol==0 ){
84481    pFKey->aCol[0].iFrom = p->nCol-1;
84482  }else{
84483    for(i=0; i<nCol; i++){
84484      int j;
84485      for(j=0; j<p->nCol; j++){
84486        if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
84487          pFKey->aCol[i].iFrom = j;
84488          break;
84489        }
84490      }
84491      if( j>=p->nCol ){
84492        sqlite3ErrorMsg(pParse,
84493          "unknown column \"%s\" in foreign key definition",
84494          pFromCol->a[i].zName);
84495        goto fk_end;
84496      }
84497    }
84498  }
84499  if( pToCol ){
84500    for(i=0; i<nCol; i++){
84501      int n = sqlite3Strlen30(pToCol->a[i].zName);
84502      pFKey->aCol[i].zCol = z;
84503      memcpy(z, pToCol->a[i].zName, n);
84504      z[n] = 0;
84505      z += n+1;
84506    }
84507  }
84508  pFKey->isDeferred = 0;
84509  pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
84510  pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
84511
84512  assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
84513  pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
84514      pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
84515  );
84516  if( pNextTo==pFKey ){
84517    db->mallocFailed = 1;
84518    goto fk_end;
84519  }
84520  if( pNextTo ){
84521    assert( pNextTo->pPrevTo==0 );
84522    pFKey->pNextTo = pNextTo;
84523    pNextTo->pPrevTo = pFKey;
84524  }
84525
84526  /* Link the foreign key to the table as the last step.
84527  */
84528  p->pFKey = pFKey;
84529  pFKey = 0;
84530
84531fk_end:
84532  sqlite3DbFree(db, pFKey);
84533#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
84534  sqlite3ExprListDelete(db, pFromCol);
84535  sqlite3ExprListDelete(db, pToCol);
84536}
84537
84538/*
84539** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
84540** clause is seen as part of a foreign key definition.  The isDeferred
84541** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
84542** The behavior of the most recently created foreign key is adjusted
84543** accordingly.
84544*/
84545SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
84546#ifndef SQLITE_OMIT_FOREIGN_KEY
84547  Table *pTab;
84548  FKey *pFKey;
84549  if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
84550  assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
84551  pFKey->isDeferred = (u8)isDeferred;
84552#endif
84553}
84554
84555/*
84556** Generate code that will erase and refill index *pIdx.  This is
84557** used to initialize a newly created index or to recompute the
84558** content of an index in response to a REINDEX command.
84559**
84560** if memRootPage is not negative, it means that the index is newly
84561** created.  The register specified by memRootPage contains the
84562** root page number of the index.  If memRootPage is negative, then
84563** the index already exists and must be cleared before being refilled and
84564** the root page number of the index is taken from pIndex->tnum.
84565*/
84566static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
84567  Table *pTab = pIndex->pTable;  /* The table that is indexed */
84568  int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
84569  int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
84570  int iSorter;                   /* Cursor opened by OpenSorter (if in use) */
84571  int addr1;                     /* Address of top of loop */
84572  int addr2;                     /* Address to jump to for next iteration */
84573  int tnum;                      /* Root page of index */
84574  Vdbe *v;                       /* Generate code into this virtual machine */
84575  KeyInfo *pKey;                 /* KeyInfo for index */
84576  int regRecord;                 /* Register holding assemblied index record */
84577  sqlite3 *db = pParse->db;      /* The database connection */
84578  int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
84579
84580#ifndef SQLITE_OMIT_AUTHORIZATION
84581  if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
84582      db->aDb[iDb].zName ) ){
84583    return;
84584  }
84585#endif
84586
84587  /* Require a write-lock on the table to perform this operation */
84588  sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
84589
84590  v = sqlite3GetVdbe(pParse);
84591  if( v==0 ) return;
84592  if( memRootPage>=0 ){
84593    tnum = memRootPage;
84594  }else{
84595    tnum = pIndex->tnum;
84596    sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
84597  }
84598  pKey = sqlite3IndexKeyinfo(pParse, pIndex);
84599  sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
84600                    (char *)pKey, P4_KEYINFO_HANDOFF);
84601  sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
84602
84603  /* Open the sorter cursor if we are to use one. */
84604  iSorter = pParse->nTab++;
84605  sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, 0, (char*)pKey, P4_KEYINFO);
84606
84607  /* Open the table. Loop through all rows of the table, inserting index
84608  ** records into the sorter. */
84609  sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
84610  addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
84611  regRecord = sqlite3GetTempReg(pParse);
84612
84613  sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
84614  sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
84615  sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
84616  sqlite3VdbeJumpHere(v, addr1);
84617  addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0);
84618  if( pIndex->onError!=OE_None ){
84619    int j2 = sqlite3VdbeCurrentAddr(v) + 3;
84620    sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
84621    addr2 = sqlite3VdbeCurrentAddr(v);
84622    sqlite3VdbeAddOp3(v, OP_SorterCompare, iSorter, j2, regRecord);
84623    sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_UNIQUE,
84624        OE_Abort, "indexed columns are not unique", P4_STATIC
84625    );
84626  }else{
84627    addr2 = sqlite3VdbeCurrentAddr(v);
84628  }
84629  sqlite3VdbeAddOp2(v, OP_SorterData, iSorter, regRecord);
84630  sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1);
84631  sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
84632  sqlite3ReleaseTempReg(pParse, regRecord);
84633  sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2);
84634  sqlite3VdbeJumpHere(v, addr1);
84635
84636  sqlite3VdbeAddOp1(v, OP_Close, iTab);
84637  sqlite3VdbeAddOp1(v, OP_Close, iIdx);
84638  sqlite3VdbeAddOp1(v, OP_Close, iSorter);
84639}
84640
84641/*
84642** Create a new index for an SQL table.  pName1.pName2 is the name of the index
84643** and pTblList is the name of the table that is to be indexed.  Both will
84644** be NULL for a primary key or an index that is created to satisfy a
84645** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
84646** as the table to be indexed.  pParse->pNewTable is a table that is
84647** currently being constructed by a CREATE TABLE statement.
84648**
84649** pList is a list of columns to be indexed.  pList will be NULL if this
84650** is a primary key or unique-constraint on the most recent column added
84651** to the table currently under construction.
84652**
84653** If the index is created successfully, return a pointer to the new Index
84654** structure. This is used by sqlite3AddPrimaryKey() to mark the index
84655** as the tables primary key (Index.autoIndex==2).
84656*/
84657SQLITE_PRIVATE Index *sqlite3CreateIndex(
84658  Parse *pParse,     /* All information about this parse */
84659  Token *pName1,     /* First part of index name. May be NULL */
84660  Token *pName2,     /* Second part of index name. May be NULL */
84661  SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
84662  ExprList *pList,   /* A list of columns to be indexed */
84663  int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
84664  Token *pStart,     /* The CREATE token that begins this statement */
84665  Token *pEnd,       /* The ")" that closes the CREATE INDEX statement */
84666  int sortOrder,     /* Sort order of primary key when pList==NULL */
84667  int ifNotExist     /* Omit error if index already exists */
84668){
84669  Index *pRet = 0;     /* Pointer to return */
84670  Table *pTab = 0;     /* Table to be indexed */
84671  Index *pIndex = 0;   /* The index to be created */
84672  char *zName = 0;     /* Name of the index */
84673  int nName;           /* Number of characters in zName */
84674  int i, j;
84675  Token nullId;        /* Fake token for an empty ID list */
84676  DbFixer sFix;        /* For assigning database names to pTable */
84677  int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
84678  sqlite3 *db = pParse->db;
84679  Db *pDb;             /* The specific table containing the indexed database */
84680  int iDb;             /* Index of the database that is being written */
84681  Token *pName = 0;    /* Unqualified name of the index to create */
84682  struct ExprList_item *pListItem; /* For looping over pList */
84683  int nCol;
84684  int nExtra = 0;
84685  char *zExtra;
84686
84687  assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */
84688  assert( pParse->nErr==0 );      /* Never called with prior errors */
84689  if( db->mallocFailed || IN_DECLARE_VTAB ){
84690    goto exit_create_index;
84691  }
84692  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
84693    goto exit_create_index;
84694  }
84695
84696  /*
84697  ** Find the table that is to be indexed.  Return early if not found.
84698  */
84699  if( pTblName!=0 ){
84700
84701    /* Use the two-part index name to determine the database
84702    ** to search for the table. 'Fix' the table name to this db
84703    ** before looking up the table.
84704    */
84705    assert( pName1 && pName2 );
84706    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
84707    if( iDb<0 ) goto exit_create_index;
84708    assert( pName && pName->z );
84709
84710#ifndef SQLITE_OMIT_TEMPDB
84711    /* If the index name was unqualified, check if the table
84712    ** is a temp table. If so, set the database to 1. Do not do this
84713    ** if initialising a database schema.
84714    */
84715    if( !db->init.busy ){
84716      pTab = sqlite3SrcListLookup(pParse, pTblName);
84717      if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
84718        iDb = 1;
84719      }
84720    }
84721#endif
84722
84723    if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
84724        sqlite3FixSrcList(&sFix, pTblName)
84725    ){
84726      /* Because the parser constructs pTblName from a single identifier,
84727      ** sqlite3FixSrcList can never fail. */
84728      assert(0);
84729    }
84730    pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
84731    assert( db->mallocFailed==0 || pTab==0 );
84732    if( pTab==0 ) goto exit_create_index;
84733    assert( db->aDb[iDb].pSchema==pTab->pSchema );
84734  }else{
84735    assert( pName==0 );
84736    assert( pStart==0 );
84737    pTab = pParse->pNewTable;
84738    if( !pTab ) goto exit_create_index;
84739    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
84740  }
84741  pDb = &db->aDb[iDb];
84742
84743  assert( pTab!=0 );
84744  assert( pParse->nErr==0 );
84745  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
84746       && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
84747    sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
84748    goto exit_create_index;
84749  }
84750#ifndef SQLITE_OMIT_VIEW
84751  if( pTab->pSelect ){
84752    sqlite3ErrorMsg(pParse, "views may not be indexed");
84753    goto exit_create_index;
84754  }
84755#endif
84756#ifndef SQLITE_OMIT_VIRTUALTABLE
84757  if( IsVirtual(pTab) ){
84758    sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
84759    goto exit_create_index;
84760  }
84761#endif
84762
84763  /*
84764  ** Find the name of the index.  Make sure there is not already another
84765  ** index or table with the same name.
84766  **
84767  ** Exception:  If we are reading the names of permanent indices from the
84768  ** sqlite_master table (because some other process changed the schema) and
84769  ** one of the index names collides with the name of a temporary table or
84770  ** index, then we will continue to process this index.
84771  **
84772  ** If pName==0 it means that we are
84773  ** dealing with a primary key or UNIQUE constraint.  We have to invent our
84774  ** own name.
84775  */
84776  if( pName ){
84777    zName = sqlite3NameFromToken(db, pName);
84778    if( zName==0 ) goto exit_create_index;
84779    assert( pName->z!=0 );
84780    if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
84781      goto exit_create_index;
84782    }
84783    if( !db->init.busy ){
84784      if( sqlite3FindTable(db, zName, 0)!=0 ){
84785        sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
84786        goto exit_create_index;
84787      }
84788    }
84789    if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
84790      if( !ifNotExist ){
84791        sqlite3ErrorMsg(pParse, "index %s already exists", zName);
84792      }else{
84793        assert( !db->init.busy );
84794        sqlite3CodeVerifySchema(pParse, iDb);
84795      }
84796      goto exit_create_index;
84797    }
84798  }else{
84799    int n;
84800    Index *pLoop;
84801    for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
84802    zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
84803    if( zName==0 ){
84804      goto exit_create_index;
84805    }
84806  }
84807
84808  /* Check for authorization to create an index.
84809  */
84810#ifndef SQLITE_OMIT_AUTHORIZATION
84811  {
84812    const char *zDb = pDb->zName;
84813    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
84814      goto exit_create_index;
84815    }
84816    i = SQLITE_CREATE_INDEX;
84817    if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
84818    if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
84819      goto exit_create_index;
84820    }
84821  }
84822#endif
84823
84824  /* If pList==0, it means this routine was called to make a primary
84825  ** key out of the last column added to the table under construction.
84826  ** So create a fake list to simulate this.
84827  */
84828  if( pList==0 ){
84829    nullId.z = pTab->aCol[pTab->nCol-1].zName;
84830    nullId.n = sqlite3Strlen30((char*)nullId.z);
84831    pList = sqlite3ExprListAppend(pParse, 0, 0);
84832    if( pList==0 ) goto exit_create_index;
84833    sqlite3ExprListSetName(pParse, pList, &nullId, 0);
84834    pList->a[0].sortOrder = (u8)sortOrder;
84835  }
84836
84837  /* Figure out how many bytes of space are required to store explicitly
84838  ** specified collation sequence names.
84839  */
84840  for(i=0; i<pList->nExpr; i++){
84841    Expr *pExpr = pList->a[i].pExpr;
84842    if( pExpr ){
84843      assert( pExpr->op==TK_COLLATE );
84844      nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
84845    }
84846  }
84847
84848  /*
84849  ** Allocate the index structure.
84850  */
84851  nName = sqlite3Strlen30(zName);
84852  nCol = pList->nExpr;
84853  pIndex = sqlite3DbMallocZero(db,
84854      ROUND8(sizeof(Index)) +              /* Index structure  */
84855      ROUND8(sizeof(tRowcnt)*(nCol+1)) +   /* Index.aiRowEst   */
84856      sizeof(char *)*nCol +                /* Index.azColl     */
84857      sizeof(int)*nCol +                   /* Index.aiColumn   */
84858      sizeof(u8)*nCol +                    /* Index.aSortOrder */
84859      nName + 1 +                          /* Index.zName      */
84860      nExtra                               /* Collation sequence names */
84861  );
84862  if( db->mallocFailed ){
84863    goto exit_create_index;
84864  }
84865  zExtra = (char*)pIndex;
84866  pIndex->aiRowEst = (tRowcnt*)&zExtra[ROUND8(sizeof(Index))];
84867  pIndex->azColl = (char**)
84868     ((char*)pIndex->aiRowEst + ROUND8(sizeof(tRowcnt)*nCol+1));
84869  assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowEst) );
84870  assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
84871  pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
84872  pIndex->aSortOrder = (u8 *)(&pIndex->aiColumn[nCol]);
84873  pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
84874  zExtra = (char *)(&pIndex->zName[nName+1]);
84875  memcpy(pIndex->zName, zName, nName+1);
84876  pIndex->pTable = pTab;
84877  pIndex->nColumn = pList->nExpr;
84878  pIndex->onError = (u8)onError;
84879  pIndex->autoIndex = (u8)(pName==0);
84880  pIndex->pSchema = db->aDb[iDb].pSchema;
84881  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
84882
84883  /* Check to see if we should honor DESC requests on index columns
84884  */
84885  if( pDb->pSchema->file_format>=4 ){
84886    sortOrderMask = -1;   /* Honor DESC */
84887  }else{
84888    sortOrderMask = 0;    /* Ignore DESC */
84889  }
84890
84891  /* Scan the names of the columns of the table to be indexed and
84892  ** load the column indices into the Index structure.  Report an error
84893  ** if any column is not found.
84894  **
84895  ** TODO:  Add a test to make sure that the same column is not named
84896  ** more than once within the same index.  Only the first instance of
84897  ** the column will ever be used by the optimizer.  Note that using the
84898  ** same column more than once cannot be an error because that would
84899  ** break backwards compatibility - it needs to be a warning.
84900  */
84901  for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
84902    const char *zColName = pListItem->zName;
84903    Column *pTabCol;
84904    int requestedSortOrder;
84905    char *zColl;                   /* Collation sequence name */
84906
84907    for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
84908      if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
84909    }
84910    if( j>=pTab->nCol ){
84911      sqlite3ErrorMsg(pParse, "table %s has no column named %s",
84912        pTab->zName, zColName);
84913      pParse->checkSchema = 1;
84914      goto exit_create_index;
84915    }
84916    pIndex->aiColumn[i] = j;
84917    if( pListItem->pExpr ){
84918      int nColl;
84919      assert( pListItem->pExpr->op==TK_COLLATE );
84920      zColl = pListItem->pExpr->u.zToken;
84921      nColl = sqlite3Strlen30(zColl) + 1;
84922      assert( nExtra>=nColl );
84923      memcpy(zExtra, zColl, nColl);
84924      zColl = zExtra;
84925      zExtra += nColl;
84926      nExtra -= nColl;
84927    }else{
84928      zColl = pTab->aCol[j].zColl;
84929      if( !zColl ) zColl = "BINARY";
84930    }
84931    if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
84932      goto exit_create_index;
84933    }
84934    pIndex->azColl[i] = zColl;
84935    requestedSortOrder = pListItem->sortOrder & sortOrderMask;
84936    pIndex->aSortOrder[i] = (u8)requestedSortOrder;
84937  }
84938  sqlite3DefaultRowEst(pIndex);
84939
84940  if( pTab==pParse->pNewTable ){
84941    /* This routine has been called to create an automatic index as a
84942    ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
84943    ** a PRIMARY KEY or UNIQUE clause following the column definitions.
84944    ** i.e. one of:
84945    **
84946    ** CREATE TABLE t(x PRIMARY KEY, y);
84947    ** CREATE TABLE t(x, y, UNIQUE(x, y));
84948    **
84949    ** Either way, check to see if the table already has such an index. If
84950    ** so, don't bother creating this one. This only applies to
84951    ** automatically created indices. Users can do as they wish with
84952    ** explicit indices.
84953    **
84954    ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
84955    ** (and thus suppressing the second one) even if they have different
84956    ** sort orders.
84957    **
84958    ** If there are different collating sequences or if the columns of
84959    ** the constraint occur in different orders, then the constraints are
84960    ** considered distinct and both result in separate indices.
84961    */
84962    Index *pIdx;
84963    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
84964      int k;
84965      assert( pIdx->onError!=OE_None );
84966      assert( pIdx->autoIndex );
84967      assert( pIndex->onError!=OE_None );
84968
84969      if( pIdx->nColumn!=pIndex->nColumn ) continue;
84970      for(k=0; k<pIdx->nColumn; k++){
84971        const char *z1;
84972        const char *z2;
84973        if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
84974        z1 = pIdx->azColl[k];
84975        z2 = pIndex->azColl[k];
84976        if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
84977      }
84978      if( k==pIdx->nColumn ){
84979        if( pIdx->onError!=pIndex->onError ){
84980          /* This constraint creates the same index as a previous
84981          ** constraint specified somewhere in the CREATE TABLE statement.
84982          ** However the ON CONFLICT clauses are different. If both this
84983          ** constraint and the previous equivalent constraint have explicit
84984          ** ON CONFLICT clauses this is an error. Otherwise, use the
84985          ** explicitly specified behavior for the index.
84986          */
84987          if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
84988            sqlite3ErrorMsg(pParse,
84989                "conflicting ON CONFLICT clauses specified", 0);
84990          }
84991          if( pIdx->onError==OE_Default ){
84992            pIdx->onError = pIndex->onError;
84993          }
84994        }
84995        goto exit_create_index;
84996      }
84997    }
84998  }
84999
85000  /* Link the new Index structure to its table and to the other
85001  ** in-memory database structures.
85002  */
85003  if( db->init.busy ){
85004    Index *p;
85005    assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
85006    p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
85007                          pIndex->zName, sqlite3Strlen30(pIndex->zName),
85008                          pIndex);
85009    if( p ){
85010      assert( p==pIndex );  /* Malloc must have failed */
85011      db->mallocFailed = 1;
85012      goto exit_create_index;
85013    }
85014    db->flags |= SQLITE_InternChanges;
85015    if( pTblName!=0 ){
85016      pIndex->tnum = db->init.newTnum;
85017    }
85018  }
85019
85020  /* If the db->init.busy is 0 then create the index on disk.  This
85021  ** involves writing the index into the master table and filling in the
85022  ** index with the current table contents.
85023  **
85024  ** The db->init.busy is 0 when the user first enters a CREATE INDEX
85025  ** command.  db->init.busy is 1 when a database is opened and
85026  ** CREATE INDEX statements are read out of the master table.  In
85027  ** the latter case the index already exists on disk, which is why
85028  ** we don't want to recreate it.
85029  **
85030  ** If pTblName==0 it means this index is generated as a primary key
85031  ** or UNIQUE constraint of a CREATE TABLE statement.  Since the table
85032  ** has just been created, it contains no data and the index initialization
85033  ** step can be skipped.
85034  */
85035  else{ /* if( db->init.busy==0 ) */
85036    Vdbe *v;
85037    char *zStmt;
85038    int iMem = ++pParse->nMem;
85039
85040    v = sqlite3GetVdbe(pParse);
85041    if( v==0 ) goto exit_create_index;
85042
85043
85044    /* Create the rootpage for the index
85045    */
85046    sqlite3BeginWriteOperation(pParse, 1, iDb);
85047    sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
85048
85049    /* Gather the complete text of the CREATE INDEX statement into
85050    ** the zStmt variable
85051    */
85052    if( pStart ){
85053      assert( pEnd!=0 );
85054      /* A named index with an explicit CREATE INDEX statement */
85055      zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
85056        onError==OE_None ? "" : " UNIQUE",
85057        (int)(pEnd->z - pName->z) + 1,
85058        pName->z);
85059    }else{
85060      /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
85061      /* zStmt = sqlite3MPrintf(""); */
85062      zStmt = 0;
85063    }
85064
85065    /* Add an entry in sqlite_master for this index
85066    */
85067    sqlite3NestedParse(pParse,
85068        "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
85069        db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
85070        pIndex->zName,
85071        pTab->zName,
85072        iMem,
85073        zStmt
85074    );
85075    sqlite3DbFree(db, zStmt);
85076
85077    /* Fill the index with data and reparse the schema. Code an OP_Expire
85078    ** to invalidate all pre-compiled statements.
85079    */
85080    if( pTblName ){
85081      sqlite3RefillIndex(pParse, pIndex, iMem);
85082      sqlite3ChangeCookie(pParse, iDb);
85083      sqlite3VdbeAddParseSchemaOp(v, iDb,
85084         sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
85085      sqlite3VdbeAddOp1(v, OP_Expire, 0);
85086    }
85087  }
85088
85089  /* When adding an index to the list of indices for a table, make
85090  ** sure all indices labeled OE_Replace come after all those labeled
85091  ** OE_Ignore.  This is necessary for the correct constraint check
85092  ** processing (in sqlite3GenerateConstraintChecks()) as part of
85093  ** UPDATE and INSERT statements.
85094  */
85095  if( db->init.busy || pTblName==0 ){
85096    if( onError!=OE_Replace || pTab->pIndex==0
85097         || pTab->pIndex->onError==OE_Replace){
85098      pIndex->pNext = pTab->pIndex;
85099      pTab->pIndex = pIndex;
85100    }else{
85101      Index *pOther = pTab->pIndex;
85102      while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
85103        pOther = pOther->pNext;
85104      }
85105      pIndex->pNext = pOther->pNext;
85106      pOther->pNext = pIndex;
85107    }
85108    pRet = pIndex;
85109    pIndex = 0;
85110  }
85111
85112  /* Clean up before exiting */
85113exit_create_index:
85114  if( pIndex ){
85115    sqlite3DbFree(db, pIndex->zColAff);
85116    sqlite3DbFree(db, pIndex);
85117  }
85118  sqlite3ExprListDelete(db, pList);
85119  sqlite3SrcListDelete(db, pTblName);
85120  sqlite3DbFree(db, zName);
85121  return pRet;
85122}
85123
85124/*
85125** Fill the Index.aiRowEst[] array with default information - information
85126** to be used when we have not run the ANALYZE command.
85127**
85128** aiRowEst[0] is suppose to contain the number of elements in the index.
85129** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
85130** number of rows in the table that match any particular value of the
85131** first column of the index.  aiRowEst[2] is an estimate of the number
85132** of rows that match any particular combiniation of the first 2 columns
85133** of the index.  And so forth.  It must always be the case that
85134*
85135**           aiRowEst[N]<=aiRowEst[N-1]
85136**           aiRowEst[N]>=1
85137**
85138** Apart from that, we have little to go on besides intuition as to
85139** how aiRowEst[] should be initialized.  The numbers generated here
85140** are based on typical values found in actual indices.
85141*/
85142SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
85143  tRowcnt *a = pIdx->aiRowEst;
85144  int i;
85145  tRowcnt n;
85146  assert( a!=0 );
85147  a[0] = pIdx->pTable->nRowEst;
85148  if( a[0]<10 ) a[0] = 10;
85149  n = 10;
85150  for(i=1; i<=pIdx->nColumn; i++){
85151    a[i] = n;
85152    if( n>5 ) n--;
85153  }
85154  if( pIdx->onError!=OE_None ){
85155    a[pIdx->nColumn] = 1;
85156  }
85157}
85158
85159/*
85160** This routine will drop an existing named index.  This routine
85161** implements the DROP INDEX statement.
85162*/
85163SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
85164  Index *pIndex;
85165  Vdbe *v;
85166  sqlite3 *db = pParse->db;
85167  int iDb;
85168
85169  assert( pParse->nErr==0 );   /* Never called with prior errors */
85170  if( db->mallocFailed ){
85171    goto exit_drop_index;
85172  }
85173  assert( pName->nSrc==1 );
85174  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
85175    goto exit_drop_index;
85176  }
85177  pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
85178  if( pIndex==0 ){
85179    if( !ifExists ){
85180      sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
85181    }else{
85182      sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
85183    }
85184    pParse->checkSchema = 1;
85185    goto exit_drop_index;
85186  }
85187  if( pIndex->autoIndex ){
85188    sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
85189      "or PRIMARY KEY constraint cannot be dropped", 0);
85190    goto exit_drop_index;
85191  }
85192  iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
85193#ifndef SQLITE_OMIT_AUTHORIZATION
85194  {
85195    int code = SQLITE_DROP_INDEX;
85196    Table *pTab = pIndex->pTable;
85197    const char *zDb = db->aDb[iDb].zName;
85198    const char *zTab = SCHEMA_TABLE(iDb);
85199    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
85200      goto exit_drop_index;
85201    }
85202    if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
85203    if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
85204      goto exit_drop_index;
85205    }
85206  }
85207#endif
85208
85209  /* Generate code to remove the index and from the master table */
85210  v = sqlite3GetVdbe(pParse);
85211  if( v ){
85212    sqlite3BeginWriteOperation(pParse, 1, iDb);
85213    sqlite3NestedParse(pParse,
85214       "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
85215       db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
85216    );
85217    sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
85218    sqlite3ChangeCookie(pParse, iDb);
85219    destroyRootPage(pParse, pIndex->tnum, iDb);
85220    sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
85221  }
85222
85223exit_drop_index:
85224  sqlite3SrcListDelete(db, pName);
85225}
85226
85227/*
85228** pArray is a pointer to an array of objects. Each object in the
85229** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
85230** to extend the array so that there is space for a new object at the end.
85231**
85232** When this function is called, *pnEntry contains the current size of
85233** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
85234** in total).
85235**
85236** If the realloc() is successful (i.e. if no OOM condition occurs), the
85237** space allocated for the new object is zeroed, *pnEntry updated to
85238** reflect the new size of the array and a pointer to the new allocation
85239** returned. *pIdx is set to the index of the new array entry in this case.
85240**
85241** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
85242** unchanged and a copy of pArray returned.
85243*/
85244SQLITE_PRIVATE void *sqlite3ArrayAllocate(
85245  sqlite3 *db,      /* Connection to notify of malloc failures */
85246  void *pArray,     /* Array of objects.  Might be reallocated */
85247  int szEntry,      /* Size of each object in the array */
85248  int *pnEntry,     /* Number of objects currently in use */
85249  int *pIdx         /* Write the index of a new slot here */
85250){
85251  char *z;
85252  int n = *pnEntry;
85253  if( (n & (n-1))==0 ){
85254    int sz = (n==0) ? 1 : 2*n;
85255    void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
85256    if( pNew==0 ){
85257      *pIdx = -1;
85258      return pArray;
85259    }
85260    pArray = pNew;
85261  }
85262  z = (char*)pArray;
85263  memset(&z[n * szEntry], 0, szEntry);
85264  *pIdx = n;
85265  ++*pnEntry;
85266  return pArray;
85267}
85268
85269/*
85270** Append a new element to the given IdList.  Create a new IdList if
85271** need be.
85272**
85273** A new IdList is returned, or NULL if malloc() fails.
85274*/
85275SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
85276  int i;
85277  if( pList==0 ){
85278    pList = sqlite3DbMallocZero(db, sizeof(IdList) );
85279    if( pList==0 ) return 0;
85280  }
85281  pList->a = sqlite3ArrayAllocate(
85282      db,
85283      pList->a,
85284      sizeof(pList->a[0]),
85285      &pList->nId,
85286      &i
85287  );
85288  if( i<0 ){
85289    sqlite3IdListDelete(db, pList);
85290    return 0;
85291  }
85292  pList->a[i].zName = sqlite3NameFromToken(db, pToken);
85293  return pList;
85294}
85295
85296/*
85297** Delete an IdList.
85298*/
85299SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
85300  int i;
85301  if( pList==0 ) return;
85302  for(i=0; i<pList->nId; i++){
85303    sqlite3DbFree(db, pList->a[i].zName);
85304  }
85305  sqlite3DbFree(db, pList->a);
85306  sqlite3DbFree(db, pList);
85307}
85308
85309/*
85310** Return the index in pList of the identifier named zId.  Return -1
85311** if not found.
85312*/
85313SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
85314  int i;
85315  if( pList==0 ) return -1;
85316  for(i=0; i<pList->nId; i++){
85317    if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
85318  }
85319  return -1;
85320}
85321
85322/*
85323** Expand the space allocated for the given SrcList object by
85324** creating nExtra new slots beginning at iStart.  iStart is zero based.
85325** New slots are zeroed.
85326**
85327** For example, suppose a SrcList initially contains two entries: A,B.
85328** To append 3 new entries onto the end, do this:
85329**
85330**    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
85331**
85332** After the call above it would contain:  A, B, nil, nil, nil.
85333** If the iStart argument had been 1 instead of 2, then the result
85334** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
85335** the iStart value would be 0.  The result then would
85336** be: nil, nil, nil, A, B.
85337**
85338** If a memory allocation fails the SrcList is unchanged.  The
85339** db->mallocFailed flag will be set to true.
85340*/
85341SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
85342  sqlite3 *db,       /* Database connection to notify of OOM errors */
85343  SrcList *pSrc,     /* The SrcList to be enlarged */
85344  int nExtra,        /* Number of new slots to add to pSrc->a[] */
85345  int iStart         /* Index in pSrc->a[] of first new slot */
85346){
85347  int i;
85348
85349  /* Sanity checking on calling parameters */
85350  assert( iStart>=0 );
85351  assert( nExtra>=1 );
85352  assert( pSrc!=0 );
85353  assert( iStart<=pSrc->nSrc );
85354
85355  /* Allocate additional space if needed */
85356  if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
85357    SrcList *pNew;
85358    int nAlloc = pSrc->nSrc+nExtra;
85359    int nGot;
85360    pNew = sqlite3DbRealloc(db, pSrc,
85361               sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
85362    if( pNew==0 ){
85363      assert( db->mallocFailed );
85364      return pSrc;
85365    }
85366    pSrc = pNew;
85367    nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
85368    pSrc->nAlloc = (u16)nGot;
85369  }
85370
85371  /* Move existing slots that come after the newly inserted slots
85372  ** out of the way */
85373  for(i=pSrc->nSrc-1; i>=iStart; i--){
85374    pSrc->a[i+nExtra] = pSrc->a[i];
85375  }
85376  pSrc->nSrc += (i16)nExtra;
85377
85378  /* Zero the newly allocated slots */
85379  memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
85380  for(i=iStart; i<iStart+nExtra; i++){
85381    pSrc->a[i].iCursor = -1;
85382  }
85383
85384  /* Return a pointer to the enlarged SrcList */
85385  return pSrc;
85386}
85387
85388
85389/*
85390** Append a new table name to the given SrcList.  Create a new SrcList if
85391** need be.  A new entry is created in the SrcList even if pTable is NULL.
85392**
85393** A SrcList is returned, or NULL if there is an OOM error.  The returned
85394** SrcList might be the same as the SrcList that was input or it might be
85395** a new one.  If an OOM error does occurs, then the prior value of pList
85396** that is input to this routine is automatically freed.
85397**
85398** If pDatabase is not null, it means that the table has an optional
85399** database name prefix.  Like this:  "database.table".  The pDatabase
85400** points to the table name and the pTable points to the database name.
85401** The SrcList.a[].zName field is filled with the table name which might
85402** come from pTable (if pDatabase is NULL) or from pDatabase.
85403** SrcList.a[].zDatabase is filled with the database name from pTable,
85404** or with NULL if no database is specified.
85405**
85406** In other words, if call like this:
85407**
85408**         sqlite3SrcListAppend(D,A,B,0);
85409**
85410** Then B is a table name and the database name is unspecified.  If called
85411** like this:
85412**
85413**         sqlite3SrcListAppend(D,A,B,C);
85414**
85415** Then C is the table name and B is the database name.  If C is defined
85416** then so is B.  In other words, we never have a case where:
85417**
85418**         sqlite3SrcListAppend(D,A,0,C);
85419**
85420** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
85421** before being added to the SrcList.
85422*/
85423SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
85424  sqlite3 *db,        /* Connection to notify of malloc failures */
85425  SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
85426  Token *pTable,      /* Table to append */
85427  Token *pDatabase    /* Database of the table */
85428){
85429  struct SrcList_item *pItem;
85430  assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
85431  if( pList==0 ){
85432    pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
85433    if( pList==0 ) return 0;
85434    pList->nAlloc = 1;
85435  }
85436  pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
85437  if( db->mallocFailed ){
85438    sqlite3SrcListDelete(db, pList);
85439    return 0;
85440  }
85441  pItem = &pList->a[pList->nSrc-1];
85442  if( pDatabase && pDatabase->z==0 ){
85443    pDatabase = 0;
85444  }
85445  if( pDatabase ){
85446    Token *pTemp = pDatabase;
85447    pDatabase = pTable;
85448    pTable = pTemp;
85449  }
85450  pItem->zName = sqlite3NameFromToken(db, pTable);
85451  pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
85452  return pList;
85453}
85454
85455/*
85456** Assign VdbeCursor index numbers to all tables in a SrcList
85457*/
85458SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
85459  int i;
85460  struct SrcList_item *pItem;
85461  assert(pList || pParse->db->mallocFailed );
85462  if( pList ){
85463    for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
85464      if( pItem->iCursor>=0 ) break;
85465      pItem->iCursor = pParse->nTab++;
85466      if( pItem->pSelect ){
85467        sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
85468      }
85469    }
85470  }
85471}
85472
85473/*
85474** Delete an entire SrcList including all its substructure.
85475*/
85476SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
85477  int i;
85478  struct SrcList_item *pItem;
85479  if( pList==0 ) return;
85480  for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
85481    sqlite3DbFree(db, pItem->zDatabase);
85482    sqlite3DbFree(db, pItem->zName);
85483    sqlite3DbFree(db, pItem->zAlias);
85484    sqlite3DbFree(db, pItem->zIndex);
85485    sqlite3DeleteTable(db, pItem->pTab);
85486    sqlite3SelectDelete(db, pItem->pSelect);
85487    sqlite3ExprDelete(db, pItem->pOn);
85488    sqlite3IdListDelete(db, pItem->pUsing);
85489  }
85490  sqlite3DbFree(db, pList);
85491}
85492
85493/*
85494** This routine is called by the parser to add a new term to the
85495** end of a growing FROM clause.  The "p" parameter is the part of
85496** the FROM clause that has already been constructed.  "p" is NULL
85497** if this is the first term of the FROM clause.  pTable and pDatabase
85498** are the name of the table and database named in the FROM clause term.
85499** pDatabase is NULL if the database name qualifier is missing - the
85500** usual case.  If the term has a alias, then pAlias points to the
85501** alias token.  If the term is a subquery, then pSubquery is the
85502** SELECT statement that the subquery encodes.  The pTable and
85503** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
85504** parameters are the content of the ON and USING clauses.
85505**
85506** Return a new SrcList which encodes is the FROM with the new
85507** term added.
85508*/
85509SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
85510  Parse *pParse,          /* Parsing context */
85511  SrcList *p,             /* The left part of the FROM clause already seen */
85512  Token *pTable,          /* Name of the table to add to the FROM clause */
85513  Token *pDatabase,       /* Name of the database containing pTable */
85514  Token *pAlias,          /* The right-hand side of the AS subexpression */
85515  Select *pSubquery,      /* A subquery used in place of a table name */
85516  Expr *pOn,              /* The ON clause of a join */
85517  IdList *pUsing          /* The USING clause of a join */
85518){
85519  struct SrcList_item *pItem;
85520  sqlite3 *db = pParse->db;
85521  if( !p && (pOn || pUsing) ){
85522    sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
85523      (pOn ? "ON" : "USING")
85524    );
85525    goto append_from_error;
85526  }
85527  p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
85528  if( p==0 || NEVER(p->nSrc==0) ){
85529    goto append_from_error;
85530  }
85531  pItem = &p->a[p->nSrc-1];
85532  assert( pAlias!=0 );
85533  if( pAlias->n ){
85534    pItem->zAlias = sqlite3NameFromToken(db, pAlias);
85535  }
85536  pItem->pSelect = pSubquery;
85537  pItem->pOn = pOn;
85538  pItem->pUsing = pUsing;
85539  return p;
85540
85541 append_from_error:
85542  assert( p==0 );
85543  sqlite3ExprDelete(db, pOn);
85544  sqlite3IdListDelete(db, pUsing);
85545  sqlite3SelectDelete(db, pSubquery);
85546  return 0;
85547}
85548
85549/*
85550** Add an INDEXED BY or NOT INDEXED clause to the most recently added
85551** element of the source-list passed as the second argument.
85552*/
85553SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
85554  assert( pIndexedBy!=0 );
85555  if( p && ALWAYS(p->nSrc>0) ){
85556    struct SrcList_item *pItem = &p->a[p->nSrc-1];
85557    assert( pItem->notIndexed==0 && pItem->zIndex==0 );
85558    if( pIndexedBy->n==1 && !pIndexedBy->z ){
85559      /* A "NOT INDEXED" clause was supplied. See parse.y
85560      ** construct "indexed_opt" for details. */
85561      pItem->notIndexed = 1;
85562    }else{
85563      pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
85564    }
85565  }
85566}
85567
85568/*
85569** When building up a FROM clause in the parser, the join operator
85570** is initially attached to the left operand.  But the code generator
85571** expects the join operator to be on the right operand.  This routine
85572** Shifts all join operators from left to right for an entire FROM
85573** clause.
85574**
85575** Example: Suppose the join is like this:
85576**
85577**           A natural cross join B
85578**
85579** The operator is "natural cross join".  The A and B operands are stored
85580** in p->a[0] and p->a[1], respectively.  The parser initially stores the
85581** operator with A.  This routine shifts that operator over to B.
85582*/
85583SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
85584  if( p ){
85585    int i;
85586    assert( p->a || p->nSrc==0 );
85587    for(i=p->nSrc-1; i>0; i--){
85588      p->a[i].jointype = p->a[i-1].jointype;
85589    }
85590    p->a[0].jointype = 0;
85591  }
85592}
85593
85594/*
85595** Begin a transaction
85596*/
85597SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
85598  sqlite3 *db;
85599  Vdbe *v;
85600  int i;
85601
85602  assert( pParse!=0 );
85603  db = pParse->db;
85604  assert( db!=0 );
85605/*  if( db->aDb[0].pBt==0 ) return; */
85606  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
85607    return;
85608  }
85609  v = sqlite3GetVdbe(pParse);
85610  if( !v ) return;
85611  if( type!=TK_DEFERRED ){
85612    for(i=0; i<db->nDb; i++){
85613      sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
85614      sqlite3VdbeUsesBtree(v, i);
85615    }
85616  }
85617  sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
85618}
85619
85620/*
85621** Commit a transaction
85622*/
85623SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
85624  Vdbe *v;
85625
85626  assert( pParse!=0 );
85627  assert( pParse->db!=0 );
85628  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
85629    return;
85630  }
85631  v = sqlite3GetVdbe(pParse);
85632  if( v ){
85633    sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
85634  }
85635}
85636
85637/*
85638** Rollback a transaction
85639*/
85640SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
85641  Vdbe *v;
85642
85643  assert( pParse!=0 );
85644  assert( pParse->db!=0 );
85645  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
85646    return;
85647  }
85648  v = sqlite3GetVdbe(pParse);
85649  if( v ){
85650    sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
85651  }
85652}
85653
85654/*
85655** This function is called by the parser when it parses a command to create,
85656** release or rollback an SQL savepoint.
85657*/
85658SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
85659  char *zName = sqlite3NameFromToken(pParse->db, pName);
85660  if( zName ){
85661    Vdbe *v = sqlite3GetVdbe(pParse);
85662#ifndef SQLITE_OMIT_AUTHORIZATION
85663    static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
85664    assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
85665#endif
85666    if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
85667      sqlite3DbFree(pParse->db, zName);
85668      return;
85669    }
85670    sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
85671  }
85672}
85673
85674/*
85675** Make sure the TEMP database is open and available for use.  Return
85676** the number of errors.  Leave any error messages in the pParse structure.
85677*/
85678SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
85679  sqlite3 *db = pParse->db;
85680  if( db->aDb[1].pBt==0 && !pParse->explain ){
85681    int rc;
85682    Btree *pBt;
85683    static const int flags =
85684          SQLITE_OPEN_READWRITE |
85685          SQLITE_OPEN_CREATE |
85686          SQLITE_OPEN_EXCLUSIVE |
85687          SQLITE_OPEN_DELETEONCLOSE |
85688          SQLITE_OPEN_TEMP_DB;
85689
85690    rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
85691    if( rc!=SQLITE_OK ){
85692      sqlite3ErrorMsg(pParse, "unable to open a temporary database "
85693        "file for storing temporary tables");
85694      pParse->rc = rc;
85695      return 1;
85696    }
85697    db->aDb[1].pBt = pBt;
85698    assert( db->aDb[1].pSchema );
85699    if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
85700      db->mallocFailed = 1;
85701      return 1;
85702    }
85703  }
85704  return 0;
85705}
85706
85707/*
85708** Generate VDBE code that will verify the schema cookie and start
85709** a read-transaction for all named database files.
85710**
85711** It is important that all schema cookies be verified and all
85712** read transactions be started before anything else happens in
85713** the VDBE program.  But this routine can be called after much other
85714** code has been generated.  So here is what we do:
85715**
85716** The first time this routine is called, we code an OP_Goto that
85717** will jump to a subroutine at the end of the program.  Then we
85718** record every database that needs its schema verified in the
85719** pParse->cookieMask field.  Later, after all other code has been
85720** generated, the subroutine that does the cookie verifications and
85721** starts the transactions will be coded and the OP_Goto P2 value
85722** will be made to point to that subroutine.  The generation of the
85723** cookie verification subroutine code happens in sqlite3FinishCoding().
85724**
85725** If iDb<0 then code the OP_Goto only - don't set flag to verify the
85726** schema on any databases.  This can be used to position the OP_Goto
85727** early in the code, before we know if any database tables will be used.
85728*/
85729SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
85730  Parse *pToplevel = sqlite3ParseToplevel(pParse);
85731
85732#ifndef SQLITE_OMIT_TRIGGER
85733  if( pToplevel!=pParse ){
85734    /* This branch is taken if a trigger is currently being coded. In this
85735    ** case, set cookieGoto to a non-zero value to show that this function
85736    ** has been called. This is used by the sqlite3ExprCodeConstants()
85737    ** function. */
85738    pParse->cookieGoto = -1;
85739  }
85740#endif
85741  if( pToplevel->cookieGoto==0 ){
85742    Vdbe *v = sqlite3GetVdbe(pToplevel);
85743    if( v==0 ) return;  /* This only happens if there was a prior error */
85744    pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
85745  }
85746  if( iDb>=0 ){
85747    sqlite3 *db = pToplevel->db;
85748    yDbMask mask;
85749
85750    assert( iDb<db->nDb );
85751    assert( db->aDb[iDb].pBt!=0 || iDb==1 );
85752    assert( iDb<SQLITE_MAX_ATTACHED+2 );
85753    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
85754    mask = ((yDbMask)1)<<iDb;
85755    if( (pToplevel->cookieMask & mask)==0 ){
85756      pToplevel->cookieMask |= mask;
85757      pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
85758      if( !OMIT_TEMPDB && iDb==1 ){
85759        sqlite3OpenTempDatabase(pToplevel);
85760      }
85761    }
85762  }
85763}
85764
85765/*
85766** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
85767** attached database. Otherwise, invoke it for the database named zDb only.
85768*/
85769SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
85770  sqlite3 *db = pParse->db;
85771  int i;
85772  for(i=0; i<db->nDb; i++){
85773    Db *pDb = &db->aDb[i];
85774    if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
85775      sqlite3CodeVerifySchema(pParse, i);
85776    }
85777  }
85778}
85779
85780/*
85781** Generate VDBE code that prepares for doing an operation that
85782** might change the database.
85783**
85784** This routine starts a new transaction if we are not already within
85785** a transaction.  If we are already within a transaction, then a checkpoint
85786** is set if the setStatement parameter is true.  A checkpoint should
85787** be set for operations that might fail (due to a constraint) part of
85788** the way through and which will need to undo some writes without having to
85789** rollback the whole transaction.  For operations where all constraints
85790** can be checked before any changes are made to the database, it is never
85791** necessary to undo a write and the checkpoint should not be set.
85792*/
85793SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
85794  Parse *pToplevel = sqlite3ParseToplevel(pParse);
85795  sqlite3CodeVerifySchema(pParse, iDb);
85796  pToplevel->writeMask |= ((yDbMask)1)<<iDb;
85797  pToplevel->isMultiWrite |= setStatement;
85798}
85799
85800/*
85801** Indicate that the statement currently under construction might write
85802** more than one entry (example: deleting one row then inserting another,
85803** inserting multiple rows in a table, or inserting a row and index entries.)
85804** If an abort occurs after some of these writes have completed, then it will
85805** be necessary to undo the completed writes.
85806*/
85807SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
85808  Parse *pToplevel = sqlite3ParseToplevel(pParse);
85809  pToplevel->isMultiWrite = 1;
85810}
85811
85812/*
85813** The code generator calls this routine if is discovers that it is
85814** possible to abort a statement prior to completion.  In order to
85815** perform this abort without corrupting the database, we need to make
85816** sure that the statement is protected by a statement transaction.
85817**
85818** Technically, we only need to set the mayAbort flag if the
85819** isMultiWrite flag was previously set.  There is a time dependency
85820** such that the abort must occur after the multiwrite.  This makes
85821** some statements involving the REPLACE conflict resolution algorithm
85822** go a little faster.  But taking advantage of this time dependency
85823** makes it more difficult to prove that the code is correct (in
85824** particular, it prevents us from writing an effective
85825** implementation of sqlite3AssertMayAbort()) and so we have chosen
85826** to take the safe route and skip the optimization.
85827*/
85828SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
85829  Parse *pToplevel = sqlite3ParseToplevel(pParse);
85830  pToplevel->mayAbort = 1;
85831}
85832
85833/*
85834** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
85835** error. The onError parameter determines which (if any) of the statement
85836** and/or current transaction is rolled back.
85837*/
85838SQLITE_PRIVATE void sqlite3HaltConstraint(
85839  Parse *pParse,    /* Parsing context */
85840  int errCode,      /* extended error code */
85841  int onError,      /* Constraint type */
85842  char *p4,         /* Error message */
85843  int p4type        /* P4_STATIC or P4_TRANSIENT */
85844){
85845  Vdbe *v = sqlite3GetVdbe(pParse);
85846  assert( (errCode&0xff)==SQLITE_CONSTRAINT );
85847  if( onError==OE_Abort ){
85848    sqlite3MayAbort(pParse);
85849  }
85850  sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
85851}
85852
85853/*
85854** Check to see if pIndex uses the collating sequence pColl.  Return
85855** true if it does and false if it does not.
85856*/
85857#ifndef SQLITE_OMIT_REINDEX
85858static int collationMatch(const char *zColl, Index *pIndex){
85859  int i;
85860  assert( zColl!=0 );
85861  for(i=0; i<pIndex->nColumn; i++){
85862    const char *z = pIndex->azColl[i];
85863    assert( z!=0 );
85864    if( 0==sqlite3StrICmp(z, zColl) ){
85865      return 1;
85866    }
85867  }
85868  return 0;
85869}
85870#endif
85871
85872/*
85873** Recompute all indices of pTab that use the collating sequence pColl.
85874** If pColl==0 then recompute all indices of pTab.
85875*/
85876#ifndef SQLITE_OMIT_REINDEX
85877static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
85878  Index *pIndex;              /* An index associated with pTab */
85879
85880  for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
85881    if( zColl==0 || collationMatch(zColl, pIndex) ){
85882      int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
85883      sqlite3BeginWriteOperation(pParse, 0, iDb);
85884      sqlite3RefillIndex(pParse, pIndex, -1);
85885    }
85886  }
85887}
85888#endif
85889
85890/*
85891** Recompute all indices of all tables in all databases where the
85892** indices use the collating sequence pColl.  If pColl==0 then recompute
85893** all indices everywhere.
85894*/
85895#ifndef SQLITE_OMIT_REINDEX
85896static void reindexDatabases(Parse *pParse, char const *zColl){
85897  Db *pDb;                    /* A single database */
85898  int iDb;                    /* The database index number */
85899  sqlite3 *db = pParse->db;   /* The database connection */
85900  HashElem *k;                /* For looping over tables in pDb */
85901  Table *pTab;                /* A table in the database */
85902
85903  assert( sqlite3BtreeHoldsAllMutexes(db) );  /* Needed for schema access */
85904  for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
85905    assert( pDb!=0 );
85906    for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
85907      pTab = (Table*)sqliteHashData(k);
85908      reindexTable(pParse, pTab, zColl);
85909    }
85910  }
85911}
85912#endif
85913
85914/*
85915** Generate code for the REINDEX command.
85916**
85917**        REINDEX                            -- 1
85918**        REINDEX  <collation>               -- 2
85919**        REINDEX  ?<database>.?<tablename>  -- 3
85920**        REINDEX  ?<database>.?<indexname>  -- 4
85921**
85922** Form 1 causes all indices in all attached databases to be rebuilt.
85923** Form 2 rebuilds all indices in all databases that use the named
85924** collating function.  Forms 3 and 4 rebuild the named index or all
85925** indices associated with the named table.
85926*/
85927#ifndef SQLITE_OMIT_REINDEX
85928SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
85929  CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
85930  char *z;                    /* Name of a table or index */
85931  const char *zDb;            /* Name of the database */
85932  Table *pTab;                /* A table in the database */
85933  Index *pIndex;              /* An index associated with pTab */
85934  int iDb;                    /* The database index number */
85935  sqlite3 *db = pParse->db;   /* The database connection */
85936  Token *pObjName;            /* Name of the table or index to be reindexed */
85937
85938  /* Read the database schema. If an error occurs, leave an error message
85939  ** and code in pParse and return NULL. */
85940  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
85941    return;
85942  }
85943
85944  if( pName1==0 ){
85945    reindexDatabases(pParse, 0);
85946    return;
85947  }else if( NEVER(pName2==0) || pName2->z==0 ){
85948    char *zColl;
85949    assert( pName1->z );
85950    zColl = sqlite3NameFromToken(pParse->db, pName1);
85951    if( !zColl ) return;
85952    pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
85953    if( pColl ){
85954      reindexDatabases(pParse, zColl);
85955      sqlite3DbFree(db, zColl);
85956      return;
85957    }
85958    sqlite3DbFree(db, zColl);
85959  }
85960  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
85961  if( iDb<0 ) return;
85962  z = sqlite3NameFromToken(db, pObjName);
85963  if( z==0 ) return;
85964  zDb = db->aDb[iDb].zName;
85965  pTab = sqlite3FindTable(db, z, zDb);
85966  if( pTab ){
85967    reindexTable(pParse, pTab, 0);
85968    sqlite3DbFree(db, z);
85969    return;
85970  }
85971  pIndex = sqlite3FindIndex(db, z, zDb);
85972  sqlite3DbFree(db, z);
85973  if( pIndex ){
85974    sqlite3BeginWriteOperation(pParse, 0, iDb);
85975    sqlite3RefillIndex(pParse, pIndex, -1);
85976    return;
85977  }
85978  sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
85979}
85980#endif
85981
85982/*
85983** Return a dynamicly allocated KeyInfo structure that can be used
85984** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
85985**
85986** If successful, a pointer to the new structure is returned. In this case
85987** the caller is responsible for calling sqlite3DbFree(db, ) on the returned
85988** pointer. If an error occurs (out of memory or missing collation
85989** sequence), NULL is returned and the state of pParse updated to reflect
85990** the error.
85991*/
85992SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
85993  int i;
85994  int nCol = pIdx->nColumn;
85995  int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
85996  sqlite3 *db = pParse->db;
85997  KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
85998
85999  if( pKey ){
86000    pKey->db = pParse->db;
86001    pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
86002    assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
86003    for(i=0; i<nCol; i++){
86004      char *zColl = pIdx->azColl[i];
86005      assert( zColl );
86006      pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
86007      pKey->aSortOrder[i] = pIdx->aSortOrder[i];
86008    }
86009    pKey->nField = (u16)nCol;
86010  }
86011
86012  if( pParse->nErr ){
86013    sqlite3DbFree(db, pKey);
86014    pKey = 0;
86015  }
86016  return pKey;
86017}
86018
86019/************** End of build.c ***********************************************/
86020/************** Begin file callback.c ****************************************/
86021/*
86022** 2005 May 23
86023**
86024** The author disclaims copyright to this source code.  In place of
86025** a legal notice, here is a blessing:
86026**
86027**    May you do good and not evil.
86028**    May you find forgiveness for yourself and forgive others.
86029**    May you share freely, never taking more than you give.
86030**
86031*************************************************************************
86032**
86033** This file contains functions used to access the internal hash tables
86034** of user defined functions and collation sequences.
86035*/
86036
86037
86038/*
86039** Invoke the 'collation needed' callback to request a collation sequence
86040** in the encoding enc of name zName, length nName.
86041*/
86042static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
86043  assert( !db->xCollNeeded || !db->xCollNeeded16 );
86044  if( db->xCollNeeded ){
86045    char *zExternal = sqlite3DbStrDup(db, zName);
86046    if( !zExternal ) return;
86047    db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
86048    sqlite3DbFree(db, zExternal);
86049  }
86050#ifndef SQLITE_OMIT_UTF16
86051  if( db->xCollNeeded16 ){
86052    char const *zExternal;
86053    sqlite3_value *pTmp = sqlite3ValueNew(db);
86054    sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
86055    zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
86056    if( zExternal ){
86057      db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
86058    }
86059    sqlite3ValueFree(pTmp);
86060  }
86061#endif
86062}
86063
86064/*
86065** This routine is called if the collation factory fails to deliver a
86066** collation function in the best encoding but there may be other versions
86067** of this collation function (for other text encodings) available. Use one
86068** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
86069** possible.
86070*/
86071static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
86072  CollSeq *pColl2;
86073  char *z = pColl->zName;
86074  int i;
86075  static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
86076  for(i=0; i<3; i++){
86077    pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
86078    if( pColl2->xCmp!=0 ){
86079      memcpy(pColl, pColl2, sizeof(CollSeq));
86080      pColl->xDel = 0;         /* Do not copy the destructor */
86081      return SQLITE_OK;
86082    }
86083  }
86084  return SQLITE_ERROR;
86085}
86086
86087/*
86088** This function is responsible for invoking the collation factory callback
86089** or substituting a collation sequence of a different encoding when the
86090** requested collation sequence is not available in the desired encoding.
86091**
86092** If it is not NULL, then pColl must point to the database native encoding
86093** collation sequence with name zName, length nName.
86094**
86095** The return value is either the collation sequence to be used in database
86096** db for collation type name zName, length nName, or NULL, if no collation
86097** sequence can be found.  If no collation is found, leave an error message.
86098**
86099** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
86100*/
86101SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
86102  Parse *pParse,        /* Parsing context */
86103  u8 enc,               /* The desired encoding for the collating sequence */
86104  CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
86105  const char *zName     /* Collating sequence name */
86106){
86107  CollSeq *p;
86108  sqlite3 *db = pParse->db;
86109
86110  p = pColl;
86111  if( !p ){
86112    p = sqlite3FindCollSeq(db, enc, zName, 0);
86113  }
86114  if( !p || !p->xCmp ){
86115    /* No collation sequence of this type for this encoding is registered.
86116    ** Call the collation factory to see if it can supply us with one.
86117    */
86118    callCollNeeded(db, enc, zName);
86119    p = sqlite3FindCollSeq(db, enc, zName, 0);
86120  }
86121  if( p && !p->xCmp && synthCollSeq(db, p) ){
86122    p = 0;
86123  }
86124  assert( !p || p->xCmp );
86125  if( p==0 ){
86126    sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
86127  }
86128  return p;
86129}
86130
86131/*
86132** This routine is called on a collation sequence before it is used to
86133** check that it is defined. An undefined collation sequence exists when
86134** a database is loaded that contains references to collation sequences
86135** that have not been defined by sqlite3_create_collation() etc.
86136**
86137** If required, this routine calls the 'collation needed' callback to
86138** request a definition of the collating sequence. If this doesn't work,
86139** an equivalent collating sequence that uses a text encoding different
86140** from the main database is substituted, if one is available.
86141*/
86142SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
86143  if( pColl ){
86144    const char *zName = pColl->zName;
86145    sqlite3 *db = pParse->db;
86146    CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
86147    if( !p ){
86148      return SQLITE_ERROR;
86149    }
86150    assert( p==pColl );
86151  }
86152  return SQLITE_OK;
86153}
86154
86155
86156
86157/*
86158** Locate and return an entry from the db.aCollSeq hash table. If the entry
86159** specified by zName and nName is not found and parameter 'create' is
86160** true, then create a new entry. Otherwise return NULL.
86161**
86162** Each pointer stored in the sqlite3.aCollSeq hash table contains an
86163** array of three CollSeq structures. The first is the collation sequence
86164** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
86165**
86166** Stored immediately after the three collation sequences is a copy of
86167** the collation sequence name. A pointer to this string is stored in
86168** each collation sequence structure.
86169*/
86170static CollSeq *findCollSeqEntry(
86171  sqlite3 *db,          /* Database connection */
86172  const char *zName,    /* Name of the collating sequence */
86173  int create            /* Create a new entry if true */
86174){
86175  CollSeq *pColl;
86176  int nName = sqlite3Strlen30(zName);
86177  pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
86178
86179  if( 0==pColl && create ){
86180    pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
86181    if( pColl ){
86182      CollSeq *pDel = 0;
86183      pColl[0].zName = (char*)&pColl[3];
86184      pColl[0].enc = SQLITE_UTF8;
86185      pColl[1].zName = (char*)&pColl[3];
86186      pColl[1].enc = SQLITE_UTF16LE;
86187      pColl[2].zName = (char*)&pColl[3];
86188      pColl[2].enc = SQLITE_UTF16BE;
86189      memcpy(pColl[0].zName, zName, nName);
86190      pColl[0].zName[nName] = 0;
86191      pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
86192
86193      /* If a malloc() failure occurred in sqlite3HashInsert(), it will
86194      ** return the pColl pointer to be deleted (because it wasn't added
86195      ** to the hash table).
86196      */
86197      assert( pDel==0 || pDel==pColl );
86198      if( pDel!=0 ){
86199        db->mallocFailed = 1;
86200        sqlite3DbFree(db, pDel);
86201        pColl = 0;
86202      }
86203    }
86204  }
86205  return pColl;
86206}
86207
86208/*
86209** Parameter zName points to a UTF-8 encoded string nName bytes long.
86210** Return the CollSeq* pointer for the collation sequence named zName
86211** for the encoding 'enc' from the database 'db'.
86212**
86213** If the entry specified is not found and 'create' is true, then create a
86214** new entry.  Otherwise return NULL.
86215**
86216** A separate function sqlite3LocateCollSeq() is a wrapper around
86217** this routine.  sqlite3LocateCollSeq() invokes the collation factory
86218** if necessary and generates an error message if the collating sequence
86219** cannot be found.
86220**
86221** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
86222*/
86223SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
86224  sqlite3 *db,
86225  u8 enc,
86226  const char *zName,
86227  int create
86228){
86229  CollSeq *pColl;
86230  if( zName ){
86231    pColl = findCollSeqEntry(db, zName, create);
86232  }else{
86233    pColl = db->pDfltColl;
86234  }
86235  assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
86236  assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
86237  if( pColl ) pColl += enc-1;
86238  return pColl;
86239}
86240
86241/* During the search for the best function definition, this procedure
86242** is called to test how well the function passed as the first argument
86243** matches the request for a function with nArg arguments in a system
86244** that uses encoding enc. The value returned indicates how well the
86245** request is matched. A higher value indicates a better match.
86246**
86247** If nArg is -1 that means to only return a match (non-zero) if p->nArg
86248** is also -1.  In other words, we are searching for a function that
86249** takes a variable number of arguments.
86250**
86251** If nArg is -2 that means that we are searching for any function
86252** regardless of the number of arguments it uses, so return a positive
86253** match score for any
86254**
86255** The returned value is always between 0 and 6, as follows:
86256**
86257** 0: Not a match.
86258** 1: UTF8/16 conversion required and function takes any number of arguments.
86259** 2: UTF16 byte order change required and function takes any number of args.
86260** 3: encoding matches and function takes any number of arguments
86261** 4: UTF8/16 conversion required - argument count matches exactly
86262** 5: UTF16 byte order conversion required - argument count matches exactly
86263** 6: Perfect match:  encoding and argument count match exactly.
86264**
86265** If nArg==(-2) then any function with a non-null xStep or xFunc is
86266** a perfect match and any function with both xStep and xFunc NULL is
86267** a non-match.
86268*/
86269#define FUNC_PERFECT_MATCH 6  /* The score for a perfect match */
86270static int matchQuality(
86271  FuncDef *p,     /* The function we are evaluating for match quality */
86272  int nArg,       /* Desired number of arguments.  (-1)==any */
86273  u8 enc          /* Desired text encoding */
86274){
86275  int match;
86276
86277  /* nArg of -2 is a special case */
86278  if( nArg==(-2) ) return (p->xFunc==0 && p->xStep==0) ? 0 : FUNC_PERFECT_MATCH;
86279
86280  /* Wrong number of arguments means "no match" */
86281  if( p->nArg!=nArg && p->nArg>=0 ) return 0;
86282
86283  /* Give a better score to a function with a specific number of arguments
86284  ** than to function that accepts any number of arguments. */
86285  if( p->nArg==nArg ){
86286    match = 4;
86287  }else{
86288    match = 1;
86289  }
86290
86291  /* Bonus points if the text encoding matches */
86292  if( enc==p->iPrefEnc ){
86293    match += 2;  /* Exact encoding match */
86294  }else if( (enc & p->iPrefEnc & 2)!=0 ){
86295    match += 1;  /* Both are UTF16, but with different byte orders */
86296  }
86297
86298  return match;
86299}
86300
86301/*
86302** Search a FuncDefHash for a function with the given name.  Return
86303** a pointer to the matching FuncDef if found, or 0 if there is no match.
86304*/
86305static FuncDef *functionSearch(
86306  FuncDefHash *pHash,  /* Hash table to search */
86307  int h,               /* Hash of the name */
86308  const char *zFunc,   /* Name of function */
86309  int nFunc            /* Number of bytes in zFunc */
86310){
86311  FuncDef *p;
86312  for(p=pHash->a[h]; p; p=p->pHash){
86313    if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
86314      return p;
86315    }
86316  }
86317  return 0;
86318}
86319
86320/*
86321** Insert a new FuncDef into a FuncDefHash hash table.
86322*/
86323SQLITE_PRIVATE void sqlite3FuncDefInsert(
86324  FuncDefHash *pHash,  /* The hash table into which to insert */
86325  FuncDef *pDef        /* The function definition to insert */
86326){
86327  FuncDef *pOther;
86328  int nName = sqlite3Strlen30(pDef->zName);
86329  u8 c1 = (u8)pDef->zName[0];
86330  int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
86331  pOther = functionSearch(pHash, h, pDef->zName, nName);
86332  if( pOther ){
86333    assert( pOther!=pDef && pOther->pNext!=pDef );
86334    pDef->pNext = pOther->pNext;
86335    pOther->pNext = pDef;
86336  }else{
86337    pDef->pNext = 0;
86338    pDef->pHash = pHash->a[h];
86339    pHash->a[h] = pDef;
86340  }
86341}
86342
86343
86344
86345/*
86346** Locate a user function given a name, a number of arguments and a flag
86347** indicating whether the function prefers UTF-16 over UTF-8.  Return a
86348** pointer to the FuncDef structure that defines that function, or return
86349** NULL if the function does not exist.
86350**
86351** If the createFlag argument is true, then a new (blank) FuncDef
86352** structure is created and liked into the "db" structure if a
86353** no matching function previously existed.
86354**
86355** If nArg is -2, then the first valid function found is returned.  A
86356** function is valid if either xFunc or xStep is non-zero.  The nArg==(-2)
86357** case is used to see if zName is a valid function name for some number
86358** of arguments.  If nArg is -2, then createFlag must be 0.
86359**
86360** If createFlag is false, then a function with the required name and
86361** number of arguments may be returned even if the eTextRep flag does not
86362** match that requested.
86363*/
86364SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
86365  sqlite3 *db,       /* An open database */
86366  const char *zName, /* Name of the function.  Not null-terminated */
86367  int nName,         /* Number of characters in the name */
86368  int nArg,          /* Number of arguments.  -1 means any number */
86369  u8 enc,            /* Preferred text encoding */
86370  u8 createFlag      /* Create new entry if true and does not otherwise exist */
86371){
86372  FuncDef *p;         /* Iterator variable */
86373  FuncDef *pBest = 0; /* Best match found so far */
86374  int bestScore = 0;  /* Score of best match */
86375  int h;              /* Hash value */
86376
86377  assert( nArg>=(-2) );
86378  assert( nArg>=(-1) || createFlag==0 );
86379  assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
86380  h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
86381
86382  /* First search for a match amongst the application-defined functions.
86383  */
86384  p = functionSearch(&db->aFunc, h, zName, nName);
86385  while( p ){
86386    int score = matchQuality(p, nArg, enc);
86387    if( score>bestScore ){
86388      pBest = p;
86389      bestScore = score;
86390    }
86391    p = p->pNext;
86392  }
86393
86394  /* If no match is found, search the built-in functions.
86395  **
86396  ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
86397  ** functions even if a prior app-defined function was found.  And give
86398  ** priority to built-in functions.
86399  **
86400  ** Except, if createFlag is true, that means that we are trying to
86401  ** install a new function.  Whatever FuncDef structure is returned it will
86402  ** have fields overwritten with new information appropriate for the
86403  ** new function.  But the FuncDefs for built-in functions are read-only.
86404  ** So we must not search for built-ins when creating a new function.
86405  */
86406  if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
86407    FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
86408    bestScore = 0;
86409    p = functionSearch(pHash, h, zName, nName);
86410    while( p ){
86411      int score = matchQuality(p, nArg, enc);
86412      if( score>bestScore ){
86413        pBest = p;
86414        bestScore = score;
86415      }
86416      p = p->pNext;
86417    }
86418  }
86419
86420  /* If the createFlag parameter is true and the search did not reveal an
86421  ** exact match for the name, number of arguments and encoding, then add a
86422  ** new entry to the hash table and return it.
86423  */
86424  if( createFlag && bestScore<FUNC_PERFECT_MATCH &&
86425      (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
86426    pBest->zName = (char *)&pBest[1];
86427    pBest->nArg = (u16)nArg;
86428    pBest->iPrefEnc = enc;
86429    memcpy(pBest->zName, zName, nName);
86430    pBest->zName[nName] = 0;
86431    sqlite3FuncDefInsert(&db->aFunc, pBest);
86432  }
86433
86434  if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
86435    return pBest;
86436  }
86437  return 0;
86438}
86439
86440/*
86441** Free all resources held by the schema structure. The void* argument points
86442** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
86443** pointer itself, it just cleans up subsidiary resources (i.e. the contents
86444** of the schema hash tables).
86445**
86446** The Schema.cache_size variable is not cleared.
86447*/
86448SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
86449  Hash temp1;
86450  Hash temp2;
86451  HashElem *pElem;
86452  Schema *pSchema = (Schema *)p;
86453
86454  temp1 = pSchema->tblHash;
86455  temp2 = pSchema->trigHash;
86456  sqlite3HashInit(&pSchema->trigHash);
86457  sqlite3HashClear(&pSchema->idxHash);
86458  for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
86459    sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
86460  }
86461  sqlite3HashClear(&temp2);
86462  sqlite3HashInit(&pSchema->tblHash);
86463  for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
86464    Table *pTab = sqliteHashData(pElem);
86465    sqlite3DeleteTable(0, pTab);
86466  }
86467  sqlite3HashClear(&temp1);
86468  sqlite3HashClear(&pSchema->fkeyHash);
86469  pSchema->pSeqTab = 0;
86470  if( pSchema->flags & DB_SchemaLoaded ){
86471    pSchema->iGeneration++;
86472    pSchema->flags &= ~DB_SchemaLoaded;
86473  }
86474}
86475
86476/*
86477** Find and return the schema associated with a BTree.  Create
86478** a new one if necessary.
86479*/
86480SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
86481  Schema * p;
86482  if( pBt ){
86483    p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
86484  }else{
86485    p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
86486  }
86487  if( !p ){
86488    db->mallocFailed = 1;
86489  }else if ( 0==p->file_format ){
86490    sqlite3HashInit(&p->tblHash);
86491    sqlite3HashInit(&p->idxHash);
86492    sqlite3HashInit(&p->trigHash);
86493    sqlite3HashInit(&p->fkeyHash);
86494    p->enc = SQLITE_UTF8;
86495  }
86496  return p;
86497}
86498
86499/************** End of callback.c ********************************************/
86500/************** Begin file delete.c ******************************************/
86501/*
86502** 2001 September 15
86503**
86504** The author disclaims copyright to this source code.  In place of
86505** a legal notice, here is a blessing:
86506**
86507**    May you do good and not evil.
86508**    May you find forgiveness for yourself and forgive others.
86509**    May you share freely, never taking more than you give.
86510**
86511*************************************************************************
86512** This file contains C code routines that are called by the parser
86513** in order to generate code for DELETE FROM statements.
86514*/
86515
86516/*
86517** While a SrcList can in general represent multiple tables and subqueries
86518** (as in the FROM clause of a SELECT statement) in this case it contains
86519** the name of a single table, as one might find in an INSERT, DELETE,
86520** or UPDATE statement.  Look up that table in the symbol table and
86521** return a pointer.  Set an error message and return NULL if the table
86522** name is not found or if any other error occurs.
86523**
86524** The following fields are initialized appropriate in pSrc:
86525**
86526**    pSrc->a[0].pTab       Pointer to the Table object
86527**    pSrc->a[0].pIndex     Pointer to the INDEXED BY index, if there is one
86528**
86529*/
86530SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
86531  struct SrcList_item *pItem = pSrc->a;
86532  Table *pTab;
86533  assert( pItem && pSrc->nSrc==1 );
86534  pTab = sqlite3LocateTableItem(pParse, 0, pItem);
86535  sqlite3DeleteTable(pParse->db, pItem->pTab);
86536  pItem->pTab = pTab;
86537  if( pTab ){
86538    pTab->nRef++;
86539  }
86540  if( sqlite3IndexedByLookup(pParse, pItem) ){
86541    pTab = 0;
86542  }
86543  return pTab;
86544}
86545
86546/*
86547** Check to make sure the given table is writable.  If it is not
86548** writable, generate an error message and return 1.  If it is
86549** writable return 0;
86550*/
86551SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
86552  /* A table is not writable under the following circumstances:
86553  **
86554  **   1) It is a virtual table and no implementation of the xUpdate method
86555  **      has been provided, or
86556  **   2) It is a system table (i.e. sqlite_master), this call is not
86557  **      part of a nested parse and writable_schema pragma has not
86558  **      been specified.
86559  **
86560  ** In either case leave an error message in pParse and return non-zero.
86561  */
86562  if( ( IsVirtual(pTab)
86563     && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
86564   || ( (pTab->tabFlags & TF_Readonly)!=0
86565     && (pParse->db->flags & SQLITE_WriteSchema)==0
86566     && pParse->nested==0 )
86567  ){
86568    sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
86569    return 1;
86570  }
86571
86572#ifndef SQLITE_OMIT_VIEW
86573  if( !viewOk && pTab->pSelect ){
86574    sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
86575    return 1;
86576  }
86577#endif
86578  return 0;
86579}
86580
86581
86582#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
86583/*
86584** Evaluate a view and store its result in an ephemeral table.  The
86585** pWhere argument is an optional WHERE clause that restricts the
86586** set of rows in the view that are to be added to the ephemeral table.
86587*/
86588SQLITE_PRIVATE void sqlite3MaterializeView(
86589  Parse *pParse,       /* Parsing context */
86590  Table *pView,        /* View definition */
86591  Expr *pWhere,        /* Optional WHERE clause to be added */
86592  int iCur             /* Cursor number for ephemerial table */
86593){
86594  SelectDest dest;
86595  Select *pSel;
86596  SrcList *pFrom;
86597  sqlite3 *db = pParse->db;
86598  int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
86599
86600  pWhere = sqlite3ExprDup(db, pWhere, 0);
86601  pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
86602
86603  if( pFrom ){
86604    assert( pFrom->nSrc==1 );
86605    pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
86606    pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
86607    assert( pFrom->a[0].pOn==0 );
86608    assert( pFrom->a[0].pUsing==0 );
86609  }
86610
86611  pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
86612  if( pSel ) pSel->selFlags |= SF_Materialize;
86613
86614  sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
86615  sqlite3Select(pParse, pSel, &dest);
86616  sqlite3SelectDelete(db, pSel);
86617}
86618#endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
86619
86620#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
86621/*
86622** Generate an expression tree to implement the WHERE, ORDER BY,
86623** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
86624**
86625**     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
86626**                            \__________________________/
86627**                               pLimitWhere (pInClause)
86628*/
86629SQLITE_PRIVATE Expr *sqlite3LimitWhere(
86630  Parse *pParse,               /* The parser context */
86631  SrcList *pSrc,               /* the FROM clause -- which tables to scan */
86632  Expr *pWhere,                /* The WHERE clause.  May be null */
86633  ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
86634  Expr *pLimit,                /* The LIMIT clause.  May be null */
86635  Expr *pOffset,               /* The OFFSET clause.  May be null */
86636  char *zStmtType              /* Either DELETE or UPDATE.  For error messages. */
86637){
86638  Expr *pWhereRowid = NULL;    /* WHERE rowid .. */
86639  Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
86640  Expr *pSelectRowid = NULL;   /* SELECT rowid ... */
86641  ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
86642  SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
86643  Select *pSelect = NULL;      /* Complete SELECT tree */
86644
86645  /* Check that there isn't an ORDER BY without a LIMIT clause.
86646  */
86647  if( pOrderBy && (pLimit == 0) ) {
86648    sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
86649    goto limit_where_cleanup_2;
86650  }
86651
86652  /* We only need to generate a select expression if there
86653  ** is a limit/offset term to enforce.
86654  */
86655  if( pLimit == 0 ) {
86656    /* if pLimit is null, pOffset will always be null as well. */
86657    assert( pOffset == 0 );
86658    return pWhere;
86659  }
86660
86661  /* Generate a select expression tree to enforce the limit/offset
86662  ** term for the DELETE or UPDATE statement.  For example:
86663  **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
86664  ** becomes:
86665  **   DELETE FROM table_a WHERE rowid IN (
86666  **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
86667  **   );
86668  */
86669
86670  pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
86671  if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
86672  pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
86673  if( pEList == 0 ) goto limit_where_cleanup_2;
86674
86675  /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
86676  ** and the SELECT subtree. */
86677  pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
86678  if( pSelectSrc == 0 ) {
86679    sqlite3ExprListDelete(pParse->db, pEList);
86680    goto limit_where_cleanup_2;
86681  }
86682
86683  /* generate the SELECT expression tree. */
86684  pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
86685                             pOrderBy,0,pLimit,pOffset);
86686  if( pSelect == 0 ) return 0;
86687
86688  /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
86689  pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
86690  if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
86691  pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
86692  if( pInClause == 0 ) goto limit_where_cleanup_1;
86693
86694  pInClause->x.pSelect = pSelect;
86695  pInClause->flags |= EP_xIsSelect;
86696  sqlite3ExprSetHeight(pParse, pInClause);
86697  return pInClause;
86698
86699  /* something went wrong. clean up anything allocated. */
86700limit_where_cleanup_1:
86701  sqlite3SelectDelete(pParse->db, pSelect);
86702  return 0;
86703
86704limit_where_cleanup_2:
86705  sqlite3ExprDelete(pParse->db, pWhere);
86706  sqlite3ExprListDelete(pParse->db, pOrderBy);
86707  sqlite3ExprDelete(pParse->db, pLimit);
86708  sqlite3ExprDelete(pParse->db, pOffset);
86709  return 0;
86710}
86711#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
86712
86713/*
86714** Generate code for a DELETE FROM statement.
86715**
86716**     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
86717**                 \________/       \________________/
86718**                  pTabList              pWhere
86719*/
86720SQLITE_PRIVATE void sqlite3DeleteFrom(
86721  Parse *pParse,         /* The parser context */
86722  SrcList *pTabList,     /* The table from which we should delete things */
86723  Expr *pWhere           /* The WHERE clause.  May be null */
86724){
86725  Vdbe *v;               /* The virtual database engine */
86726  Table *pTab;           /* The table from which records will be deleted */
86727  const char *zDb;       /* Name of database holding pTab */
86728  int end, addr = 0;     /* A couple addresses of generated code */
86729  int i;                 /* Loop counter */
86730  WhereInfo *pWInfo;     /* Information about the WHERE clause */
86731  Index *pIdx;           /* For looping over indices of the table */
86732  int iCur;              /* VDBE Cursor number for pTab */
86733  sqlite3 *db;           /* Main database structure */
86734  AuthContext sContext;  /* Authorization context */
86735  NameContext sNC;       /* Name context to resolve expressions in */
86736  int iDb;               /* Database number */
86737  int memCnt = -1;       /* Memory cell used for change counting */
86738  int rcauth;            /* Value returned by authorization callback */
86739
86740#ifndef SQLITE_OMIT_TRIGGER
86741  int isView;                  /* True if attempting to delete from a view */
86742  Trigger *pTrigger;           /* List of table triggers, if required */
86743#endif
86744
86745  memset(&sContext, 0, sizeof(sContext));
86746  db = pParse->db;
86747  if( pParse->nErr || db->mallocFailed ){
86748    goto delete_from_cleanup;
86749  }
86750  assert( pTabList->nSrc==1 );
86751
86752  /* Locate the table which we want to delete.  This table has to be
86753  ** put in an SrcList structure because some of the subroutines we
86754  ** will be calling are designed to work with multiple tables and expect
86755  ** an SrcList* parameter instead of just a Table* parameter.
86756  */
86757  pTab = sqlite3SrcListLookup(pParse, pTabList);
86758  if( pTab==0 )  goto delete_from_cleanup;
86759
86760  /* Figure out if we have any triggers and if the table being
86761  ** deleted from is a view
86762  */
86763#ifndef SQLITE_OMIT_TRIGGER
86764  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
86765  isView = pTab->pSelect!=0;
86766#else
86767# define pTrigger 0
86768# define isView 0
86769#endif
86770#ifdef SQLITE_OMIT_VIEW
86771# undef isView
86772# define isView 0
86773#endif
86774
86775  /* If pTab is really a view, make sure it has been initialized.
86776  */
86777  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
86778    goto delete_from_cleanup;
86779  }
86780
86781  if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
86782    goto delete_from_cleanup;
86783  }
86784  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
86785  assert( iDb<db->nDb );
86786  zDb = db->aDb[iDb].zName;
86787  rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
86788  assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
86789  if( rcauth==SQLITE_DENY ){
86790    goto delete_from_cleanup;
86791  }
86792  assert(!isView || pTrigger);
86793
86794  /* Assign  cursor number to the table and all its indices.
86795  */
86796  assert( pTabList->nSrc==1 );
86797  iCur = pTabList->a[0].iCursor = pParse->nTab++;
86798  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
86799    pParse->nTab++;
86800  }
86801
86802  /* Start the view context
86803  */
86804  if( isView ){
86805    sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
86806  }
86807
86808  /* Begin generating code.
86809  */
86810  v = sqlite3GetVdbe(pParse);
86811  if( v==0 ){
86812    goto delete_from_cleanup;
86813  }
86814  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
86815  sqlite3BeginWriteOperation(pParse, 1, iDb);
86816
86817  /* If we are trying to delete from a view, realize that view into
86818  ** a ephemeral table.
86819  */
86820#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
86821  if( isView ){
86822    sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
86823  }
86824#endif
86825
86826  /* Resolve the column names in the WHERE clause.
86827  */
86828  memset(&sNC, 0, sizeof(sNC));
86829  sNC.pParse = pParse;
86830  sNC.pSrcList = pTabList;
86831  if( sqlite3ResolveExprNames(&sNC, pWhere) ){
86832    goto delete_from_cleanup;
86833  }
86834
86835  /* Initialize the counter of the number of rows deleted, if
86836  ** we are counting rows.
86837  */
86838  if( db->flags & SQLITE_CountRows ){
86839    memCnt = ++pParse->nMem;
86840    sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
86841  }
86842
86843#ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
86844  /* Special case: A DELETE without a WHERE clause deletes everything.
86845  ** It is easier just to erase the whole table. Prior to version 3.6.5,
86846  ** this optimization caused the row change count (the value returned by
86847  ** API function sqlite3_count_changes) to be set incorrectly.  */
86848  if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab)
86849   && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
86850  ){
86851    assert( !isView );
86852    sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
86853                      pTab->zName, P4_STATIC);
86854    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
86855      assert( pIdx->pSchema==pTab->pSchema );
86856      sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
86857    }
86858  }else
86859#endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
86860  /* The usual case: There is a WHERE clause so we have to scan through
86861  ** the table and pick which records to delete.
86862  */
86863  {
86864    int iRowSet = ++pParse->nMem;   /* Register for rowset of rows to delete */
86865    int iRowid = ++pParse->nMem;    /* Used for storing rowid values. */
86866    int regRowid;                   /* Actual register containing rowids */
86867
86868    /* Collect rowids of every row to be deleted.
86869    */
86870    sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
86871    pWInfo = sqlite3WhereBegin(
86872        pParse, pTabList, pWhere, 0, 0, WHERE_DUPLICATES_OK, 0
86873    );
86874    if( pWInfo==0 ) goto delete_from_cleanup;
86875    regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid, 0);
86876    sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
86877    if( db->flags & SQLITE_CountRows ){
86878      sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
86879    }
86880    sqlite3WhereEnd(pWInfo);
86881
86882    /* Delete every item whose key was written to the list during the
86883    ** database scan.  We have to delete items after the scan is complete
86884    ** because deleting an item can change the scan order.  */
86885    end = sqlite3VdbeMakeLabel(v);
86886
86887    /* Unless this is a view, open cursors for the table we are
86888    ** deleting from and all its indices. If this is a view, then the
86889    ** only effect this statement has is to fire the INSTEAD OF
86890    ** triggers.  */
86891    if( !isView ){
86892      sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
86893    }
86894
86895    addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);
86896
86897    /* Delete the row */
86898#ifndef SQLITE_OMIT_VIRTUALTABLE
86899    if( IsVirtual(pTab) ){
86900      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
86901      sqlite3VtabMakeWritable(pParse, pTab);
86902      sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB);
86903      sqlite3VdbeChangeP5(v, OE_Abort);
86904      sqlite3MayAbort(pParse);
86905    }else
86906#endif
86907    {
86908      int count = (pParse->nested==0);    /* True to count changes */
86909      sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default);
86910    }
86911
86912    /* End of the delete loop */
86913    sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
86914    sqlite3VdbeResolveLabel(v, end);
86915
86916    /* Close the cursors open on the table and its indexes. */
86917    if( !isView && !IsVirtual(pTab) ){
86918      for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
86919        sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
86920      }
86921      sqlite3VdbeAddOp1(v, OP_Close, iCur);
86922    }
86923  }
86924
86925  /* Update the sqlite_sequence table by storing the content of the
86926  ** maximum rowid counter values recorded while inserting into
86927  ** autoincrement tables.
86928  */
86929  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
86930    sqlite3AutoincrementEnd(pParse);
86931  }
86932
86933  /* Return the number of rows that were deleted. If this routine is
86934  ** generating code because of a call to sqlite3NestedParse(), do not
86935  ** invoke the callback function.
86936  */
86937  if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
86938    sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
86939    sqlite3VdbeSetNumCols(v, 1);
86940    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
86941  }
86942
86943delete_from_cleanup:
86944  sqlite3AuthContextPop(&sContext);
86945  sqlite3SrcListDelete(db, pTabList);
86946  sqlite3ExprDelete(db, pWhere);
86947  return;
86948}
86949/* Make sure "isView" and other macros defined above are undefined. Otherwise
86950** thely may interfere with compilation of other functions in this file
86951** (or in another file, if this file becomes part of the amalgamation).  */
86952#ifdef isView
86953 #undef isView
86954#endif
86955#ifdef pTrigger
86956 #undef pTrigger
86957#endif
86958
86959/*
86960** This routine generates VDBE code that causes a single row of a
86961** single table to be deleted.
86962**
86963** The VDBE must be in a particular state when this routine is called.
86964** These are the requirements:
86965**
86966**   1.  A read/write cursor pointing to pTab, the table containing the row
86967**       to be deleted, must be opened as cursor number $iCur.
86968**
86969**   2.  Read/write cursors for all indices of pTab must be open as
86970**       cursor number base+i for the i-th index.
86971**
86972**   3.  The record number of the row to be deleted must be stored in
86973**       memory cell iRowid.
86974**
86975** This routine generates code to remove both the table record and all
86976** index entries that point to that record.
86977*/
86978SQLITE_PRIVATE void sqlite3GenerateRowDelete(
86979  Parse *pParse,     /* Parsing context */
86980  Table *pTab,       /* Table containing the row to be deleted */
86981  int iCur,          /* Cursor number for the table */
86982  int iRowid,        /* Memory cell that contains the rowid to delete */
86983  int count,         /* If non-zero, increment the row change counter */
86984  Trigger *pTrigger, /* List of triggers to (potentially) fire */
86985  int onconf         /* Default ON CONFLICT policy for triggers */
86986){
86987  Vdbe *v = pParse->pVdbe;        /* Vdbe */
86988  int iOld = 0;                   /* First register in OLD.* array */
86989  int iLabel;                     /* Label resolved to end of generated code */
86990
86991  /* Vdbe is guaranteed to have been allocated by this stage. */
86992  assert( v );
86993
86994  /* Seek cursor iCur to the row to delete. If this row no longer exists
86995  ** (this can happen if a trigger program has already deleted it), do
86996  ** not attempt to delete it or fire any DELETE triggers.  */
86997  iLabel = sqlite3VdbeMakeLabel(v);
86998  sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
86999
87000  /* If there are any triggers to fire, allocate a range of registers to
87001  ** use for the old.* references in the triggers.  */
87002  if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
87003    u32 mask;                     /* Mask of OLD.* columns in use */
87004    int iCol;                     /* Iterator used while populating OLD.* */
87005
87006    /* TODO: Could use temporary registers here. Also could attempt to
87007    ** avoid copying the contents of the rowid register.  */
87008    mask = sqlite3TriggerColmask(
87009        pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
87010    );
87011    mask |= sqlite3FkOldmask(pParse, pTab);
87012    iOld = pParse->nMem+1;
87013    pParse->nMem += (1 + pTab->nCol);
87014
87015    /* Populate the OLD.* pseudo-table register array. These values will be
87016    ** used by any BEFORE and AFTER triggers that exist.  */
87017    sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld);
87018    for(iCol=0; iCol<pTab->nCol; iCol++){
87019      if( mask==0xffffffff || mask&(1<<iCol) ){
87020        sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol, iOld+iCol+1);
87021      }
87022    }
87023
87024    /* Invoke BEFORE DELETE trigger programs. */
87025    sqlite3CodeRowTrigger(pParse, pTrigger,
87026        TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
87027    );
87028
87029    /* Seek the cursor to the row to be deleted again. It may be that
87030    ** the BEFORE triggers coded above have already removed the row
87031    ** being deleted. Do not attempt to delete the row a second time, and
87032    ** do not fire AFTER triggers.  */
87033    sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
87034
87035    /* Do FK processing. This call checks that any FK constraints that
87036    ** refer to this table (i.e. constraints attached to other tables)
87037    ** are not violated by deleting this row.  */
87038    sqlite3FkCheck(pParse, pTab, iOld, 0);
87039  }
87040
87041  /* Delete the index and table entries. Skip this step if pTab is really
87042  ** a view (in which case the only effect of the DELETE statement is to
87043  ** fire the INSTEAD OF triggers).  */
87044  if( pTab->pSelect==0 ){
87045    sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
87046    sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
87047    if( count ){
87048      sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
87049    }
87050  }
87051
87052  /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
87053  ** handle rows (possibly in other tables) that refer via a foreign key
87054  ** to the row just deleted. */
87055  sqlite3FkActions(pParse, pTab, 0, iOld);
87056
87057  /* Invoke AFTER DELETE trigger programs. */
87058  sqlite3CodeRowTrigger(pParse, pTrigger,
87059      TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
87060  );
87061
87062  /* Jump here if the row had already been deleted before any BEFORE
87063  ** trigger programs were invoked. Or if a trigger program throws a
87064  ** RAISE(IGNORE) exception.  */
87065  sqlite3VdbeResolveLabel(v, iLabel);
87066}
87067
87068/*
87069** This routine generates VDBE code that causes the deletion of all
87070** index entries associated with a single row of a single table.
87071**
87072** The VDBE must be in a particular state when this routine is called.
87073** These are the requirements:
87074**
87075**   1.  A read/write cursor pointing to pTab, the table containing the row
87076**       to be deleted, must be opened as cursor number "iCur".
87077**
87078**   2.  Read/write cursors for all indices of pTab must be open as
87079**       cursor number iCur+i for the i-th index.
87080**
87081**   3.  The "iCur" cursor must be pointing to the row that is to be
87082**       deleted.
87083*/
87084SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
87085  Parse *pParse,     /* Parsing and code generating context */
87086  Table *pTab,       /* Table containing the row to be deleted */
87087  int iCur,          /* Cursor number for the table */
87088  int *aRegIdx       /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
87089){
87090  int i;
87091  Index *pIdx;
87092  int r1;
87093
87094  for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
87095    if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
87096    r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0);
87097    sqlite3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1);
87098  }
87099}
87100
87101/*
87102** Generate code that will assemble an index key and put it in register
87103** regOut.  The key with be for index pIdx which is an index on pTab.
87104** iCur is the index of a cursor open on the pTab table and pointing to
87105** the entry that needs indexing.
87106**
87107** Return a register number which is the first in a block of
87108** registers that holds the elements of the index key.  The
87109** block of registers has already been deallocated by the time
87110** this routine returns.
87111*/
87112SQLITE_PRIVATE int sqlite3GenerateIndexKey(
87113  Parse *pParse,     /* Parsing context */
87114  Index *pIdx,       /* The index for which to generate a key */
87115  int iCur,          /* Cursor number for the pIdx->pTable table */
87116  int regOut,        /* Write the new index key to this register */
87117  int doMakeRec      /* Run the OP_MakeRecord instruction if true */
87118){
87119  Vdbe *v = pParse->pVdbe;
87120  int j;
87121  Table *pTab = pIdx->pTable;
87122  int regBase;
87123  int nCol;
87124
87125  nCol = pIdx->nColumn;
87126  regBase = sqlite3GetTempRange(pParse, nCol+1);
87127  sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
87128  for(j=0; j<nCol; j++){
87129    int idx = pIdx->aiColumn[j];
87130    if( idx==pTab->iPKey ){
87131      sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
87132    }else{
87133      sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
87134      sqlite3ColumnDefault(v, pTab, idx, -1);
87135    }
87136  }
87137  if( doMakeRec ){
87138    const char *zAff;
87139    if( pTab->pSelect
87140     || OptimizationDisabled(pParse->db, SQLITE_IdxRealAsInt)
87141    ){
87142      zAff = 0;
87143    }else{
87144      zAff = sqlite3IndexAffinityStr(v, pIdx);
87145    }
87146    sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
87147    sqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT);
87148  }
87149  sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
87150  return regBase;
87151}
87152
87153/************** End of delete.c **********************************************/
87154/************** Begin file func.c ********************************************/
87155/*
87156** 2002 February 23
87157**
87158** The author disclaims copyright to this source code.  In place of
87159** a legal notice, here is a blessing:
87160**
87161**    May you do good and not evil.
87162**    May you find forgiveness for yourself and forgive others.
87163**    May you share freely, never taking more than you give.
87164**
87165*************************************************************************
87166** This file contains the C functions that implement various SQL
87167** functions of SQLite.
87168**
87169** There is only one exported symbol in this file - the function
87170** sqliteRegisterBuildinFunctions() found at the bottom of the file.
87171** All other code has file scope.
87172*/
87173/* #include <stdlib.h> */
87174/* #include <assert.h> */
87175
87176/*
87177** Return the collating function associated with a function.
87178*/
87179static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
87180  return context->pColl;
87181}
87182
87183/*
87184** Indicate that the accumulator load should be skipped on this
87185** iteration of the aggregate loop.
87186*/
87187static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
87188  context->skipFlag = 1;
87189}
87190
87191/*
87192** Implementation of the non-aggregate min() and max() functions
87193*/
87194static void minmaxFunc(
87195  sqlite3_context *context,
87196  int argc,
87197  sqlite3_value **argv
87198){
87199  int i;
87200  int mask;    /* 0 for min() or 0xffffffff for max() */
87201  int iBest;
87202  CollSeq *pColl;
87203
87204  assert( argc>1 );
87205  mask = sqlite3_user_data(context)==0 ? 0 : -1;
87206  pColl = sqlite3GetFuncCollSeq(context);
87207  assert( pColl );
87208  assert( mask==-1 || mask==0 );
87209  iBest = 0;
87210  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
87211  for(i=1; i<argc; i++){
87212    if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
87213    if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
87214      testcase( mask==0 );
87215      iBest = i;
87216    }
87217  }
87218  sqlite3_result_value(context, argv[iBest]);
87219}
87220
87221/*
87222** Return the type of the argument.
87223*/
87224static void typeofFunc(
87225  sqlite3_context *context,
87226  int NotUsed,
87227  sqlite3_value **argv
87228){
87229  const char *z = 0;
87230  UNUSED_PARAMETER(NotUsed);
87231  switch( sqlite3_value_type(argv[0]) ){
87232    case SQLITE_INTEGER: z = "integer"; break;
87233    case SQLITE_TEXT:    z = "text";    break;
87234    case SQLITE_FLOAT:   z = "real";    break;
87235    case SQLITE_BLOB:    z = "blob";    break;
87236    default:             z = "null";    break;
87237  }
87238  sqlite3_result_text(context, z, -1, SQLITE_STATIC);
87239}
87240
87241
87242/*
87243** Implementation of the length() function
87244*/
87245static void lengthFunc(
87246  sqlite3_context *context,
87247  int argc,
87248  sqlite3_value **argv
87249){
87250  int len;
87251
87252  assert( argc==1 );
87253  UNUSED_PARAMETER(argc);
87254  switch( sqlite3_value_type(argv[0]) ){
87255    case SQLITE_BLOB:
87256    case SQLITE_INTEGER:
87257    case SQLITE_FLOAT: {
87258      sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
87259      break;
87260    }
87261    case SQLITE_TEXT: {
87262      const unsigned char *z = sqlite3_value_text(argv[0]);
87263      if( z==0 ) return;
87264      len = 0;
87265      while( *z ){
87266        len++;
87267        SQLITE_SKIP_UTF8(z);
87268      }
87269      sqlite3_result_int(context, len);
87270      break;
87271    }
87272    default: {
87273      sqlite3_result_null(context);
87274      break;
87275    }
87276  }
87277}
87278
87279/*
87280** Implementation of the abs() function.
87281**
87282** IMP: R-23979-26855 The abs(X) function returns the absolute value of
87283** the numeric argument X.
87284*/
87285static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
87286  assert( argc==1 );
87287  UNUSED_PARAMETER(argc);
87288  switch( sqlite3_value_type(argv[0]) ){
87289    case SQLITE_INTEGER: {
87290      i64 iVal = sqlite3_value_int64(argv[0]);
87291      if( iVal<0 ){
87292        if( (iVal<<1)==0 ){
87293          /* IMP: R-35460-15084 If X is the integer -9223372036854775807 then
87294          ** abs(X) throws an integer overflow error since there is no
87295          ** equivalent positive 64-bit two complement value. */
87296          sqlite3_result_error(context, "integer overflow", -1);
87297          return;
87298        }
87299        iVal = -iVal;
87300      }
87301      sqlite3_result_int64(context, iVal);
87302      break;
87303    }
87304    case SQLITE_NULL: {
87305      /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
87306      sqlite3_result_null(context);
87307      break;
87308    }
87309    default: {
87310      /* Because sqlite3_value_double() returns 0.0 if the argument is not
87311      ** something that can be converted into a number, we have:
87312      ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
87313      ** cannot be converted to a numeric value.
87314      */
87315      double rVal = sqlite3_value_double(argv[0]);
87316      if( rVal<0 ) rVal = -rVal;
87317      sqlite3_result_double(context, rVal);
87318      break;
87319    }
87320  }
87321}
87322
87323/*
87324** Implementation of the instr() function.
87325**
87326** instr(haystack,needle) finds the first occurrence of needle
87327** in haystack and returns the number of previous characters plus 1,
87328** or 0 if needle does not occur within haystack.
87329**
87330** If both haystack and needle are BLOBs, then the result is one more than
87331** the number of bytes in haystack prior to the first occurrence of needle,
87332** or 0 if needle never occurs in haystack.
87333*/
87334static void instrFunc(
87335  sqlite3_context *context,
87336  int argc,
87337  sqlite3_value **argv
87338){
87339  const unsigned char *zHaystack;
87340  const unsigned char *zNeedle;
87341  int nHaystack;
87342  int nNeedle;
87343  int typeHaystack, typeNeedle;
87344  int N = 1;
87345  int isText;
87346
87347  UNUSED_PARAMETER(argc);
87348  typeHaystack = sqlite3_value_type(argv[0]);
87349  typeNeedle = sqlite3_value_type(argv[1]);
87350  if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
87351  nHaystack = sqlite3_value_bytes(argv[0]);
87352  nNeedle = sqlite3_value_bytes(argv[1]);
87353  if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
87354    zHaystack = sqlite3_value_blob(argv[0]);
87355    zNeedle = sqlite3_value_blob(argv[1]);
87356    isText = 0;
87357  }else{
87358    zHaystack = sqlite3_value_text(argv[0]);
87359    zNeedle = sqlite3_value_text(argv[1]);
87360    isText = 1;
87361  }
87362  while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){
87363    N++;
87364    do{
87365      nHaystack--;
87366      zHaystack++;
87367    }while( isText && (zHaystack[0]&0xc0)==0x80 );
87368  }
87369  if( nNeedle>nHaystack ) N = 0;
87370  sqlite3_result_int(context, N);
87371}
87372
87373/*
87374** Implementation of the substr() function.
87375**
87376** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
87377** p1 is 1-indexed.  So substr(x,1,1) returns the first character
87378** of x.  If x is text, then we actually count UTF-8 characters.
87379** If x is a blob, then we count bytes.
87380**
87381** If p1 is negative, then we begin abs(p1) from the end of x[].
87382**
87383** If p2 is negative, return the p2 characters preceeding p1.
87384*/
87385static void substrFunc(
87386  sqlite3_context *context,
87387  int argc,
87388  sqlite3_value **argv
87389){
87390  const unsigned char *z;
87391  const unsigned char *z2;
87392  int len;
87393  int p0type;
87394  i64 p1, p2;
87395  int negP2 = 0;
87396
87397  assert( argc==3 || argc==2 );
87398  if( sqlite3_value_type(argv[1])==SQLITE_NULL
87399   || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
87400  ){
87401    return;
87402  }
87403  p0type = sqlite3_value_type(argv[0]);
87404  p1 = sqlite3_value_int(argv[1]);
87405  if( p0type==SQLITE_BLOB ){
87406    len = sqlite3_value_bytes(argv[0]);
87407    z = sqlite3_value_blob(argv[0]);
87408    if( z==0 ) return;
87409    assert( len==sqlite3_value_bytes(argv[0]) );
87410  }else{
87411    z = sqlite3_value_text(argv[0]);
87412    if( z==0 ) return;
87413    len = 0;
87414    if( p1<0 ){
87415      for(z2=z; *z2; len++){
87416        SQLITE_SKIP_UTF8(z2);
87417      }
87418    }
87419  }
87420  if( argc==3 ){
87421    p2 = sqlite3_value_int(argv[2]);
87422    if( p2<0 ){
87423      p2 = -p2;
87424      negP2 = 1;
87425    }
87426  }else{
87427    p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
87428  }
87429  if( p1<0 ){
87430    p1 += len;
87431    if( p1<0 ){
87432      p2 += p1;
87433      if( p2<0 ) p2 = 0;
87434      p1 = 0;
87435    }
87436  }else if( p1>0 ){
87437    p1--;
87438  }else if( p2>0 ){
87439    p2--;
87440  }
87441  if( negP2 ){
87442    p1 -= p2;
87443    if( p1<0 ){
87444      p2 += p1;
87445      p1 = 0;
87446    }
87447  }
87448  assert( p1>=0 && p2>=0 );
87449  if( p0type!=SQLITE_BLOB ){
87450    while( *z && p1 ){
87451      SQLITE_SKIP_UTF8(z);
87452      p1--;
87453    }
87454    for(z2=z; *z2 && p2; p2--){
87455      SQLITE_SKIP_UTF8(z2);
87456    }
87457    sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
87458  }else{
87459    if( p1+p2>len ){
87460      p2 = len-p1;
87461      if( p2<0 ) p2 = 0;
87462    }
87463    sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
87464  }
87465}
87466
87467/*
87468** Implementation of the round() function
87469*/
87470#ifndef SQLITE_OMIT_FLOATING_POINT
87471static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
87472  int n = 0;
87473  double r;
87474  char *zBuf;
87475  assert( argc==1 || argc==2 );
87476  if( argc==2 ){
87477    if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
87478    n = sqlite3_value_int(argv[1]);
87479    if( n>30 ) n = 30;
87480    if( n<0 ) n = 0;
87481  }
87482  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
87483  r = sqlite3_value_double(argv[0]);
87484  /* If Y==0 and X will fit in a 64-bit int,
87485  ** handle the rounding directly,
87486  ** otherwise use printf.
87487  */
87488  if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
87489    r = (double)((sqlite_int64)(r+0.5));
87490  }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
87491    r = -(double)((sqlite_int64)((-r)+0.5));
87492  }else{
87493    zBuf = sqlite3_mprintf("%.*f",n,r);
87494    if( zBuf==0 ){
87495      sqlite3_result_error_nomem(context);
87496      return;
87497    }
87498    sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
87499    sqlite3_free(zBuf);
87500  }
87501  sqlite3_result_double(context, r);
87502}
87503#endif
87504
87505/*
87506** Allocate nByte bytes of space using sqlite3_malloc(). If the
87507** allocation fails, call sqlite3_result_error_nomem() to notify
87508** the database handle that malloc() has failed and return NULL.
87509** If nByte is larger than the maximum string or blob length, then
87510** raise an SQLITE_TOOBIG exception and return NULL.
87511*/
87512static void *contextMalloc(sqlite3_context *context, i64 nByte){
87513  char *z;
87514  sqlite3 *db = sqlite3_context_db_handle(context);
87515  assert( nByte>0 );
87516  testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
87517  testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
87518  if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
87519    sqlite3_result_error_toobig(context);
87520    z = 0;
87521  }else{
87522    z = sqlite3Malloc((int)nByte);
87523    if( !z ){
87524      sqlite3_result_error_nomem(context);
87525    }
87526  }
87527  return z;
87528}
87529
87530/*
87531** Implementation of the upper() and lower() SQL functions.
87532*/
87533static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
87534  char *z1;
87535  const char *z2;
87536  int i, n;
87537  UNUSED_PARAMETER(argc);
87538  z2 = (char*)sqlite3_value_text(argv[0]);
87539  n = sqlite3_value_bytes(argv[0]);
87540  /* Verify that the call to _bytes() does not invalidate the _text() pointer */
87541  assert( z2==(char*)sqlite3_value_text(argv[0]) );
87542  if( z2 ){
87543    z1 = contextMalloc(context, ((i64)n)+1);
87544    if( z1 ){
87545      for(i=0; i<n; i++){
87546        z1[i] = (char)sqlite3Toupper(z2[i]);
87547      }
87548      sqlite3_result_text(context, z1, n, sqlite3_free);
87549    }
87550  }
87551}
87552static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
87553  char *z1;
87554  const char *z2;
87555  int i, n;
87556  UNUSED_PARAMETER(argc);
87557  z2 = (char*)sqlite3_value_text(argv[0]);
87558  n = sqlite3_value_bytes(argv[0]);
87559  /* Verify that the call to _bytes() does not invalidate the _text() pointer */
87560  assert( z2==(char*)sqlite3_value_text(argv[0]) );
87561  if( z2 ){
87562    z1 = contextMalloc(context, ((i64)n)+1);
87563    if( z1 ){
87564      for(i=0; i<n; i++){
87565        z1[i] = sqlite3Tolower(z2[i]);
87566      }
87567      sqlite3_result_text(context, z1, n, sqlite3_free);
87568    }
87569  }
87570}
87571
87572/*
87573** The COALESCE() and IFNULL() functions are implemented as VDBE code so
87574** that unused argument values do not have to be computed.  However, we
87575** still need some kind of function implementation for this routines in
87576** the function table.  That function implementation will never be called
87577** so it doesn't matter what the implementation is.  We might as well use
87578** the "version()" function as a substitute.
87579*/
87580#define ifnullFunc versionFunc   /* Substitute function - never called */
87581
87582/*
87583** Implementation of random().  Return a random integer.
87584*/
87585static void randomFunc(
87586  sqlite3_context *context,
87587  int NotUsed,
87588  sqlite3_value **NotUsed2
87589){
87590  sqlite_int64 r;
87591  UNUSED_PARAMETER2(NotUsed, NotUsed2);
87592  sqlite3_randomness(sizeof(r), &r);
87593  if( r<0 ){
87594    /* We need to prevent a random number of 0x8000000000000000
87595    ** (or -9223372036854775808) since when you do abs() of that
87596    ** number of you get the same value back again.  To do this
87597    ** in a way that is testable, mask the sign bit off of negative
87598    ** values, resulting in a positive value.  Then take the
87599    ** 2s complement of that positive value.  The end result can
87600    ** therefore be no less than -9223372036854775807.
87601    */
87602    r = -(r & LARGEST_INT64);
87603  }
87604  sqlite3_result_int64(context, r);
87605}
87606
87607/*
87608** Implementation of randomblob(N).  Return a random blob
87609** that is N bytes long.
87610*/
87611static void randomBlob(
87612  sqlite3_context *context,
87613  int argc,
87614  sqlite3_value **argv
87615){
87616  int n;
87617  unsigned char *p;
87618  assert( argc==1 );
87619  UNUSED_PARAMETER(argc);
87620  n = sqlite3_value_int(argv[0]);
87621  if( n<1 ){
87622    n = 1;
87623  }
87624  p = contextMalloc(context, n);
87625  if( p ){
87626    sqlite3_randomness(n, p);
87627    sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
87628  }
87629}
87630
87631/*
87632** Implementation of the last_insert_rowid() SQL function.  The return
87633** value is the same as the sqlite3_last_insert_rowid() API function.
87634*/
87635static void last_insert_rowid(
87636  sqlite3_context *context,
87637  int NotUsed,
87638  sqlite3_value **NotUsed2
87639){
87640  sqlite3 *db = sqlite3_context_db_handle(context);
87641  UNUSED_PARAMETER2(NotUsed, NotUsed2);
87642  /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
87643  ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
87644  ** function. */
87645  sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
87646}
87647
87648/*
87649** Implementation of the changes() SQL function.
87650**
87651** IMP: R-62073-11209 The changes() SQL function is a wrapper
87652** around the sqlite3_changes() C/C++ function and hence follows the same
87653** rules for counting changes.
87654*/
87655static void changes(
87656  sqlite3_context *context,
87657  int NotUsed,
87658  sqlite3_value **NotUsed2
87659){
87660  sqlite3 *db = sqlite3_context_db_handle(context);
87661  UNUSED_PARAMETER2(NotUsed, NotUsed2);
87662  sqlite3_result_int(context, sqlite3_changes(db));
87663}
87664
87665/*
87666** Implementation of the total_changes() SQL function.  The return value is
87667** the same as the sqlite3_total_changes() API function.
87668*/
87669static void total_changes(
87670  sqlite3_context *context,
87671  int NotUsed,
87672  sqlite3_value **NotUsed2
87673){
87674  sqlite3 *db = sqlite3_context_db_handle(context);
87675  UNUSED_PARAMETER2(NotUsed, NotUsed2);
87676  /* IMP: R-52756-41993 This function is a wrapper around the
87677  ** sqlite3_total_changes() C/C++ interface. */
87678  sqlite3_result_int(context, sqlite3_total_changes(db));
87679}
87680
87681/*
87682** A structure defining how to do GLOB-style comparisons.
87683*/
87684struct compareInfo {
87685  u8 matchAll;
87686  u8 matchOne;
87687  u8 matchSet;
87688  u8 noCase;
87689};
87690
87691/*
87692** For LIKE and GLOB matching on EBCDIC machines, assume that every
87693** character is exactly one byte in size.  Also, all characters are
87694** able to participate in upper-case-to-lower-case mappings in EBCDIC
87695** whereas only characters less than 0x80 do in ASCII.
87696*/
87697#if defined(SQLITE_EBCDIC)
87698# define sqlite3Utf8Read(A)    (*((*A)++))
87699# define GlogUpperToLower(A)   A = sqlite3UpperToLower[A]
87700#else
87701# define GlogUpperToLower(A)   if( !((A)&~0x7f) ){ A = sqlite3UpperToLower[A]; }
87702#endif
87703
87704static const struct compareInfo globInfo = { '*', '?', '[', 0 };
87705/* The correct SQL-92 behavior is for the LIKE operator to ignore
87706** case.  Thus  'a' LIKE 'A' would be true. */
87707static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
87708/* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
87709** is case sensitive causing 'a' LIKE 'A' to be false */
87710static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
87711
87712/*
87713** Compare two UTF-8 strings for equality where the first string can
87714** potentially be a "glob" expression.  Return true (1) if they
87715** are the same and false (0) if they are different.
87716**
87717** Globbing rules:
87718**
87719**      '*'       Matches any sequence of zero or more characters.
87720**
87721**      '?'       Matches exactly one character.
87722**
87723**     [...]      Matches one character from the enclosed list of
87724**                characters.
87725**
87726**     [^...]     Matches one character not in the enclosed list.
87727**
87728** With the [...] and [^...] matching, a ']' character can be included
87729** in the list by making it the first character after '[' or '^'.  A
87730** range of characters can be specified using '-'.  Example:
87731** "[a-z]" matches any single lower-case letter.  To match a '-', make
87732** it the last character in the list.
87733**
87734** This routine is usually quick, but can be N**2 in the worst case.
87735**
87736** Hints: to match '*' or '?', put them in "[]".  Like this:
87737**
87738**         abc[*]xyz        Matches "abc*xyz" only
87739*/
87740static int patternCompare(
87741  const u8 *zPattern,              /* The glob pattern */
87742  const u8 *zString,               /* The string to compare against the glob */
87743  const struct compareInfo *pInfo, /* Information about how to do the compare */
87744  u32 esc                          /* The escape character */
87745){
87746  u32 c, c2;
87747  int invert;
87748  int seen;
87749  u8 matchOne = pInfo->matchOne;
87750  u8 matchAll = pInfo->matchAll;
87751  u8 matchSet = pInfo->matchSet;
87752  u8 noCase = pInfo->noCase;
87753  int prevEscape = 0;     /* True if the previous character was 'escape' */
87754
87755  while( (c = sqlite3Utf8Read(&zPattern))!=0 ){
87756    if( c==matchAll && !prevEscape ){
87757      while( (c=sqlite3Utf8Read(&zPattern)) == matchAll
87758               || c == matchOne ){
87759        if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
87760          return 0;
87761        }
87762      }
87763      if( c==0 ){
87764        return 1;
87765      }else if( c==esc ){
87766        c = sqlite3Utf8Read(&zPattern);
87767        if( c==0 ){
87768          return 0;
87769        }
87770      }else if( c==matchSet ){
87771        assert( esc==0 );         /* This is GLOB, not LIKE */
87772        assert( matchSet<0x80 );  /* '[' is a single-byte character */
87773        while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
87774          SQLITE_SKIP_UTF8(zString);
87775        }
87776        return *zString!=0;
87777      }
87778      while( (c2 = sqlite3Utf8Read(&zString))!=0 ){
87779        if( noCase ){
87780          GlogUpperToLower(c2);
87781          GlogUpperToLower(c);
87782          while( c2 != 0 && c2 != c ){
87783            c2 = sqlite3Utf8Read(&zString);
87784            GlogUpperToLower(c2);
87785          }
87786        }else{
87787          while( c2 != 0 && c2 != c ){
87788            c2 = sqlite3Utf8Read(&zString);
87789          }
87790        }
87791        if( c2==0 ) return 0;
87792        if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
87793      }
87794      return 0;
87795    }else if( c==matchOne && !prevEscape ){
87796      if( sqlite3Utf8Read(&zString)==0 ){
87797        return 0;
87798      }
87799    }else if( c==matchSet ){
87800      u32 prior_c = 0;
87801      assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
87802      seen = 0;
87803      invert = 0;
87804      c = sqlite3Utf8Read(&zString);
87805      if( c==0 ) return 0;
87806      c2 = sqlite3Utf8Read(&zPattern);
87807      if( c2=='^' ){
87808        invert = 1;
87809        c2 = sqlite3Utf8Read(&zPattern);
87810      }
87811      if( c2==']' ){
87812        if( c==']' ) seen = 1;
87813        c2 = sqlite3Utf8Read(&zPattern);
87814      }
87815      while( c2 && c2!=']' ){
87816        if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
87817          c2 = sqlite3Utf8Read(&zPattern);
87818          if( c>=prior_c && c<=c2 ) seen = 1;
87819          prior_c = 0;
87820        }else{
87821          if( c==c2 ){
87822            seen = 1;
87823          }
87824          prior_c = c2;
87825        }
87826        c2 = sqlite3Utf8Read(&zPattern);
87827      }
87828      if( c2==0 || (seen ^ invert)==0 ){
87829        return 0;
87830      }
87831    }else if( esc==c && !prevEscape ){
87832      prevEscape = 1;
87833    }else{
87834      c2 = sqlite3Utf8Read(&zString);
87835      if( noCase ){
87836        GlogUpperToLower(c);
87837        GlogUpperToLower(c2);
87838      }
87839      if( c!=c2 ){
87840        return 0;
87841      }
87842      prevEscape = 0;
87843    }
87844  }
87845  return *zString==0;
87846}
87847
87848/*
87849** The sqlite3_strglob() interface.
87850*/
87851SQLITE_API int sqlite3_strglob(const char *zGlobPattern, const char *zString){
87852  return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, 0)==0;
87853}
87854
87855/*
87856** Count the number of times that the LIKE operator (or GLOB which is
87857** just a variation of LIKE) gets called.  This is used for testing
87858** only.
87859*/
87860#ifdef SQLITE_TEST
87861SQLITE_API int sqlite3_like_count = 0;
87862#endif
87863
87864
87865/*
87866** Implementation of the like() SQL function.  This function implements
87867** the build-in LIKE operator.  The first argument to the function is the
87868** pattern and the second argument is the string.  So, the SQL statements:
87869**
87870**       A LIKE B
87871**
87872** is implemented as like(B,A).
87873**
87874** This same function (with a different compareInfo structure) computes
87875** the GLOB operator.
87876*/
87877static void likeFunc(
87878  sqlite3_context *context,
87879  int argc,
87880  sqlite3_value **argv
87881){
87882  const unsigned char *zA, *zB;
87883  u32 escape = 0;
87884  int nPat;
87885  sqlite3 *db = sqlite3_context_db_handle(context);
87886
87887  zB = sqlite3_value_text(argv[0]);
87888  zA = sqlite3_value_text(argv[1]);
87889
87890  /* Limit the length of the LIKE or GLOB pattern to avoid problems
87891  ** of deep recursion and N*N behavior in patternCompare().
87892  */
87893  nPat = sqlite3_value_bytes(argv[0]);
87894  testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
87895  testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
87896  if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
87897    sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
87898    return;
87899  }
87900  assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
87901
87902  if( argc==3 ){
87903    /* The escape character string must consist of a single UTF-8 character.
87904    ** Otherwise, return an error.
87905    */
87906    const unsigned char *zEsc = sqlite3_value_text(argv[2]);
87907    if( zEsc==0 ) return;
87908    if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
87909      sqlite3_result_error(context,
87910          "ESCAPE expression must be a single character", -1);
87911      return;
87912    }
87913    escape = sqlite3Utf8Read(&zEsc);
87914  }
87915  if( zA && zB ){
87916    struct compareInfo *pInfo = sqlite3_user_data(context);
87917#ifdef SQLITE_TEST
87918    sqlite3_like_count++;
87919#endif
87920
87921    sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
87922  }
87923}
87924
87925/*
87926** Implementation of the NULLIF(x,y) function.  The result is the first
87927** argument if the arguments are different.  The result is NULL if the
87928** arguments are equal to each other.
87929*/
87930static void nullifFunc(
87931  sqlite3_context *context,
87932  int NotUsed,
87933  sqlite3_value **argv
87934){
87935  CollSeq *pColl = sqlite3GetFuncCollSeq(context);
87936  UNUSED_PARAMETER(NotUsed);
87937  if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
87938    sqlite3_result_value(context, argv[0]);
87939  }
87940}
87941
87942/*
87943** Implementation of the sqlite_version() function.  The result is the version
87944** of the SQLite library that is running.
87945*/
87946static void versionFunc(
87947  sqlite3_context *context,
87948  int NotUsed,
87949  sqlite3_value **NotUsed2
87950){
87951  UNUSED_PARAMETER2(NotUsed, NotUsed2);
87952  /* IMP: R-48699-48617 This function is an SQL wrapper around the
87953  ** sqlite3_libversion() C-interface. */
87954  sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
87955}
87956
87957/*
87958** Implementation of the sqlite_source_id() function. The result is a string
87959** that identifies the particular version of the source code used to build
87960** SQLite.
87961*/
87962static void sourceidFunc(
87963  sqlite3_context *context,
87964  int NotUsed,
87965  sqlite3_value **NotUsed2
87966){
87967  UNUSED_PARAMETER2(NotUsed, NotUsed2);
87968  /* IMP: R-24470-31136 This function is an SQL wrapper around the
87969  ** sqlite3_sourceid() C interface. */
87970  sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
87971}
87972
87973/*
87974** Implementation of the sqlite_log() function.  This is a wrapper around
87975** sqlite3_log().  The return value is NULL.  The function exists purely for
87976** its side-effects.
87977*/
87978static void errlogFunc(
87979  sqlite3_context *context,
87980  int argc,
87981  sqlite3_value **argv
87982){
87983  UNUSED_PARAMETER(argc);
87984  UNUSED_PARAMETER(context);
87985  sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
87986}
87987
87988/*
87989** Implementation of the sqlite_compileoption_used() function.
87990** The result is an integer that identifies if the compiler option
87991** was used to build SQLite.
87992*/
87993#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
87994static void compileoptionusedFunc(
87995  sqlite3_context *context,
87996  int argc,
87997  sqlite3_value **argv
87998){
87999  const char *zOptName;
88000  assert( argc==1 );
88001  UNUSED_PARAMETER(argc);
88002  /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
88003  ** function is a wrapper around the sqlite3_compileoption_used() C/C++
88004  ** function.
88005  */
88006  if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
88007    sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
88008  }
88009}
88010#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
88011
88012/*
88013** Implementation of the sqlite_compileoption_get() function.
88014** The result is a string that identifies the compiler options
88015** used to build SQLite.
88016*/
88017#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
88018static void compileoptiongetFunc(
88019  sqlite3_context *context,
88020  int argc,
88021  sqlite3_value **argv
88022){
88023  int n;
88024  assert( argc==1 );
88025  UNUSED_PARAMETER(argc);
88026  /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
88027  ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
88028  */
88029  n = sqlite3_value_int(argv[0]);
88030  sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
88031}
88032#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
88033
88034/* Array for converting from half-bytes (nybbles) into ASCII hex
88035** digits. */
88036static const char hexdigits[] = {
88037  '0', '1', '2', '3', '4', '5', '6', '7',
88038  '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
88039};
88040
88041/*
88042** EXPERIMENTAL - This is not an official function.  The interface may
88043** change.  This function may disappear.  Do not write code that depends
88044** on this function.
88045**
88046** Implementation of the QUOTE() function.  This function takes a single
88047** argument.  If the argument is numeric, the return value is the same as
88048** the argument.  If the argument is NULL, the return value is the string
88049** "NULL".  Otherwise, the argument is enclosed in single quotes with
88050** single-quote escapes.
88051*/
88052static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
88053  assert( argc==1 );
88054  UNUSED_PARAMETER(argc);
88055  switch( sqlite3_value_type(argv[0]) ){
88056    case SQLITE_FLOAT: {
88057      double r1, r2;
88058      char zBuf[50];
88059      r1 = sqlite3_value_double(argv[0]);
88060      sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
88061      sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
88062      if( r1!=r2 ){
88063        sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
88064      }
88065      sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
88066      break;
88067    }
88068    case SQLITE_INTEGER: {
88069      sqlite3_result_value(context, argv[0]);
88070      break;
88071    }
88072    case SQLITE_BLOB: {
88073      char *zText = 0;
88074      char const *zBlob = sqlite3_value_blob(argv[0]);
88075      int nBlob = sqlite3_value_bytes(argv[0]);
88076      assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
88077      zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
88078      if( zText ){
88079        int i;
88080        for(i=0; i<nBlob; i++){
88081          zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
88082          zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
88083        }
88084        zText[(nBlob*2)+2] = '\'';
88085        zText[(nBlob*2)+3] = '\0';
88086        zText[0] = 'X';
88087        zText[1] = '\'';
88088        sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
88089        sqlite3_free(zText);
88090      }
88091      break;
88092    }
88093    case SQLITE_TEXT: {
88094      int i,j;
88095      u64 n;
88096      const unsigned char *zArg = sqlite3_value_text(argv[0]);
88097      char *z;
88098
88099      if( zArg==0 ) return;
88100      for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
88101      z = contextMalloc(context, ((i64)i)+((i64)n)+3);
88102      if( z ){
88103        z[0] = '\'';
88104        for(i=0, j=1; zArg[i]; i++){
88105          z[j++] = zArg[i];
88106          if( zArg[i]=='\'' ){
88107            z[j++] = '\'';
88108          }
88109        }
88110        z[j++] = '\'';
88111        z[j] = 0;
88112        sqlite3_result_text(context, z, j, sqlite3_free);
88113      }
88114      break;
88115    }
88116    default: {
88117      assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
88118      sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
88119      break;
88120    }
88121  }
88122}
88123
88124/*
88125** The unicode() function.  Return the integer unicode code-point value
88126** for the first character of the input string.
88127*/
88128static void unicodeFunc(
88129  sqlite3_context *context,
88130  int argc,
88131  sqlite3_value **argv
88132){
88133  const unsigned char *z = sqlite3_value_text(argv[0]);
88134  (void)argc;
88135  if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
88136}
88137
88138/*
88139** The char() function takes zero or more arguments, each of which is
88140** an integer.  It constructs a string where each character of the string
88141** is the unicode character for the corresponding integer argument.
88142*/
88143static void charFunc(
88144  sqlite3_context *context,
88145  int argc,
88146  sqlite3_value **argv
88147){
88148  unsigned char *z, *zOut;
88149  int i;
88150  zOut = z = sqlite3_malloc( argc*4 );
88151  if( z==0 ){
88152    sqlite3_result_error_nomem(context);
88153    return;
88154  }
88155  for(i=0; i<argc; i++){
88156    sqlite3_int64 x;
88157    unsigned c;
88158    x = sqlite3_value_int64(argv[i]);
88159    if( x<0 || x>0x10ffff ) x = 0xfffd;
88160    c = (unsigned)(x & 0x1fffff);
88161    if( c<0x00080 ){
88162      *zOut++ = (u8)(c&0xFF);
88163    }else if( c<0x00800 ){
88164      *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
88165      *zOut++ = 0x80 + (u8)(c & 0x3F);
88166    }else if( c<0x10000 ){
88167      *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
88168      *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
88169      *zOut++ = 0x80 + (u8)(c & 0x3F);
88170    }else{
88171      *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
88172      *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
88173      *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
88174      *zOut++ = 0x80 + (u8)(c & 0x3F);
88175    }                                                    \
88176  }
88177  sqlite3_result_text(context, (char*)z, (int)(zOut-z), sqlite3_free);
88178}
88179
88180/*
88181** The hex() function.  Interpret the argument as a blob.  Return
88182** a hexadecimal rendering as text.
88183*/
88184static void hexFunc(
88185  sqlite3_context *context,
88186  int argc,
88187  sqlite3_value **argv
88188){
88189  int i, n;
88190  const unsigned char *pBlob;
88191  char *zHex, *z;
88192  assert( argc==1 );
88193  UNUSED_PARAMETER(argc);
88194  pBlob = sqlite3_value_blob(argv[0]);
88195  n = sqlite3_value_bytes(argv[0]);
88196  assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
88197  z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
88198  if( zHex ){
88199    for(i=0; i<n; i++, pBlob++){
88200      unsigned char c = *pBlob;
88201      *(z++) = hexdigits[(c>>4)&0xf];
88202      *(z++) = hexdigits[c&0xf];
88203    }
88204    *z = 0;
88205    sqlite3_result_text(context, zHex, n*2, sqlite3_free);
88206  }
88207}
88208
88209/*
88210** The zeroblob(N) function returns a zero-filled blob of size N bytes.
88211*/
88212static void zeroblobFunc(
88213  sqlite3_context *context,
88214  int argc,
88215  sqlite3_value **argv
88216){
88217  i64 n;
88218  sqlite3 *db = sqlite3_context_db_handle(context);
88219  assert( argc==1 );
88220  UNUSED_PARAMETER(argc);
88221  n = sqlite3_value_int64(argv[0]);
88222  testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
88223  testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
88224  if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
88225    sqlite3_result_error_toobig(context);
88226  }else{
88227    sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
88228  }
88229}
88230
88231/*
88232** The replace() function.  Three arguments are all strings: call
88233** them A, B, and C. The result is also a string which is derived
88234** from A by replacing every occurance of B with C.  The match
88235** must be exact.  Collating sequences are not used.
88236*/
88237static void replaceFunc(
88238  sqlite3_context *context,
88239  int argc,
88240  sqlite3_value **argv
88241){
88242  const unsigned char *zStr;        /* The input string A */
88243  const unsigned char *zPattern;    /* The pattern string B */
88244  const unsigned char *zRep;        /* The replacement string C */
88245  unsigned char *zOut;              /* The output */
88246  int nStr;                /* Size of zStr */
88247  int nPattern;            /* Size of zPattern */
88248  int nRep;                /* Size of zRep */
88249  i64 nOut;                /* Maximum size of zOut */
88250  int loopLimit;           /* Last zStr[] that might match zPattern[] */
88251  int i, j;                /* Loop counters */
88252
88253  assert( argc==3 );
88254  UNUSED_PARAMETER(argc);
88255  zStr = sqlite3_value_text(argv[0]);
88256  if( zStr==0 ) return;
88257  nStr = sqlite3_value_bytes(argv[0]);
88258  assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
88259  zPattern = sqlite3_value_text(argv[1]);
88260  if( zPattern==0 ){
88261    assert( sqlite3_value_type(argv[1])==SQLITE_NULL
88262            || sqlite3_context_db_handle(context)->mallocFailed );
88263    return;
88264  }
88265  if( zPattern[0]==0 ){
88266    assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
88267    sqlite3_result_value(context, argv[0]);
88268    return;
88269  }
88270  nPattern = sqlite3_value_bytes(argv[1]);
88271  assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
88272  zRep = sqlite3_value_text(argv[2]);
88273  if( zRep==0 ) return;
88274  nRep = sqlite3_value_bytes(argv[2]);
88275  assert( zRep==sqlite3_value_text(argv[2]) );
88276  nOut = nStr + 1;
88277  assert( nOut<SQLITE_MAX_LENGTH );
88278  zOut = contextMalloc(context, (i64)nOut);
88279  if( zOut==0 ){
88280    return;
88281  }
88282  loopLimit = nStr - nPattern;
88283  for(i=j=0; i<=loopLimit; i++){
88284    if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
88285      zOut[j++] = zStr[i];
88286    }else{
88287      u8 *zOld;
88288      sqlite3 *db = sqlite3_context_db_handle(context);
88289      nOut += nRep - nPattern;
88290      testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
88291      testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
88292      if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
88293        sqlite3_result_error_toobig(context);
88294        sqlite3_free(zOut);
88295        return;
88296      }
88297      zOld = zOut;
88298      zOut = sqlite3_realloc(zOut, (int)nOut);
88299      if( zOut==0 ){
88300        sqlite3_result_error_nomem(context);
88301        sqlite3_free(zOld);
88302        return;
88303      }
88304      memcpy(&zOut[j], zRep, nRep);
88305      j += nRep;
88306      i += nPattern-1;
88307    }
88308  }
88309  assert( j+nStr-i+1==nOut );
88310  memcpy(&zOut[j], &zStr[i], nStr-i);
88311  j += nStr - i;
88312  assert( j<=nOut );
88313  zOut[j] = 0;
88314  sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
88315}
88316
88317/*
88318** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
88319** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
88320*/
88321static void trimFunc(
88322  sqlite3_context *context,
88323  int argc,
88324  sqlite3_value **argv
88325){
88326  const unsigned char *zIn;         /* Input string */
88327  const unsigned char *zCharSet;    /* Set of characters to trim */
88328  int nIn;                          /* Number of bytes in input */
88329  int flags;                        /* 1: trimleft  2: trimright  3: trim */
88330  int i;                            /* Loop counter */
88331  unsigned char *aLen = 0;          /* Length of each character in zCharSet */
88332  unsigned char **azChar = 0;       /* Individual characters in zCharSet */
88333  int nChar;                        /* Number of characters in zCharSet */
88334
88335  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
88336    return;
88337  }
88338  zIn = sqlite3_value_text(argv[0]);
88339  if( zIn==0 ) return;
88340  nIn = sqlite3_value_bytes(argv[0]);
88341  assert( zIn==sqlite3_value_text(argv[0]) );
88342  if( argc==1 ){
88343    static const unsigned char lenOne[] = { 1 };
88344    static unsigned char * const azOne[] = { (u8*)" " };
88345    nChar = 1;
88346    aLen = (u8*)lenOne;
88347    azChar = (unsigned char **)azOne;
88348    zCharSet = 0;
88349  }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
88350    return;
88351  }else{
88352    const unsigned char *z;
88353    for(z=zCharSet, nChar=0; *z; nChar++){
88354      SQLITE_SKIP_UTF8(z);
88355    }
88356    if( nChar>0 ){
88357      azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
88358      if( azChar==0 ){
88359        return;
88360      }
88361      aLen = (unsigned char*)&azChar[nChar];
88362      for(z=zCharSet, nChar=0; *z; nChar++){
88363        azChar[nChar] = (unsigned char *)z;
88364        SQLITE_SKIP_UTF8(z);
88365        aLen[nChar] = (u8)(z - azChar[nChar]);
88366      }
88367    }
88368  }
88369  if( nChar>0 ){
88370    flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
88371    if( flags & 1 ){
88372      while( nIn>0 ){
88373        int len = 0;
88374        for(i=0; i<nChar; i++){
88375          len = aLen[i];
88376          if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
88377        }
88378        if( i>=nChar ) break;
88379        zIn += len;
88380        nIn -= len;
88381      }
88382    }
88383    if( flags & 2 ){
88384      while( nIn>0 ){
88385        int len = 0;
88386        for(i=0; i<nChar; i++){
88387          len = aLen[i];
88388          if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
88389        }
88390        if( i>=nChar ) break;
88391        nIn -= len;
88392      }
88393    }
88394    if( zCharSet ){
88395      sqlite3_free(azChar);
88396    }
88397  }
88398  sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
88399}
88400
88401
88402/* IMP: R-25361-16150 This function is omitted from SQLite by default. It
88403** is only available if the SQLITE_SOUNDEX compile-time option is used
88404** when SQLite is built.
88405*/
88406#ifdef SQLITE_SOUNDEX
88407/*
88408** Compute the soundex encoding of a word.
88409**
88410** IMP: R-59782-00072 The soundex(X) function returns a string that is the
88411** soundex encoding of the string X.
88412*/
88413static void soundexFunc(
88414  sqlite3_context *context,
88415  int argc,
88416  sqlite3_value **argv
88417){
88418  char zResult[8];
88419  const u8 *zIn;
88420  int i, j;
88421  static const unsigned char iCode[] = {
88422    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
88423    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
88424    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
88425    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
88426    0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
88427    1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
88428    0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
88429    1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
88430  };
88431  assert( argc==1 );
88432  zIn = (u8*)sqlite3_value_text(argv[0]);
88433  if( zIn==0 ) zIn = (u8*)"";
88434  for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
88435  if( zIn[i] ){
88436    u8 prevcode = iCode[zIn[i]&0x7f];
88437    zResult[0] = sqlite3Toupper(zIn[i]);
88438    for(j=1; j<4 && zIn[i]; i++){
88439      int code = iCode[zIn[i]&0x7f];
88440      if( code>0 ){
88441        if( code!=prevcode ){
88442          prevcode = code;
88443          zResult[j++] = code + '0';
88444        }
88445      }else{
88446        prevcode = 0;
88447      }
88448    }
88449    while( j<4 ){
88450      zResult[j++] = '0';
88451    }
88452    zResult[j] = 0;
88453    sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
88454  }else{
88455    /* IMP: R-64894-50321 The string "?000" is returned if the argument
88456    ** is NULL or contains no ASCII alphabetic characters. */
88457    sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
88458  }
88459}
88460#endif /* SQLITE_SOUNDEX */
88461
88462#ifndef SQLITE_OMIT_LOAD_EXTENSION
88463/*
88464** A function that loads a shared-library extension then returns NULL.
88465*/
88466static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
88467  const char *zFile = (const char *)sqlite3_value_text(argv[0]);
88468  const char *zProc;
88469  sqlite3 *db = sqlite3_context_db_handle(context);
88470  char *zErrMsg = 0;
88471
88472  if( argc==2 ){
88473    zProc = (const char *)sqlite3_value_text(argv[1]);
88474  }else{
88475    zProc = 0;
88476  }
88477  if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
88478    sqlite3_result_error(context, zErrMsg, -1);
88479    sqlite3_free(zErrMsg);
88480  }
88481}
88482#endif
88483
88484
88485/*
88486** An instance of the following structure holds the context of a
88487** sum() or avg() aggregate computation.
88488*/
88489typedef struct SumCtx SumCtx;
88490struct SumCtx {
88491  double rSum;      /* Floating point sum */
88492  i64 iSum;         /* Integer sum */
88493  i64 cnt;          /* Number of elements summed */
88494  u8 overflow;      /* True if integer overflow seen */
88495  u8 approx;        /* True if non-integer value was input to the sum */
88496};
88497
88498/*
88499** Routines used to compute the sum, average, and total.
88500**
88501** The SUM() function follows the (broken) SQL standard which means
88502** that it returns NULL if it sums over no inputs.  TOTAL returns
88503** 0.0 in that case.  In addition, TOTAL always returns a float where
88504** SUM might return an integer if it never encounters a floating point
88505** value.  TOTAL never fails, but SUM might through an exception if
88506** it overflows an integer.
88507*/
88508static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
88509  SumCtx *p;
88510  int type;
88511  assert( argc==1 );
88512  UNUSED_PARAMETER(argc);
88513  p = sqlite3_aggregate_context(context, sizeof(*p));
88514  type = sqlite3_value_numeric_type(argv[0]);
88515  if( p && type!=SQLITE_NULL ){
88516    p->cnt++;
88517    if( type==SQLITE_INTEGER ){
88518      i64 v = sqlite3_value_int64(argv[0]);
88519      p->rSum += v;
88520      if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
88521        p->overflow = 1;
88522      }
88523    }else{
88524      p->rSum += sqlite3_value_double(argv[0]);
88525      p->approx = 1;
88526    }
88527  }
88528}
88529static void sumFinalize(sqlite3_context *context){
88530  SumCtx *p;
88531  p = sqlite3_aggregate_context(context, 0);
88532  if( p && p->cnt>0 ){
88533    if( p->overflow ){
88534      sqlite3_result_error(context,"integer overflow",-1);
88535    }else if( p->approx ){
88536      sqlite3_result_double(context, p->rSum);
88537    }else{
88538      sqlite3_result_int64(context, p->iSum);
88539    }
88540  }
88541}
88542static void avgFinalize(sqlite3_context *context){
88543  SumCtx *p;
88544  p = sqlite3_aggregate_context(context, 0);
88545  if( p && p->cnt>0 ){
88546    sqlite3_result_double(context, p->rSum/(double)p->cnt);
88547  }
88548}
88549static void totalFinalize(sqlite3_context *context){
88550  SumCtx *p;
88551  p = sqlite3_aggregate_context(context, 0);
88552  /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
88553  sqlite3_result_double(context, p ? p->rSum : (double)0);
88554}
88555
88556/*
88557** The following structure keeps track of state information for the
88558** count() aggregate function.
88559*/
88560typedef struct CountCtx CountCtx;
88561struct CountCtx {
88562  i64 n;
88563};
88564
88565/*
88566** Routines to implement the count() aggregate function.
88567*/
88568static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
88569  CountCtx *p;
88570  p = sqlite3_aggregate_context(context, sizeof(*p));
88571  if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
88572    p->n++;
88573  }
88574
88575#ifndef SQLITE_OMIT_DEPRECATED
88576  /* The sqlite3_aggregate_count() function is deprecated.  But just to make
88577  ** sure it still operates correctly, verify that its count agrees with our
88578  ** internal count when using count(*) and when the total count can be
88579  ** expressed as a 32-bit integer. */
88580  assert( argc==1 || p==0 || p->n>0x7fffffff
88581          || p->n==sqlite3_aggregate_count(context) );
88582#endif
88583}
88584static void countFinalize(sqlite3_context *context){
88585  CountCtx *p;
88586  p = sqlite3_aggregate_context(context, 0);
88587  sqlite3_result_int64(context, p ? p->n : 0);
88588}
88589
88590/*
88591** Routines to implement min() and max() aggregate functions.
88592*/
88593static void minmaxStep(
88594  sqlite3_context *context,
88595  int NotUsed,
88596  sqlite3_value **argv
88597){
88598  Mem *pArg  = (Mem *)argv[0];
88599  Mem *pBest;
88600  UNUSED_PARAMETER(NotUsed);
88601
88602  pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
88603  if( !pBest ) return;
88604
88605  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
88606    if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
88607  }else if( pBest->flags ){
88608    int max;
88609    int cmp;
88610    CollSeq *pColl = sqlite3GetFuncCollSeq(context);
88611    /* This step function is used for both the min() and max() aggregates,
88612    ** the only difference between the two being that the sense of the
88613    ** comparison is inverted. For the max() aggregate, the
88614    ** sqlite3_user_data() function returns (void *)-1. For min() it
88615    ** returns (void *)db, where db is the sqlite3* database pointer.
88616    ** Therefore the next statement sets variable 'max' to 1 for the max()
88617    ** aggregate, or 0 for min().
88618    */
88619    max = sqlite3_user_data(context)!=0;
88620    cmp = sqlite3MemCompare(pBest, pArg, pColl);
88621    if( (max && cmp<0) || (!max && cmp>0) ){
88622      sqlite3VdbeMemCopy(pBest, pArg);
88623    }else{
88624      sqlite3SkipAccumulatorLoad(context);
88625    }
88626  }else{
88627    sqlite3VdbeMemCopy(pBest, pArg);
88628  }
88629}
88630static void minMaxFinalize(sqlite3_context *context){
88631  sqlite3_value *pRes;
88632  pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
88633  if( pRes ){
88634    if( pRes->flags ){
88635      sqlite3_result_value(context, pRes);
88636    }
88637    sqlite3VdbeMemRelease(pRes);
88638  }
88639}
88640
88641/*
88642** group_concat(EXPR, ?SEPARATOR?)
88643*/
88644static void groupConcatStep(
88645  sqlite3_context *context,
88646  int argc,
88647  sqlite3_value **argv
88648){
88649  const char *zVal;
88650  StrAccum *pAccum;
88651  const char *zSep;
88652  int nVal, nSep;
88653  assert( argc==1 || argc==2 );
88654  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
88655  pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
88656
88657  if( pAccum ){
88658    sqlite3 *db = sqlite3_context_db_handle(context);
88659    int firstTerm = pAccum->useMalloc==0;
88660    pAccum->useMalloc = 2;
88661    pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
88662    if( !firstTerm ){
88663      if( argc==2 ){
88664        zSep = (char*)sqlite3_value_text(argv[1]);
88665        nSep = sqlite3_value_bytes(argv[1]);
88666      }else{
88667        zSep = ",";
88668        nSep = 1;
88669      }
88670      sqlite3StrAccumAppend(pAccum, zSep, nSep);
88671    }
88672    zVal = (char*)sqlite3_value_text(argv[0]);
88673    nVal = sqlite3_value_bytes(argv[0]);
88674    sqlite3StrAccumAppend(pAccum, zVal, nVal);
88675  }
88676}
88677static void groupConcatFinalize(sqlite3_context *context){
88678  StrAccum *pAccum;
88679  pAccum = sqlite3_aggregate_context(context, 0);
88680  if( pAccum ){
88681    if( pAccum->tooBig ){
88682      sqlite3_result_error_toobig(context);
88683    }else if( pAccum->mallocFailed ){
88684      sqlite3_result_error_nomem(context);
88685    }else{
88686      sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
88687                          sqlite3_free);
88688    }
88689  }
88690}
88691
88692/*
88693** This routine does per-connection function registration.  Most
88694** of the built-in functions above are part of the global function set.
88695** This routine only deals with those that are not global.
88696*/
88697SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
88698  int rc = sqlite3_overload_function(db, "MATCH", 2);
88699  assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
88700  if( rc==SQLITE_NOMEM ){
88701    db->mallocFailed = 1;
88702  }
88703}
88704
88705/*
88706** Set the LIKEOPT flag on the 2-argument function with the given name.
88707*/
88708static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
88709  FuncDef *pDef;
88710  pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
88711                             2, SQLITE_UTF8, 0);
88712  if( ALWAYS(pDef) ){
88713    pDef->flags = flagVal;
88714  }
88715}
88716
88717/*
88718** Register the built-in LIKE and GLOB functions.  The caseSensitive
88719** parameter determines whether or not the LIKE operator is case
88720** sensitive.  GLOB is always case sensitive.
88721*/
88722SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
88723  struct compareInfo *pInfo;
88724  if( caseSensitive ){
88725    pInfo = (struct compareInfo*)&likeInfoAlt;
88726  }else{
88727    pInfo = (struct compareInfo*)&likeInfoNorm;
88728  }
88729  sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
88730  sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
88731  sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
88732      (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
88733  setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
88734  setLikeOptFlag(db, "like",
88735      caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
88736}
88737
88738/*
88739** pExpr points to an expression which implements a function.  If
88740** it is appropriate to apply the LIKE optimization to that function
88741** then set aWc[0] through aWc[2] to the wildcard characters and
88742** return TRUE.  If the function is not a LIKE-style function then
88743** return FALSE.
88744*/
88745SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
88746  FuncDef *pDef;
88747  if( pExpr->op!=TK_FUNCTION
88748   || !pExpr->x.pList
88749   || pExpr->x.pList->nExpr!=2
88750  ){
88751    return 0;
88752  }
88753  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
88754  pDef = sqlite3FindFunction(db, pExpr->u.zToken,
88755                             sqlite3Strlen30(pExpr->u.zToken),
88756                             2, SQLITE_UTF8, 0);
88757  if( NEVER(pDef==0) || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
88758    return 0;
88759  }
88760
88761  /* The memcpy() statement assumes that the wildcard characters are
88762  ** the first three statements in the compareInfo structure.  The
88763  ** asserts() that follow verify that assumption
88764  */
88765  memcpy(aWc, pDef->pUserData, 3);
88766  assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
88767  assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
88768  assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
88769  *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
88770  return 1;
88771}
88772
88773/*
88774** All all of the FuncDef structures in the aBuiltinFunc[] array above
88775** to the global function hash table.  This occurs at start-time (as
88776** a consequence of calling sqlite3_initialize()).
88777**
88778** After this routine runs
88779*/
88780SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
88781  /*
88782  ** The following array holds FuncDef structures for all of the functions
88783  ** defined in this file.
88784  **
88785  ** The array cannot be constant since changes are made to the
88786  ** FuncDef.pHash elements at start-time.  The elements of this array
88787  ** are read-only after initialization is complete.
88788  */
88789  static SQLITE_WSD FuncDef aBuiltinFunc[] = {
88790    FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
88791    FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
88792    FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
88793    FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
88794    FUNCTION(trim,               1, 3, 0, trimFunc         ),
88795    FUNCTION(trim,               2, 3, 0, trimFunc         ),
88796    FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
88797    FUNCTION(min,                0, 0, 1, 0                ),
88798    AGGREGATE(min,               1, 0, 1, minmaxStep,      minMaxFinalize ),
88799    FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
88800    FUNCTION(max,                0, 1, 1, 0                ),
88801    AGGREGATE(max,               1, 1, 1, minmaxStep,      minMaxFinalize ),
88802    FUNCTION2(typeof,            1, 0, 0, typeofFunc,  SQLITE_FUNC_TYPEOF),
88803    FUNCTION2(length,            1, 0, 0, lengthFunc,  SQLITE_FUNC_LENGTH),
88804    FUNCTION(instr,              2, 0, 0, instrFunc        ),
88805    FUNCTION(substr,             2, 0, 0, substrFunc       ),
88806    FUNCTION(substr,             3, 0, 0, substrFunc       ),
88807    FUNCTION(unicode,            1, 0, 0, unicodeFunc      ),
88808    FUNCTION(char,              -1, 0, 0, charFunc         ),
88809    FUNCTION(abs,                1, 0, 0, absFunc          ),
88810#ifndef SQLITE_OMIT_FLOATING_POINT
88811    FUNCTION(round,              1, 0, 0, roundFunc        ),
88812    FUNCTION(round,              2, 0, 0, roundFunc        ),
88813#endif
88814    FUNCTION(upper,              1, 0, 0, upperFunc        ),
88815    FUNCTION(lower,              1, 0, 0, lowerFunc        ),
88816    FUNCTION(coalesce,           1, 0, 0, 0                ),
88817    FUNCTION(coalesce,           0, 0, 0, 0                ),
88818    FUNCTION2(coalesce,         -1, 0, 0, ifnullFunc,  SQLITE_FUNC_COALESCE),
88819    FUNCTION(hex,                1, 0, 0, hexFunc          ),
88820    FUNCTION2(ifnull,            2, 0, 0, ifnullFunc,  SQLITE_FUNC_COALESCE),
88821    FUNCTION(random,             0, 0, 0, randomFunc       ),
88822    FUNCTION(randomblob,         1, 0, 0, randomBlob       ),
88823    FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
88824    FUNCTION(sqlite_version,     0, 0, 0, versionFunc      ),
88825    FUNCTION(sqlite_source_id,   0, 0, 0, sourceidFunc     ),
88826    FUNCTION(sqlite_log,         2, 0, 0, errlogFunc       ),
88827#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
88828    FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc  ),
88829    FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),
88830#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
88831    FUNCTION(quote,              1, 0, 0, quoteFunc        ),
88832    FUNCTION(last_insert_rowid,  0, 0, 0, last_insert_rowid),
88833    FUNCTION(changes,            0, 0, 0, changes          ),
88834    FUNCTION(total_changes,      0, 0, 0, total_changes    ),
88835    FUNCTION(replace,            3, 0, 0, replaceFunc      ),
88836    FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
88837  #ifdef SQLITE_SOUNDEX
88838    FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
88839  #endif
88840  #ifndef SQLITE_OMIT_LOAD_EXTENSION
88841    FUNCTION(load_extension,     1, 0, 0, loadExt          ),
88842    FUNCTION(load_extension,     2, 0, 0, loadExt          ),
88843  #endif
88844    AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
88845    AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
88846    AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
88847 /* AGGREGATE(count,             0, 0, 0, countStep,       countFinalize  ), */
88848    {0,SQLITE_UTF8,SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0,0},
88849    AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
88850    AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
88851    AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
88852
88853    LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
88854  #ifdef SQLITE_CASE_SENSITIVE_LIKE
88855    LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
88856    LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
88857  #else
88858    LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
88859    LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
88860  #endif
88861  };
88862
88863  int i;
88864  FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
88865  FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
88866
88867  for(i=0; i<ArraySize(aBuiltinFunc); i++){
88868    sqlite3FuncDefInsert(pHash, &aFunc[i]);
88869  }
88870  sqlite3RegisterDateTimeFunctions();
88871#ifndef SQLITE_OMIT_ALTERTABLE
88872  sqlite3AlterFunctions();
88873#endif
88874}
88875
88876/************** End of func.c ************************************************/
88877/************** Begin file fkey.c ********************************************/
88878/*
88879**
88880** The author disclaims copyright to this source code.  In place of
88881** a legal notice, here is a blessing:
88882**
88883**    May you do good and not evil.
88884**    May you find forgiveness for yourself and forgive others.
88885**    May you share freely, never taking more than you give.
88886**
88887*************************************************************************
88888** This file contains code used by the compiler to add foreign key
88889** support to compiled SQL statements.
88890*/
88891
88892#ifndef SQLITE_OMIT_FOREIGN_KEY
88893#ifndef SQLITE_OMIT_TRIGGER
88894
88895/*
88896** Deferred and Immediate FKs
88897** --------------------------
88898**
88899** Foreign keys in SQLite come in two flavours: deferred and immediate.
88900** If an immediate foreign key constraint is violated,
88901** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
88902** statement transaction rolled back. If a
88903** deferred foreign key constraint is violated, no action is taken
88904** immediately. However if the application attempts to commit the
88905** transaction before fixing the constraint violation, the attempt fails.
88906**
88907** Deferred constraints are implemented using a simple counter associated
88908** with the database handle. The counter is set to zero each time a
88909** database transaction is opened. Each time a statement is executed
88910** that causes a foreign key violation, the counter is incremented. Each
88911** time a statement is executed that removes an existing violation from
88912** the database, the counter is decremented. When the transaction is
88913** committed, the commit fails if the current value of the counter is
88914** greater than zero. This scheme has two big drawbacks:
88915**
88916**   * When a commit fails due to a deferred foreign key constraint,
88917**     there is no way to tell which foreign constraint is not satisfied,
88918**     or which row it is not satisfied for.
88919**
88920**   * If the database contains foreign key violations when the
88921**     transaction is opened, this may cause the mechanism to malfunction.
88922**
88923** Despite these problems, this approach is adopted as it seems simpler
88924** than the alternatives.
88925**
88926** INSERT operations:
88927**
88928**   I.1) For each FK for which the table is the child table, search
88929**        the parent table for a match. If none is found increment the
88930**        constraint counter.
88931**
88932**   I.2) For each FK for which the table is the parent table,
88933**        search the child table for rows that correspond to the new
88934**        row in the parent table. Decrement the counter for each row
88935**        found (as the constraint is now satisfied).
88936**
88937** DELETE operations:
88938**
88939**   D.1) For each FK for which the table is the child table,
88940**        search the parent table for a row that corresponds to the
88941**        deleted row in the child table. If such a row is not found,
88942**        decrement the counter.
88943**
88944**   D.2) For each FK for which the table is the parent table, search
88945**        the child table for rows that correspond to the deleted row
88946**        in the parent table. For each found increment the counter.
88947**
88948** UPDATE operations:
88949**
88950**   An UPDATE command requires that all 4 steps above are taken, but only
88951**   for FK constraints for which the affected columns are actually
88952**   modified (values must be compared at runtime).
88953**
88954** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
88955** This simplifies the implementation a bit.
88956**
88957** For the purposes of immediate FK constraints, the OR REPLACE conflict
88958** resolution is considered to delete rows before the new row is inserted.
88959** If a delete caused by OR REPLACE violates an FK constraint, an exception
88960** is thrown, even if the FK constraint would be satisfied after the new
88961** row is inserted.
88962**
88963** Immediate constraints are usually handled similarly. The only difference
88964** is that the counter used is stored as part of each individual statement
88965** object (struct Vdbe). If, after the statement has run, its immediate
88966** constraint counter is greater than zero,
88967** it returns SQLITE_CONSTRAINT_FOREIGNKEY
88968** and the statement transaction is rolled back. An exception is an INSERT
88969** statement that inserts a single row only (no triggers). In this case,
88970** instead of using a counter, an exception is thrown immediately if the
88971** INSERT violates a foreign key constraint. This is necessary as such
88972** an INSERT does not open a statement transaction.
88973**
88974** TODO: How should dropping a table be handled? How should renaming a
88975** table be handled?
88976**
88977**
88978** Query API Notes
88979** ---------------
88980**
88981** Before coding an UPDATE or DELETE row operation, the code-generator
88982** for those two operations needs to know whether or not the operation
88983** requires any FK processing and, if so, which columns of the original
88984** row are required by the FK processing VDBE code (i.e. if FKs were
88985** implemented using triggers, which of the old.* columns would be
88986** accessed). No information is required by the code-generator before
88987** coding an INSERT operation. The functions used by the UPDATE/DELETE
88988** generation code to query for this information are:
88989**
88990**   sqlite3FkRequired() - Test to see if FK processing is required.
88991**   sqlite3FkOldmask()  - Query for the set of required old.* columns.
88992**
88993**
88994** Externally accessible module functions
88995** --------------------------------------
88996**
88997**   sqlite3FkCheck()    - Check for foreign key violations.
88998**   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
88999**   sqlite3FkDelete()   - Delete an FKey structure.
89000*/
89001
89002/*
89003** VDBE Calling Convention
89004** -----------------------
89005**
89006** Example:
89007**
89008**   For the following INSERT statement:
89009**
89010**     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
89011**     INSERT INTO t1 VALUES(1, 2, 3.1);
89012**
89013**   Register (x):        2    (type integer)
89014**   Register (x+1):      1    (type integer)
89015**   Register (x+2):      NULL (type NULL)
89016**   Register (x+3):      3.1  (type real)
89017*/
89018
89019/*
89020** A foreign key constraint requires that the key columns in the parent
89021** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
89022** Given that pParent is the parent table for foreign key constraint pFKey,
89023** search the schema for a unique index on the parent key columns.
89024**
89025** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
89026** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
89027** is set to point to the unique index.
89028**
89029** If the parent key consists of a single column (the foreign key constraint
89030** is not a composite foreign key), output variable *paiCol is set to NULL.
89031** Otherwise, it is set to point to an allocated array of size N, where
89032** N is the number of columns in the parent key. The first element of the
89033** array is the index of the child table column that is mapped by the FK
89034** constraint to the parent table column stored in the left-most column
89035** of index *ppIdx. The second element of the array is the index of the
89036** child table column that corresponds to the second left-most column of
89037** *ppIdx, and so on.
89038**
89039** If the required index cannot be found, either because:
89040**
89041**   1) The named parent key columns do not exist, or
89042**
89043**   2) The named parent key columns do exist, but are not subject to a
89044**      UNIQUE or PRIMARY KEY constraint, or
89045**
89046**   3) No parent key columns were provided explicitly as part of the
89047**      foreign key definition, and the parent table does not have a
89048**      PRIMARY KEY, or
89049**
89050**   4) No parent key columns were provided explicitly as part of the
89051**      foreign key definition, and the PRIMARY KEY of the parent table
89052**      consists of a a different number of columns to the child key in
89053**      the child table.
89054**
89055** then non-zero is returned, and a "foreign key mismatch" error loaded
89056** into pParse. If an OOM error occurs, non-zero is returned and the
89057** pParse->db->mallocFailed flag is set.
89058*/
89059SQLITE_PRIVATE int sqlite3FkLocateIndex(
89060  Parse *pParse,                  /* Parse context to store any error in */
89061  Table *pParent,                 /* Parent table of FK constraint pFKey */
89062  FKey *pFKey,                    /* Foreign key to find index for */
89063  Index **ppIdx,                  /* OUT: Unique index on parent table */
89064  int **paiCol                    /* OUT: Map of index columns in pFKey */
89065){
89066  Index *pIdx = 0;                    /* Value to return via *ppIdx */
89067  int *aiCol = 0;                     /* Value to return via *paiCol */
89068  int nCol = pFKey->nCol;             /* Number of columns in parent key */
89069  char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */
89070
89071  /* The caller is responsible for zeroing output parameters. */
89072  assert( ppIdx && *ppIdx==0 );
89073  assert( !paiCol || *paiCol==0 );
89074  assert( pParse );
89075
89076  /* If this is a non-composite (single column) foreign key, check if it
89077  ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
89078  ** and *paiCol set to zero and return early.
89079  **
89080  ** Otherwise, for a composite foreign key (more than one column), allocate
89081  ** space for the aiCol array (returned via output parameter *paiCol).
89082  ** Non-composite foreign keys do not require the aiCol array.
89083  */
89084  if( nCol==1 ){
89085    /* The FK maps to the IPK if any of the following are true:
89086    **
89087    **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
89088    **      mapped to the primary key of table pParent, or
89089    **   2) The FK is explicitly mapped to a column declared as INTEGER
89090    **      PRIMARY KEY.
89091    */
89092    if( pParent->iPKey>=0 ){
89093      if( !zKey ) return 0;
89094      if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
89095    }
89096  }else if( paiCol ){
89097    assert( nCol>1 );
89098    aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
89099    if( !aiCol ) return 1;
89100    *paiCol = aiCol;
89101  }
89102
89103  for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
89104    if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){
89105      /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
89106      ** of columns. If each indexed column corresponds to a foreign key
89107      ** column of pFKey, then this index is a winner.  */
89108
89109      if( zKey==0 ){
89110        /* If zKey is NULL, then this foreign key is implicitly mapped to
89111        ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
89112        ** identified by the test (Index.autoIndex==2).  */
89113        if( pIdx->autoIndex==2 ){
89114          if( aiCol ){
89115            int i;
89116            for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
89117          }
89118          break;
89119        }
89120      }else{
89121        /* If zKey is non-NULL, then this foreign key was declared to
89122        ** map to an explicit list of columns in table pParent. Check if this
89123        ** index matches those columns. Also, check that the index uses
89124        ** the default collation sequences for each column. */
89125        int i, j;
89126        for(i=0; i<nCol; i++){
89127          int iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
89128          char *zDfltColl;                  /* Def. collation for column */
89129          char *zIdxCol;                    /* Name of indexed column */
89130
89131          /* If the index uses a collation sequence that is different from
89132          ** the default collation sequence for the column, this index is
89133          ** unusable. Bail out early in this case.  */
89134          zDfltColl = pParent->aCol[iCol].zColl;
89135          if( !zDfltColl ){
89136            zDfltColl = "BINARY";
89137          }
89138          if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
89139
89140          zIdxCol = pParent->aCol[iCol].zName;
89141          for(j=0; j<nCol; j++){
89142            if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
89143              if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
89144              break;
89145            }
89146          }
89147          if( j==nCol ) break;
89148        }
89149        if( i==nCol ) break;      /* pIdx is usable */
89150      }
89151    }
89152  }
89153
89154  if( !pIdx ){
89155    if( !pParse->disableTriggers ){
89156      sqlite3ErrorMsg(pParse,
89157           "foreign key mismatch - \"%w\" referencing \"%w\"",
89158           pFKey->pFrom->zName, pFKey->zTo);
89159    }
89160    sqlite3DbFree(pParse->db, aiCol);
89161    return 1;
89162  }
89163
89164  *ppIdx = pIdx;
89165  return 0;
89166}
89167
89168/*
89169** This function is called when a row is inserted into or deleted from the
89170** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
89171** on the child table of pFKey, this function is invoked twice for each row
89172** affected - once to "delete" the old row, and then again to "insert" the
89173** new row.
89174**
89175** Each time it is called, this function generates VDBE code to locate the
89176** row in the parent table that corresponds to the row being inserted into
89177** or deleted from the child table. If the parent row can be found, no
89178** special action is taken. Otherwise, if the parent row can *not* be
89179** found in the parent table:
89180**
89181**   Operation | FK type   | Action taken
89182**   --------------------------------------------------------------------------
89183**   INSERT      immediate   Increment the "immediate constraint counter".
89184**
89185**   DELETE      immediate   Decrement the "immediate constraint counter".
89186**
89187**   INSERT      deferred    Increment the "deferred constraint counter".
89188**
89189**   DELETE      deferred    Decrement the "deferred constraint counter".
89190**
89191** These operations are identified in the comment at the top of this file
89192** (fkey.c) as "I.1" and "D.1".
89193*/
89194static void fkLookupParent(
89195  Parse *pParse,        /* Parse context */
89196  int iDb,              /* Index of database housing pTab */
89197  Table *pTab,          /* Parent table of FK pFKey */
89198  Index *pIdx,          /* Unique index on parent key columns in pTab */
89199  FKey *pFKey,          /* Foreign key constraint */
89200  int *aiCol,           /* Map from parent key columns to child table columns */
89201  int regData,          /* Address of array containing child table row */
89202  int nIncr,            /* Increment constraint counter by this */
89203  int isIgnore          /* If true, pretend pTab contains all NULL values */
89204){
89205  int i;                                    /* Iterator variable */
89206  Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */
89207  int iCur = pParse->nTab - 1;              /* Cursor number to use */
89208  int iOk = sqlite3VdbeMakeLabel(v);        /* jump here if parent key found */
89209
89210  /* If nIncr is less than zero, then check at runtime if there are any
89211  ** outstanding constraints to resolve. If there are not, there is no need
89212  ** to check if deleting this row resolves any outstanding violations.
89213  **
89214  ** Check if any of the key columns in the child table row are NULL. If
89215  ** any are, then the constraint is considered satisfied. No need to
89216  ** search for a matching row in the parent table.  */
89217  if( nIncr<0 ){
89218    sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
89219  }
89220  for(i=0; i<pFKey->nCol; i++){
89221    int iReg = aiCol[i] + regData + 1;
89222    sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
89223  }
89224
89225  if( isIgnore==0 ){
89226    if( pIdx==0 ){
89227      /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
89228      ** column of the parent table (table pTab).  */
89229      int iMustBeInt;               /* Address of MustBeInt instruction */
89230      int regTemp = sqlite3GetTempReg(pParse);
89231
89232      /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
89233      ** apply the affinity of the parent key). If this fails, then there
89234      ** is no matching parent key. Before using MustBeInt, make a copy of
89235      ** the value. Otherwise, the value inserted into the child key column
89236      ** will have INTEGER affinity applied to it, which may not be correct.  */
89237      sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
89238      iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
89239
89240      /* If the parent table is the same as the child table, and we are about
89241      ** to increment the constraint-counter (i.e. this is an INSERT operation),
89242      ** then check if the row being inserted matches itself. If so, do not
89243      ** increment the constraint-counter.  */
89244      if( pTab==pFKey->pFrom && nIncr==1 ){
89245        sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp);
89246      }
89247
89248      sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
89249      sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);
89250      sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
89251      sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
89252      sqlite3VdbeJumpHere(v, iMustBeInt);
89253      sqlite3ReleaseTempReg(pParse, regTemp);
89254    }else{
89255      int nCol = pFKey->nCol;
89256      int regTemp = sqlite3GetTempRange(pParse, nCol);
89257      int regRec = sqlite3GetTempReg(pParse);
89258      KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
89259
89260      sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
89261      sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
89262      for(i=0; i<nCol; i++){
89263        sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
89264      }
89265
89266      /* If the parent table is the same as the child table, and we are about
89267      ** to increment the constraint-counter (i.e. this is an INSERT operation),
89268      ** then check if the row being inserted matches itself. If so, do not
89269      ** increment the constraint-counter.
89270      **
89271      ** If any of the parent-key values are NULL, then the row cannot match
89272      ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
89273      ** of the parent-key values are NULL (at this point it is known that
89274      ** none of the child key values are).
89275      */
89276      if( pTab==pFKey->pFrom && nIncr==1 ){
89277        int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
89278        for(i=0; i<nCol; i++){
89279          int iChild = aiCol[i]+1+regData;
89280          int iParent = pIdx->aiColumn[i]+1+regData;
89281          assert( aiCol[i]!=pTab->iPKey );
89282          if( pIdx->aiColumn[i]==pTab->iPKey ){
89283            /* The parent key is a composite key that includes the IPK column */
89284            iParent = regData;
89285          }
89286          sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent);
89287          sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
89288        }
89289        sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
89290      }
89291
89292      sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
89293      sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v,pIdx), P4_TRANSIENT);
89294      sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0);
89295
89296      sqlite3ReleaseTempReg(pParse, regRec);
89297      sqlite3ReleaseTempRange(pParse, regTemp, nCol);
89298    }
89299  }
89300
89301  if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
89302    /* Special case: If this is an INSERT statement that will insert exactly
89303    ** one row into the table, raise a constraint immediately instead of
89304    ** incrementing a counter. This is necessary as the VM code is being
89305    ** generated for will not open a statement transaction.  */
89306    assert( nIncr==1 );
89307    sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
89308        OE_Abort, "foreign key constraint failed", P4_STATIC
89309    );
89310  }else{
89311    if( nIncr>0 && pFKey->isDeferred==0 ){
89312      sqlite3ParseToplevel(pParse)->mayAbort = 1;
89313    }
89314    sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
89315  }
89316
89317  sqlite3VdbeResolveLabel(v, iOk);
89318  sqlite3VdbeAddOp1(v, OP_Close, iCur);
89319}
89320
89321/*
89322** This function is called to generate code executed when a row is deleted
89323** from the parent table of foreign key constraint pFKey and, if pFKey is
89324** deferred, when a row is inserted into the same table. When generating
89325** code for an SQL UPDATE operation, this function may be called twice -
89326** once to "delete" the old row and once to "insert" the new row.
89327**
89328** The code generated by this function scans through the rows in the child
89329** table that correspond to the parent table row being deleted or inserted.
89330** For each child row found, one of the following actions is taken:
89331**
89332**   Operation | FK type   | Action taken
89333**   --------------------------------------------------------------------------
89334**   DELETE      immediate   Increment the "immediate constraint counter".
89335**                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
89336**                           throw a "foreign key constraint failed" exception.
89337**
89338**   INSERT      immediate   Decrement the "immediate constraint counter".
89339**
89340**   DELETE      deferred    Increment the "deferred constraint counter".
89341**                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
89342**                           throw a "foreign key constraint failed" exception.
89343**
89344**   INSERT      deferred    Decrement the "deferred constraint counter".
89345**
89346** These operations are identified in the comment at the top of this file
89347** (fkey.c) as "I.2" and "D.2".
89348*/
89349static void fkScanChildren(
89350  Parse *pParse,                  /* Parse context */
89351  SrcList *pSrc,                  /* SrcList containing the table to scan */
89352  Table *pTab,
89353  Index *pIdx,                    /* Foreign key index */
89354  FKey *pFKey,                    /* Foreign key relationship */
89355  int *aiCol,                     /* Map from pIdx cols to child table cols */
89356  int regData,                    /* Referenced table data starts here */
89357  int nIncr                       /* Amount to increment deferred counter by */
89358){
89359  sqlite3 *db = pParse->db;       /* Database handle */
89360  int i;                          /* Iterator variable */
89361  Expr *pWhere = 0;               /* WHERE clause to scan with */
89362  NameContext sNameContext;       /* Context used to resolve WHERE clause */
89363  WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */
89364  int iFkIfZero = 0;              /* Address of OP_FkIfZero */
89365  Vdbe *v = sqlite3GetVdbe(pParse);
89366
89367  assert( !pIdx || pIdx->pTable==pTab );
89368
89369  if( nIncr<0 ){
89370    iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
89371  }
89372
89373  /* Create an Expr object representing an SQL expression like:
89374  **
89375  **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
89376  **
89377  ** The collation sequence used for the comparison should be that of
89378  ** the parent key columns. The affinity of the parent key column should
89379  ** be applied to each child key value before the comparison takes place.
89380  */
89381  for(i=0; i<pFKey->nCol; i++){
89382    Expr *pLeft;                  /* Value from parent table row */
89383    Expr *pRight;                 /* Column ref to child table */
89384    Expr *pEq;                    /* Expression (pLeft = pRight) */
89385    int iCol;                     /* Index of column in child table */
89386    const char *zCol;             /* Name of column in child table */
89387
89388    pLeft = sqlite3Expr(db, TK_REGISTER, 0);
89389    if( pLeft ){
89390      /* Set the collation sequence and affinity of the LHS of each TK_EQ
89391      ** expression to the parent key column defaults.  */
89392      if( pIdx ){
89393        Column *pCol;
89394        const char *zColl;
89395        iCol = pIdx->aiColumn[i];
89396        pCol = &pTab->aCol[iCol];
89397        if( pTab->iPKey==iCol ) iCol = -1;
89398        pLeft->iTable = regData+iCol+1;
89399        pLeft->affinity = pCol->affinity;
89400        zColl = pCol->zColl;
89401        if( zColl==0 ) zColl = db->pDfltColl->zName;
89402        pLeft = sqlite3ExprAddCollateString(pParse, pLeft, zColl);
89403      }else{
89404        pLeft->iTable = regData;
89405        pLeft->affinity = SQLITE_AFF_INTEGER;
89406      }
89407    }
89408    iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
89409    assert( iCol>=0 );
89410    zCol = pFKey->pFrom->aCol[iCol].zName;
89411    pRight = sqlite3Expr(db, TK_ID, zCol);
89412    pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
89413    pWhere = sqlite3ExprAnd(db, pWhere, pEq);
89414  }
89415
89416  /* If the child table is the same as the parent table, and this scan
89417  ** is taking place as part of a DELETE operation (operation D.2), omit the
89418  ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE
89419  ** clause, where $rowid is the rowid of the row being deleted.  */
89420  if( pTab==pFKey->pFrom && nIncr>0 ){
89421    Expr *pEq;                    /* Expression (pLeft = pRight) */
89422    Expr *pLeft;                  /* Value from parent table row */
89423    Expr *pRight;                 /* Column ref to child table */
89424    pLeft = sqlite3Expr(db, TK_REGISTER, 0);
89425    pRight = sqlite3Expr(db, TK_COLUMN, 0);
89426    if( pLeft && pRight ){
89427      pLeft->iTable = regData;
89428      pLeft->affinity = SQLITE_AFF_INTEGER;
89429      pRight->iTable = pSrc->a[0].iCursor;
89430      pRight->iColumn = -1;
89431    }
89432    pEq = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
89433    pWhere = sqlite3ExprAnd(db, pWhere, pEq);
89434  }
89435
89436  /* Resolve the references in the WHERE clause. */
89437  memset(&sNameContext, 0, sizeof(NameContext));
89438  sNameContext.pSrcList = pSrc;
89439  sNameContext.pParse = pParse;
89440  sqlite3ResolveExprNames(&sNameContext, pWhere);
89441
89442  /* Create VDBE to loop through the entries in pSrc that match the WHERE
89443  ** clause. If the constraint is not deferred, throw an exception for
89444  ** each row found. Otherwise, for deferred constraints, increment the
89445  ** deferred constraint counter by nIncr for each row selected.  */
89446  pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
89447  if( nIncr>0 && pFKey->isDeferred==0 ){
89448    sqlite3ParseToplevel(pParse)->mayAbort = 1;
89449  }
89450  sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
89451  if( pWInfo ){
89452    sqlite3WhereEnd(pWInfo);
89453  }
89454
89455  /* Clean up the WHERE clause constructed above. */
89456  sqlite3ExprDelete(db, pWhere);
89457  if( iFkIfZero ){
89458    sqlite3VdbeJumpHere(v, iFkIfZero);
89459  }
89460}
89461
89462/*
89463** This function returns a pointer to the head of a linked list of FK
89464** constraints for which table pTab is the parent table. For example,
89465** given the following schema:
89466**
89467**   CREATE TABLE t1(a PRIMARY KEY);
89468**   CREATE TABLE t2(b REFERENCES t1(a);
89469**
89470** Calling this function with table "t1" as an argument returns a pointer
89471** to the FKey structure representing the foreign key constraint on table
89472** "t2". Calling this function with "t2" as the argument would return a
89473** NULL pointer (as there are no FK constraints for which t2 is the parent
89474** table).
89475*/
89476SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
89477  int nName = sqlite3Strlen30(pTab->zName);
89478  return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
89479}
89480
89481/*
89482** The second argument is a Trigger structure allocated by the
89483** fkActionTrigger() routine. This function deletes the Trigger structure
89484** and all of its sub-components.
89485**
89486** The Trigger structure or any of its sub-components may be allocated from
89487** the lookaside buffer belonging to database handle dbMem.
89488*/
89489static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
89490  if( p ){
89491    TriggerStep *pStep = p->step_list;
89492    sqlite3ExprDelete(dbMem, pStep->pWhere);
89493    sqlite3ExprListDelete(dbMem, pStep->pExprList);
89494    sqlite3SelectDelete(dbMem, pStep->pSelect);
89495    sqlite3ExprDelete(dbMem, p->pWhen);
89496    sqlite3DbFree(dbMem, p);
89497  }
89498}
89499
89500/*
89501** This function is called to generate code that runs when table pTab is
89502** being dropped from the database. The SrcList passed as the second argument
89503** to this function contains a single entry guaranteed to resolve to
89504** table pTab.
89505**
89506** Normally, no code is required. However, if either
89507**
89508**   (a) The table is the parent table of a FK constraint, or
89509**   (b) The table is the child table of a deferred FK constraint and it is
89510**       determined at runtime that there are outstanding deferred FK
89511**       constraint violations in the database,
89512**
89513** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
89514** the table from the database. Triggers are disabled while running this
89515** DELETE, but foreign key actions are not.
89516*/
89517SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
89518  sqlite3 *db = pParse->db;
89519  if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
89520    int iSkip = 0;
89521    Vdbe *v = sqlite3GetVdbe(pParse);
89522
89523    assert( v );                  /* VDBE has already been allocated */
89524    if( sqlite3FkReferences(pTab)==0 ){
89525      /* Search for a deferred foreign key constraint for which this table
89526      ** is the child table. If one cannot be found, return without
89527      ** generating any VDBE code. If one can be found, then jump over
89528      ** the entire DELETE if there are no outstanding deferred constraints
89529      ** when this statement is run.  */
89530      FKey *p;
89531      for(p=pTab->pFKey; p; p=p->pNextFrom){
89532        if( p->isDeferred ) break;
89533      }
89534      if( !p ) return;
89535      iSkip = sqlite3VdbeMakeLabel(v);
89536      sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip);
89537    }
89538
89539    pParse->disableTriggers = 1;
89540    sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
89541    pParse->disableTriggers = 0;
89542
89543    /* If the DELETE has generated immediate foreign key constraint
89544    ** violations, halt the VDBE and return an error at this point, before
89545    ** any modifications to the schema are made. This is because statement
89546    ** transactions are not able to rollback schema changes.  */
89547    sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
89548    sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
89549        OE_Abort, "foreign key constraint failed", P4_STATIC
89550    );
89551
89552    if( iSkip ){
89553      sqlite3VdbeResolveLabel(v, iSkip);
89554    }
89555  }
89556}
89557
89558/*
89559** This function is called when inserting, deleting or updating a row of
89560** table pTab to generate VDBE code to perform foreign key constraint
89561** processing for the operation.
89562**
89563** For a DELETE operation, parameter regOld is passed the index of the
89564** first register in an array of (pTab->nCol+1) registers containing the
89565** rowid of the row being deleted, followed by each of the column values
89566** of the row being deleted, from left to right. Parameter regNew is passed
89567** zero in this case.
89568**
89569** For an INSERT operation, regOld is passed zero and regNew is passed the
89570** first register of an array of (pTab->nCol+1) registers containing the new
89571** row data.
89572**
89573** For an UPDATE operation, this function is called twice. Once before
89574** the original record is deleted from the table using the calling convention
89575** described for DELETE. Then again after the original record is deleted
89576** but before the new record is inserted using the INSERT convention.
89577*/
89578SQLITE_PRIVATE void sqlite3FkCheck(
89579  Parse *pParse,                  /* Parse context */
89580  Table *pTab,                    /* Row is being deleted from this table */
89581  int regOld,                     /* Previous row data is stored here */
89582  int regNew                      /* New row data is stored here */
89583){
89584  sqlite3 *db = pParse->db;       /* Database handle */
89585  FKey *pFKey;                    /* Used to iterate through FKs */
89586  int iDb;                        /* Index of database containing pTab */
89587  const char *zDb;                /* Name of database containing pTab */
89588  int isIgnoreErrors = pParse->disableTriggers;
89589
89590  /* Exactly one of regOld and regNew should be non-zero. */
89591  assert( (regOld==0)!=(regNew==0) );
89592
89593  /* If foreign-keys are disabled, this function is a no-op. */
89594  if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
89595
89596  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
89597  zDb = db->aDb[iDb].zName;
89598
89599  /* Loop through all the foreign key constraints for which pTab is the
89600  ** child table (the table that the foreign key definition is part of).  */
89601  for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
89602    Table *pTo;                   /* Parent table of foreign key pFKey */
89603    Index *pIdx = 0;              /* Index on key columns in pTo */
89604    int *aiFree = 0;
89605    int *aiCol;
89606    int iCol;
89607    int i;
89608    int isIgnore = 0;
89609
89610    /* Find the parent table of this foreign key. Also find a unique index
89611    ** on the parent key columns in the parent table. If either of these
89612    ** schema items cannot be located, set an error in pParse and return
89613    ** early.  */
89614    if( pParse->disableTriggers ){
89615      pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
89616    }else{
89617      pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
89618    }
89619    if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
89620      assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
89621      if( !isIgnoreErrors || db->mallocFailed ) return;
89622      if( pTo==0 ){
89623        /* If isIgnoreErrors is true, then a table is being dropped. In this
89624        ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
89625        ** before actually dropping it in order to check FK constraints.
89626        ** If the parent table of an FK constraint on the current table is
89627        ** missing, behave as if it is empty. i.e. decrement the relevant
89628        ** FK counter for each row of the current table with non-NULL keys.
89629        */
89630        Vdbe *v = sqlite3GetVdbe(pParse);
89631        int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
89632        for(i=0; i<pFKey->nCol; i++){
89633          int iReg = pFKey->aCol[i].iFrom + regOld + 1;
89634          sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump);
89635        }
89636        sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
89637      }
89638      continue;
89639    }
89640    assert( pFKey->nCol==1 || (aiFree && pIdx) );
89641
89642    if( aiFree ){
89643      aiCol = aiFree;
89644    }else{
89645      iCol = pFKey->aCol[0].iFrom;
89646      aiCol = &iCol;
89647    }
89648    for(i=0; i<pFKey->nCol; i++){
89649      if( aiCol[i]==pTab->iPKey ){
89650        aiCol[i] = -1;
89651      }
89652#ifndef SQLITE_OMIT_AUTHORIZATION
89653      /* Request permission to read the parent key columns. If the
89654      ** authorization callback returns SQLITE_IGNORE, behave as if any
89655      ** values read from the parent table are NULL. */
89656      if( db->xAuth ){
89657        int rcauth;
89658        char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
89659        rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
89660        isIgnore = (rcauth==SQLITE_IGNORE);
89661      }
89662#endif
89663    }
89664
89665    /* Take a shared-cache advisory read-lock on the parent table. Allocate
89666    ** a cursor to use to search the unique index on the parent key columns
89667    ** in the parent table.  */
89668    sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
89669    pParse->nTab++;
89670
89671    if( regOld!=0 ){
89672      /* A row is being removed from the child table. Search for the parent.
89673      ** If the parent does not exist, removing the child row resolves an
89674      ** outstanding foreign key constraint violation. */
89675      fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
89676    }
89677    if( regNew!=0 ){
89678      /* A row is being added to the child table. If a parent row cannot
89679      ** be found, adding the child row has violated the FK constraint. */
89680      fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
89681    }
89682
89683    sqlite3DbFree(db, aiFree);
89684  }
89685
89686  /* Loop through all the foreign key constraints that refer to this table */
89687  for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
89688    Index *pIdx = 0;              /* Foreign key index for pFKey */
89689    SrcList *pSrc;
89690    int *aiCol = 0;
89691
89692    if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
89693      assert( regOld==0 && regNew!=0 );
89694      /* Inserting a single row into a parent table cannot cause an immediate
89695      ** foreign key violation. So do nothing in this case.  */
89696      continue;
89697    }
89698
89699    if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
89700      if( !isIgnoreErrors || db->mallocFailed ) return;
89701      continue;
89702    }
89703    assert( aiCol || pFKey->nCol==1 );
89704
89705    /* Create a SrcList structure containing a single table (the table
89706    ** the foreign key that refers to this table is attached to). This
89707    ** is required for the sqlite3WhereXXX() interface.  */
89708    pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
89709    if( pSrc ){
89710      struct SrcList_item *pItem = pSrc->a;
89711      pItem->pTab = pFKey->pFrom;
89712      pItem->zName = pFKey->pFrom->zName;
89713      pItem->pTab->nRef++;
89714      pItem->iCursor = pParse->nTab++;
89715
89716      if( regNew!=0 ){
89717        fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
89718      }
89719      if( regOld!=0 ){
89720        /* If there is a RESTRICT action configured for the current operation
89721        ** on the parent table of this FK, then throw an exception
89722        ** immediately if the FK constraint is violated, even if this is a
89723        ** deferred trigger. That's what RESTRICT means. To defer checking
89724        ** the constraint, the FK should specify NO ACTION (represented
89725        ** using OE_None). NO ACTION is the default.  */
89726        fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
89727      }
89728      pItem->zName = 0;
89729      sqlite3SrcListDelete(db, pSrc);
89730    }
89731    sqlite3DbFree(db, aiCol);
89732  }
89733}
89734
89735#define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
89736
89737/*
89738** This function is called before generating code to update or delete a
89739** row contained in table pTab.
89740*/
89741SQLITE_PRIVATE u32 sqlite3FkOldmask(
89742  Parse *pParse,                  /* Parse context */
89743  Table *pTab                     /* Table being modified */
89744){
89745  u32 mask = 0;
89746  if( pParse->db->flags&SQLITE_ForeignKeys ){
89747    FKey *p;
89748    int i;
89749    for(p=pTab->pFKey; p; p=p->pNextFrom){
89750      for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
89751    }
89752    for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
89753      Index *pIdx = 0;
89754      sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
89755      if( pIdx ){
89756        for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
89757      }
89758    }
89759  }
89760  return mask;
89761}
89762
89763/*
89764** This function is called before generating code to update or delete a
89765** row contained in table pTab. If the operation is a DELETE, then
89766** parameter aChange is passed a NULL value. For an UPDATE, aChange points
89767** to an array of size N, where N is the number of columns in table pTab.
89768** If the i'th column is not modified by the UPDATE, then the corresponding
89769** entry in the aChange[] array is set to -1. If the column is modified,
89770** the value is 0 or greater. Parameter chngRowid is set to true if the
89771** UPDATE statement modifies the rowid fields of the table.
89772**
89773** If any foreign key processing will be required, this function returns
89774** true. If there is no foreign key related processing, this function
89775** returns false.
89776*/
89777SQLITE_PRIVATE int sqlite3FkRequired(
89778  Parse *pParse,                  /* Parse context */
89779  Table *pTab,                    /* Table being modified */
89780  int *aChange,                   /* Non-NULL for UPDATE operations */
89781  int chngRowid                   /* True for UPDATE that affects rowid */
89782){
89783  if( pParse->db->flags&SQLITE_ForeignKeys ){
89784    if( !aChange ){
89785      /* A DELETE operation. Foreign key processing is required if the
89786      ** table in question is either the child or parent table for any
89787      ** foreign key constraint.  */
89788      return (sqlite3FkReferences(pTab) || pTab->pFKey);
89789    }else{
89790      /* This is an UPDATE. Foreign key processing is only required if the
89791      ** operation modifies one or more child or parent key columns. */
89792      int i;
89793      FKey *p;
89794
89795      /* Check if any child key columns are being modified. */
89796      for(p=pTab->pFKey; p; p=p->pNextFrom){
89797        for(i=0; i<p->nCol; i++){
89798          int iChildKey = p->aCol[i].iFrom;
89799          if( aChange[iChildKey]>=0 ) return 1;
89800          if( iChildKey==pTab->iPKey && chngRowid ) return 1;
89801        }
89802      }
89803
89804      /* Check if any parent key columns are being modified. */
89805      for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
89806        for(i=0; i<p->nCol; i++){
89807          char *zKey = p->aCol[i].zCol;
89808          int iKey;
89809          for(iKey=0; iKey<pTab->nCol; iKey++){
89810            Column *pCol = &pTab->aCol[iKey];
89811            if( (zKey ? !sqlite3StrICmp(pCol->zName, zKey)
89812                      : (pCol->colFlags & COLFLAG_PRIMKEY)!=0) ){
89813              if( aChange[iKey]>=0 ) return 1;
89814              if( iKey==pTab->iPKey && chngRowid ) return 1;
89815            }
89816          }
89817        }
89818      }
89819    }
89820  }
89821  return 0;
89822}
89823
89824/*
89825** This function is called when an UPDATE or DELETE operation is being
89826** compiled on table pTab, which is the parent table of foreign-key pFKey.
89827** If the current operation is an UPDATE, then the pChanges parameter is
89828** passed a pointer to the list of columns being modified. If it is a
89829** DELETE, pChanges is passed a NULL pointer.
89830**
89831** It returns a pointer to a Trigger structure containing a trigger
89832** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
89833** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
89834** returned (these actions require no special handling by the triggers
89835** sub-system, code for them is created by fkScanChildren()).
89836**
89837** For example, if pFKey is the foreign key and pTab is table "p" in
89838** the following schema:
89839**
89840**   CREATE TABLE p(pk PRIMARY KEY);
89841**   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
89842**
89843** then the returned trigger structure is equivalent to:
89844**
89845**   CREATE TRIGGER ... DELETE ON p BEGIN
89846**     DELETE FROM c WHERE ck = old.pk;
89847**   END;
89848**
89849** The returned pointer is cached as part of the foreign key object. It
89850** is eventually freed along with the rest of the foreign key object by
89851** sqlite3FkDelete().
89852*/
89853static Trigger *fkActionTrigger(
89854  Parse *pParse,                  /* Parse context */
89855  Table *pTab,                    /* Table being updated or deleted from */
89856  FKey *pFKey,                    /* Foreign key to get action for */
89857  ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
89858){
89859  sqlite3 *db = pParse->db;       /* Database handle */
89860  int action;                     /* One of OE_None, OE_Cascade etc. */
89861  Trigger *pTrigger;              /* Trigger definition to return */
89862  int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
89863
89864  action = pFKey->aAction[iAction];
89865  pTrigger = pFKey->apTrigger[iAction];
89866
89867  if( action!=OE_None && !pTrigger ){
89868    u8 enableLookaside;           /* Copy of db->lookaside.bEnabled */
89869    char const *zFrom;            /* Name of child table */
89870    int nFrom;                    /* Length in bytes of zFrom */
89871    Index *pIdx = 0;              /* Parent key index for this FK */
89872    int *aiCol = 0;               /* child table cols -> parent key cols */
89873    TriggerStep *pStep = 0;        /* First (only) step of trigger program */
89874    Expr *pWhere = 0;             /* WHERE clause of trigger step */
89875    ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
89876    Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
89877    int i;                        /* Iterator variable */
89878    Expr *pWhen = 0;              /* WHEN clause for the trigger */
89879
89880    if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
89881    assert( aiCol || pFKey->nCol==1 );
89882
89883    for(i=0; i<pFKey->nCol; i++){
89884      Token tOld = { "old", 3 };  /* Literal "old" token */
89885      Token tNew = { "new", 3 };  /* Literal "new" token */
89886      Token tFromCol;             /* Name of column in child table */
89887      Token tToCol;               /* Name of column in parent table */
89888      int iFromCol;               /* Idx of column in child table */
89889      Expr *pEq;                  /* tFromCol = OLD.tToCol */
89890
89891      iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
89892      assert( iFromCol>=0 );
89893      tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
89894      tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
89895
89896      tToCol.n = sqlite3Strlen30(tToCol.z);
89897      tFromCol.n = sqlite3Strlen30(tFromCol.z);
89898
89899      /* Create the expression "OLD.zToCol = zFromCol". It is important
89900      ** that the "OLD.zToCol" term is on the LHS of the = operator, so
89901      ** that the affinity and collation sequence associated with the
89902      ** parent table are used for the comparison. */
89903      pEq = sqlite3PExpr(pParse, TK_EQ,
89904          sqlite3PExpr(pParse, TK_DOT,
89905            sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
89906            sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
89907          , 0),
89908          sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
89909      , 0);
89910      pWhere = sqlite3ExprAnd(db, pWhere, pEq);
89911
89912      /* For ON UPDATE, construct the next term of the WHEN clause.
89913      ** The final WHEN clause will be like this:
89914      **
89915      **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
89916      */
89917      if( pChanges ){
89918        pEq = sqlite3PExpr(pParse, TK_IS,
89919            sqlite3PExpr(pParse, TK_DOT,
89920              sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
89921              sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
89922              0),
89923            sqlite3PExpr(pParse, TK_DOT,
89924              sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
89925              sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
89926              0),
89927            0);
89928        pWhen = sqlite3ExprAnd(db, pWhen, pEq);
89929      }
89930
89931      if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
89932        Expr *pNew;
89933        if( action==OE_Cascade ){
89934          pNew = sqlite3PExpr(pParse, TK_DOT,
89935            sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
89936            sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
89937          , 0);
89938        }else if( action==OE_SetDflt ){
89939          Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
89940          if( pDflt ){
89941            pNew = sqlite3ExprDup(db, pDflt, 0);
89942          }else{
89943            pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
89944          }
89945        }else{
89946          pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
89947        }
89948        pList = sqlite3ExprListAppend(pParse, pList, pNew);
89949        sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
89950      }
89951    }
89952    sqlite3DbFree(db, aiCol);
89953
89954    zFrom = pFKey->pFrom->zName;
89955    nFrom = sqlite3Strlen30(zFrom);
89956
89957    if( action==OE_Restrict ){
89958      Token tFrom;
89959      Expr *pRaise;
89960
89961      tFrom.z = zFrom;
89962      tFrom.n = nFrom;
89963      pRaise = sqlite3Expr(db, TK_RAISE, "foreign key constraint failed");
89964      if( pRaise ){
89965        pRaise->affinity = OE_Abort;
89966      }
89967      pSelect = sqlite3SelectNew(pParse,
89968          sqlite3ExprListAppend(pParse, 0, pRaise),
89969          sqlite3SrcListAppend(db, 0, &tFrom, 0),
89970          pWhere,
89971          0, 0, 0, 0, 0, 0
89972      );
89973      pWhere = 0;
89974    }
89975
89976    /* Disable lookaside memory allocation */
89977    enableLookaside = db->lookaside.bEnabled;
89978    db->lookaside.bEnabled = 0;
89979
89980    pTrigger = (Trigger *)sqlite3DbMallocZero(db,
89981        sizeof(Trigger) +         /* struct Trigger */
89982        sizeof(TriggerStep) +     /* Single step in trigger program */
89983        nFrom + 1                 /* Space for pStep->target.z */
89984    );
89985    if( pTrigger ){
89986      pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
89987      pStep->target.z = (char *)&pStep[1];
89988      pStep->target.n = nFrom;
89989      memcpy((char *)pStep->target.z, zFrom, nFrom);
89990
89991      pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
89992      pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
89993      pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
89994      if( pWhen ){
89995        pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
89996        pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
89997      }
89998    }
89999
90000    /* Re-enable the lookaside buffer, if it was disabled earlier. */
90001    db->lookaside.bEnabled = enableLookaside;
90002
90003    sqlite3ExprDelete(db, pWhere);
90004    sqlite3ExprDelete(db, pWhen);
90005    sqlite3ExprListDelete(db, pList);
90006    sqlite3SelectDelete(db, pSelect);
90007    if( db->mallocFailed==1 ){
90008      fkTriggerDelete(db, pTrigger);
90009      return 0;
90010    }
90011    assert( pStep!=0 );
90012
90013    switch( action ){
90014      case OE_Restrict:
90015        pStep->op = TK_SELECT;
90016        break;
90017      case OE_Cascade:
90018        if( !pChanges ){
90019          pStep->op = TK_DELETE;
90020          break;
90021        }
90022      default:
90023        pStep->op = TK_UPDATE;
90024    }
90025    pStep->pTrig = pTrigger;
90026    pTrigger->pSchema = pTab->pSchema;
90027    pTrigger->pTabSchema = pTab->pSchema;
90028    pFKey->apTrigger[iAction] = pTrigger;
90029    pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
90030  }
90031
90032  return pTrigger;
90033}
90034
90035/*
90036** This function is called when deleting or updating a row to implement
90037** any required CASCADE, SET NULL or SET DEFAULT actions.
90038*/
90039SQLITE_PRIVATE void sqlite3FkActions(
90040  Parse *pParse,                  /* Parse context */
90041  Table *pTab,                    /* Table being updated or deleted from */
90042  ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
90043  int regOld                      /* Address of array containing old row */
90044){
90045  /* If foreign-key support is enabled, iterate through all FKs that
90046  ** refer to table pTab. If there is an action associated with the FK
90047  ** for this operation (either update or delete), invoke the associated
90048  ** trigger sub-program.  */
90049  if( pParse->db->flags&SQLITE_ForeignKeys ){
90050    FKey *pFKey;                  /* Iterator variable */
90051    for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
90052      Trigger *pAction = fkActionTrigger(pParse, pTab, pFKey, pChanges);
90053      if( pAction ){
90054        sqlite3CodeRowTriggerDirect(pParse, pAction, pTab, regOld, OE_Abort, 0);
90055      }
90056    }
90057  }
90058}
90059
90060#endif /* ifndef SQLITE_OMIT_TRIGGER */
90061
90062/*
90063** Free all memory associated with foreign key definitions attached to
90064** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
90065** hash table.
90066*/
90067SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
90068  FKey *pFKey;                    /* Iterator variable */
90069  FKey *pNext;                    /* Copy of pFKey->pNextFrom */
90070
90071  assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
90072  for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
90073
90074    /* Remove the FK from the fkeyHash hash table. */
90075    if( !db || db->pnBytesFreed==0 ){
90076      if( pFKey->pPrevTo ){
90077        pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
90078      }else{
90079        void *p = (void *)pFKey->pNextTo;
90080        const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
90081        sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), p);
90082      }
90083      if( pFKey->pNextTo ){
90084        pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
90085      }
90086    }
90087
90088    /* EV: R-30323-21917 Each foreign key constraint in SQLite is
90089    ** classified as either immediate or deferred.
90090    */
90091    assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
90092
90093    /* Delete any triggers created to implement actions for this FK. */
90094#ifndef SQLITE_OMIT_TRIGGER
90095    fkTriggerDelete(db, pFKey->apTrigger[0]);
90096    fkTriggerDelete(db, pFKey->apTrigger[1]);
90097#endif
90098
90099    pNext = pFKey->pNextFrom;
90100    sqlite3DbFree(db, pFKey);
90101  }
90102}
90103#endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
90104
90105/************** End of fkey.c ************************************************/
90106/************** Begin file insert.c ******************************************/
90107/*
90108** 2001 September 15
90109**
90110** The author disclaims copyright to this source code.  In place of
90111** a legal notice, here is a blessing:
90112**
90113**    May you do good and not evil.
90114**    May you find forgiveness for yourself and forgive others.
90115**    May you share freely, never taking more than you give.
90116**
90117*************************************************************************
90118** This file contains C code routines that are called by the parser
90119** to handle INSERT statements in SQLite.
90120*/
90121
90122/*
90123** Generate code that will open a table for reading.
90124*/
90125SQLITE_PRIVATE void sqlite3OpenTable(
90126  Parse *p,       /* Generate code into this VDBE */
90127  int iCur,       /* The cursor number of the table */
90128  int iDb,        /* The database index in sqlite3.aDb[] */
90129  Table *pTab,    /* The table to be opened */
90130  int opcode      /* OP_OpenRead or OP_OpenWrite */
90131){
90132  Vdbe *v;
90133  assert( !IsVirtual(pTab) );
90134  v = sqlite3GetVdbe(p);
90135  assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
90136  sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
90137  sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
90138  sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
90139  VdbeComment((v, "%s", pTab->zName));
90140}
90141
90142/*
90143** Return a pointer to the column affinity string associated with index
90144** pIdx. A column affinity string has one character for each column in
90145** the table, according to the affinity of the column:
90146**
90147**  Character      Column affinity
90148**  ------------------------------
90149**  'a'            TEXT
90150**  'b'            NONE
90151**  'c'            NUMERIC
90152**  'd'            INTEGER
90153**  'e'            REAL
90154**
90155** An extra 'd' is appended to the end of the string to cover the
90156** rowid that appears as the last column in every index.
90157**
90158** Memory for the buffer containing the column index affinity string
90159** is managed along with the rest of the Index structure. It will be
90160** released when sqlite3DeleteIndex() is called.
90161*/
90162SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
90163  if( !pIdx->zColAff ){
90164    /* The first time a column affinity string for a particular index is
90165    ** required, it is allocated and populated here. It is then stored as
90166    ** a member of the Index structure for subsequent use.
90167    **
90168    ** The column affinity string will eventually be deleted by
90169    ** sqliteDeleteIndex() when the Index structure itself is cleaned
90170    ** up.
90171    */
90172    int n;
90173    Table *pTab = pIdx->pTable;
90174    sqlite3 *db = sqlite3VdbeDb(v);
90175    pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+2);
90176    if( !pIdx->zColAff ){
90177      db->mallocFailed = 1;
90178      return 0;
90179    }
90180    for(n=0; n<pIdx->nColumn; n++){
90181      pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
90182    }
90183    pIdx->zColAff[n++] = SQLITE_AFF_INTEGER;
90184    pIdx->zColAff[n] = 0;
90185  }
90186
90187  return pIdx->zColAff;
90188}
90189
90190/*
90191** Set P4 of the most recently inserted opcode to a column affinity
90192** string for table pTab. A column affinity string has one character
90193** for each column indexed by the index, according to the affinity of the
90194** column:
90195**
90196**  Character      Column affinity
90197**  ------------------------------
90198**  'a'            TEXT
90199**  'b'            NONE
90200**  'c'            NUMERIC
90201**  'd'            INTEGER
90202**  'e'            REAL
90203*/
90204SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
90205  /* The first time a column affinity string for a particular table
90206  ** is required, it is allocated and populated here. It is then
90207  ** stored as a member of the Table structure for subsequent use.
90208  **
90209  ** The column affinity string will eventually be deleted by
90210  ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
90211  */
90212  if( !pTab->zColAff ){
90213    char *zColAff;
90214    int i;
90215    sqlite3 *db = sqlite3VdbeDb(v);
90216
90217    zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
90218    if( !zColAff ){
90219      db->mallocFailed = 1;
90220      return;
90221    }
90222
90223    for(i=0; i<pTab->nCol; i++){
90224      zColAff[i] = pTab->aCol[i].affinity;
90225    }
90226    zColAff[pTab->nCol] = '\0';
90227
90228    pTab->zColAff = zColAff;
90229  }
90230
90231  sqlite3VdbeChangeP4(v, -1, pTab->zColAff, P4_TRANSIENT);
90232}
90233
90234/*
90235** Return non-zero if the table pTab in database iDb or any of its indices
90236** have been opened at any point in the VDBE program beginning at location
90237** iStartAddr throught the end of the program.  This is used to see if
90238** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can
90239** run without using temporary table for the results of the SELECT.
90240*/
90241static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
90242  Vdbe *v = sqlite3GetVdbe(p);
90243  int i;
90244  int iEnd = sqlite3VdbeCurrentAddr(v);
90245#ifndef SQLITE_OMIT_VIRTUALTABLE
90246  VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
90247#endif
90248
90249  for(i=iStartAddr; i<iEnd; i++){
90250    VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
90251    assert( pOp!=0 );
90252    if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
90253      Index *pIndex;
90254      int tnum = pOp->p2;
90255      if( tnum==pTab->tnum ){
90256        return 1;
90257      }
90258      for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
90259        if( tnum==pIndex->tnum ){
90260          return 1;
90261        }
90262      }
90263    }
90264#ifndef SQLITE_OMIT_VIRTUALTABLE
90265    if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
90266      assert( pOp->p4.pVtab!=0 );
90267      assert( pOp->p4type==P4_VTAB );
90268      return 1;
90269    }
90270#endif
90271  }
90272  return 0;
90273}
90274
90275#ifndef SQLITE_OMIT_AUTOINCREMENT
90276/*
90277** Locate or create an AutoincInfo structure associated with table pTab
90278** which is in database iDb.  Return the register number for the register
90279** that holds the maximum rowid.
90280**
90281** There is at most one AutoincInfo structure per table even if the
90282** same table is autoincremented multiple times due to inserts within
90283** triggers.  A new AutoincInfo structure is created if this is the
90284** first use of table pTab.  On 2nd and subsequent uses, the original
90285** AutoincInfo structure is used.
90286**
90287** Three memory locations are allocated:
90288**
90289**   (1)  Register to hold the name of the pTab table.
90290**   (2)  Register to hold the maximum ROWID of pTab.
90291**   (3)  Register to hold the rowid in sqlite_sequence of pTab
90292**
90293** The 2nd register is the one that is returned.  That is all the
90294** insert routine needs to know about.
90295*/
90296static int autoIncBegin(
90297  Parse *pParse,      /* Parsing context */
90298  int iDb,            /* Index of the database holding pTab */
90299  Table *pTab         /* The table we are writing to */
90300){
90301  int memId = 0;      /* Register holding maximum rowid */
90302  if( pTab->tabFlags & TF_Autoincrement ){
90303    Parse *pToplevel = sqlite3ParseToplevel(pParse);
90304    AutoincInfo *pInfo;
90305
90306    pInfo = pToplevel->pAinc;
90307    while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
90308    if( pInfo==0 ){
90309      pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
90310      if( pInfo==0 ) return 0;
90311      pInfo->pNext = pToplevel->pAinc;
90312      pToplevel->pAinc = pInfo;
90313      pInfo->pTab = pTab;
90314      pInfo->iDb = iDb;
90315      pToplevel->nMem++;                  /* Register to hold name of table */
90316      pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
90317      pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
90318    }
90319    memId = pInfo->regCtr;
90320  }
90321  return memId;
90322}
90323
90324/*
90325** This routine generates code that will initialize all of the
90326** register used by the autoincrement tracker.
90327*/
90328SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
90329  AutoincInfo *p;            /* Information about an AUTOINCREMENT */
90330  sqlite3 *db = pParse->db;  /* The database connection */
90331  Db *pDb;                   /* Database only autoinc table */
90332  int memId;                 /* Register holding max rowid */
90333  int addr;                  /* A VDBE address */
90334  Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
90335
90336  /* This routine is never called during trigger-generation.  It is
90337  ** only called from the top-level */
90338  assert( pParse->pTriggerTab==0 );
90339  assert( pParse==sqlite3ParseToplevel(pParse) );
90340
90341  assert( v );   /* We failed long ago if this is not so */
90342  for(p = pParse->pAinc; p; p = p->pNext){
90343    pDb = &db->aDb[p->iDb];
90344    memId = p->regCtr;
90345    assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
90346    sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
90347    sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1);
90348    addr = sqlite3VdbeCurrentAddr(v);
90349    sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
90350    sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
90351    sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
90352    sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
90353    sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
90354    sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
90355    sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
90356    sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
90357    sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
90358    sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
90359    sqlite3VdbeAddOp0(v, OP_Close);
90360  }
90361}
90362
90363/*
90364** Update the maximum rowid for an autoincrement calculation.
90365**
90366** This routine should be called when the top of the stack holds a
90367** new rowid that is about to be inserted.  If that new rowid is
90368** larger than the maximum rowid in the memId memory cell, then the
90369** memory cell is updated.  The stack is unchanged.
90370*/
90371static void autoIncStep(Parse *pParse, int memId, int regRowid){
90372  if( memId>0 ){
90373    sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
90374  }
90375}
90376
90377/*
90378** This routine generates the code needed to write autoincrement
90379** maximum rowid values back into the sqlite_sequence register.
90380** Every statement that might do an INSERT into an autoincrement
90381** table (either directly or through triggers) needs to call this
90382** routine just before the "exit" code.
90383*/
90384SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
90385  AutoincInfo *p;
90386  Vdbe *v = pParse->pVdbe;
90387  sqlite3 *db = pParse->db;
90388
90389  assert( v );
90390  for(p = pParse->pAinc; p; p = p->pNext){
90391    Db *pDb = &db->aDb[p->iDb];
90392    int j1, j2, j3, j4, j5;
90393    int iRec;
90394    int memId = p->regCtr;
90395
90396    iRec = sqlite3GetTempReg(pParse);
90397    assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
90398    sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
90399    j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
90400    j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
90401    j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
90402    j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
90403    sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
90404    sqlite3VdbeJumpHere(v, j2);
90405    sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
90406    j5 = sqlite3VdbeAddOp0(v, OP_Goto);
90407    sqlite3VdbeJumpHere(v, j4);
90408    sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
90409    sqlite3VdbeJumpHere(v, j1);
90410    sqlite3VdbeJumpHere(v, j5);
90411    sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
90412    sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
90413    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
90414    sqlite3VdbeAddOp0(v, OP_Close);
90415    sqlite3ReleaseTempReg(pParse, iRec);
90416  }
90417}
90418#else
90419/*
90420** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
90421** above are all no-ops
90422*/
90423# define autoIncBegin(A,B,C) (0)
90424# define autoIncStep(A,B,C)
90425#endif /* SQLITE_OMIT_AUTOINCREMENT */
90426
90427
90428/*
90429** Generate code for a co-routine that will evaluate a subquery one
90430** row at a time.
90431**
90432** The pSelect parameter is the subquery that the co-routine will evaluation.
90433** Information about the location of co-routine and the registers it will use
90434** is returned by filling in the pDest object.
90435**
90436** Registers are allocated as follows:
90437**
90438**   pDest->iSDParm      The register holding the next entry-point of the
90439**                       co-routine.  Run the co-routine to its next breakpoint
90440**                       by calling "OP_Yield $X" where $X is pDest->iSDParm.
90441**
90442**   pDest->iSDParm+1    The register holding the "completed" flag for the
90443**                       co-routine. This register is 0 if the previous Yield
90444**                       generated a new result row, or 1 if the subquery
90445**                       has completed.  If the Yield is called again
90446**                       after this register becomes 1, then the VDBE will
90447**                       halt with an SQLITE_INTERNAL error.
90448**
90449**   pDest->iSdst        First result register.
90450**
90451**   pDest->nSdst        Number of result registers.
90452**
90453** This routine handles all of the register allocation and fills in the
90454** pDest structure appropriately.
90455**
90456** Here is a schematic of the generated code assuming that X is the
90457** co-routine entry-point register reg[pDest->iSDParm], that EOF is the
90458** completed flag reg[pDest->iSDParm+1], and R and S are the range of
90459** registers that hold the result set, reg[pDest->iSdst] through
90460** reg[pDest->iSdst+pDest->nSdst-1]:
90461**
90462**         X <- A
90463**         EOF <- 0
90464**         goto B
90465**      A: setup for the SELECT
90466**         loop rows in the SELECT
90467**           load results into registers R..S
90468**           yield X
90469**         end loop
90470**         cleanup after the SELECT
90471**         EOF <- 1
90472**         yield X
90473**         halt-error
90474**      B:
90475**
90476** To use this subroutine, the caller generates code as follows:
90477**
90478**         [ Co-routine generated by this subroutine, shown above ]
90479**      S: yield X
90480**         if EOF goto E
90481**         if skip this row, goto C
90482**         if terminate loop, goto E
90483**         deal with this row
90484**      C: goto S
90485**      E:
90486*/
90487SQLITE_PRIVATE int sqlite3CodeCoroutine(Parse *pParse, Select *pSelect, SelectDest *pDest){
90488  int regYield;       /* Register holding co-routine entry-point */
90489  int regEof;         /* Register holding co-routine completion flag */
90490  int addrTop;        /* Top of the co-routine */
90491  int j1;             /* Jump instruction */
90492  int rc;             /* Result code */
90493  Vdbe *v;            /* VDBE under construction */
90494
90495  regYield = ++pParse->nMem;
90496  regEof = ++pParse->nMem;
90497  v = sqlite3GetVdbe(pParse);
90498  addrTop = sqlite3VdbeCurrentAddr(v);
90499  sqlite3VdbeAddOp2(v, OP_Integer, addrTop+2, regYield); /* X <- A */
90500  VdbeComment((v, "Co-routine entry point"));
90501  sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof);           /* EOF <- 0 */
90502  VdbeComment((v, "Co-routine completion flag"));
90503  sqlite3SelectDestInit(pDest, SRT_Coroutine, regYield);
90504  j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
90505  rc = sqlite3Select(pParse, pSelect, pDest);
90506  assert( pParse->nErr==0 || rc );
90507  if( pParse->db->mallocFailed && rc==SQLITE_OK ) rc = SQLITE_NOMEM;
90508  if( rc ) return rc;
90509  sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof);            /* EOF <- 1 */
90510  sqlite3VdbeAddOp1(v, OP_Yield, regYield);   /* yield X */
90511  sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
90512  VdbeComment((v, "End of coroutine"));
90513  sqlite3VdbeJumpHere(v, j1);                             /* label B: */
90514  return rc;
90515}
90516
90517
90518
90519/* Forward declaration */
90520static int xferOptimization(
90521  Parse *pParse,        /* Parser context */
90522  Table *pDest,         /* The table we are inserting into */
90523  Select *pSelect,      /* A SELECT statement to use as the data source */
90524  int onError,          /* How to handle constraint errors */
90525  int iDbDest           /* The database of pDest */
90526);
90527
90528/*
90529** This routine is call to handle SQL of the following forms:
90530**
90531**    insert into TABLE (IDLIST) values(EXPRLIST)
90532**    insert into TABLE (IDLIST) select
90533**
90534** The IDLIST following the table name is always optional.  If omitted,
90535** then a list of all columns for the table is substituted.  The IDLIST
90536** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
90537**
90538** The pList parameter holds EXPRLIST in the first form of the INSERT
90539** statement above, and pSelect is NULL.  For the second form, pList is
90540** NULL and pSelect is a pointer to the select statement used to generate
90541** data for the insert.
90542**
90543** The code generated follows one of four templates.  For a simple
90544** select with data coming from a VALUES clause, the code executes
90545** once straight down through.  Pseudo-code follows (we call this
90546** the "1st template"):
90547**
90548**         open write cursor to <table> and its indices
90549**         puts VALUES clause expressions onto the stack
90550**         write the resulting record into <table>
90551**         cleanup
90552**
90553** The three remaining templates assume the statement is of the form
90554**
90555**   INSERT INTO <table> SELECT ...
90556**
90557** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
90558** in other words if the SELECT pulls all columns from a single table
90559** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
90560** if <table2> and <table1> are distinct tables but have identical
90561** schemas, including all the same indices, then a special optimization
90562** is invoked that copies raw records from <table2> over to <table1>.
90563** See the xferOptimization() function for the implementation of this
90564** template.  This is the 2nd template.
90565**
90566**         open a write cursor to <table>
90567**         open read cursor on <table2>
90568**         transfer all records in <table2> over to <table>
90569**         close cursors
90570**         foreach index on <table>
90571**           open a write cursor on the <table> index
90572**           open a read cursor on the corresponding <table2> index
90573**           transfer all records from the read to the write cursors
90574**           close cursors
90575**         end foreach
90576**
90577** The 3rd template is for when the second template does not apply
90578** and the SELECT clause does not read from <table> at any time.
90579** The generated code follows this template:
90580**
90581**         EOF <- 0
90582**         X <- A
90583**         goto B
90584**      A: setup for the SELECT
90585**         loop over the rows in the SELECT
90586**           load values into registers R..R+n
90587**           yield X
90588**         end loop
90589**         cleanup after the SELECT
90590**         EOF <- 1
90591**         yield X
90592**         goto A
90593**      B: open write cursor to <table> and its indices
90594**      C: yield X
90595**         if EOF goto D
90596**         insert the select result into <table> from R..R+n
90597**         goto C
90598**      D: cleanup
90599**
90600** The 4th template is used if the insert statement takes its
90601** values from a SELECT but the data is being inserted into a table
90602** that is also read as part of the SELECT.  In the third form,
90603** we have to use a intermediate table to store the results of
90604** the select.  The template is like this:
90605**
90606**         EOF <- 0
90607**         X <- A
90608**         goto B
90609**      A: setup for the SELECT
90610**         loop over the tables in the SELECT
90611**           load value into register R..R+n
90612**           yield X
90613**         end loop
90614**         cleanup after the SELECT
90615**         EOF <- 1
90616**         yield X
90617**         halt-error
90618**      B: open temp table
90619**      L: yield X
90620**         if EOF goto M
90621**         insert row from R..R+n into temp table
90622**         goto L
90623**      M: open write cursor to <table> and its indices
90624**         rewind temp table
90625**      C: loop over rows of intermediate table
90626**           transfer values form intermediate table into <table>
90627**         end loop
90628**      D: cleanup
90629*/
90630SQLITE_PRIVATE void sqlite3Insert(
90631  Parse *pParse,        /* Parser context */
90632  SrcList *pTabList,    /* Name of table into which we are inserting */
90633  ExprList *pList,      /* List of values to be inserted */
90634  Select *pSelect,      /* A SELECT statement to use as the data source */
90635  IdList *pColumn,      /* Column names corresponding to IDLIST. */
90636  int onError           /* How to handle constraint errors */
90637){
90638  sqlite3 *db;          /* The main database structure */
90639  Table *pTab;          /* The table to insert into.  aka TABLE */
90640  char *zTab;           /* Name of the table into which we are inserting */
90641  const char *zDb;      /* Name of the database holding this table */
90642  int i, j, idx;        /* Loop counters */
90643  Vdbe *v;              /* Generate code into this virtual machine */
90644  Index *pIdx;          /* For looping over indices of the table */
90645  int nColumn;          /* Number of columns in the data */
90646  int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
90647  int baseCur = 0;      /* VDBE Cursor number for pTab */
90648  int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
90649  int endOfLoop;        /* Label for the end of the insertion loop */
90650  int useTempTable = 0; /* Store SELECT results in intermediate table */
90651  int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
90652  int addrInsTop = 0;   /* Jump to label "D" */
90653  int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
90654  int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
90655  SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
90656  int iDb;              /* Index of database holding TABLE */
90657  Db *pDb;              /* The database containing table being inserted into */
90658  int appendFlag = 0;   /* True if the insert is likely to be an append */
90659
90660  /* Register allocations */
90661  int regFromSelect = 0;/* Base register for data coming from SELECT */
90662  int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
90663  int regRowCount = 0;  /* Memory cell used for the row counter */
90664  int regIns;           /* Block of regs holding rowid+data being inserted */
90665  int regRowid;         /* registers holding insert rowid */
90666  int regData;          /* register holding first column to insert */
90667  int regEof = 0;       /* Register recording end of SELECT data */
90668  int *aRegIdx = 0;     /* One register allocated to each index */
90669
90670#ifndef SQLITE_OMIT_TRIGGER
90671  int isView;                 /* True if attempting to insert into a view */
90672  Trigger *pTrigger;          /* List of triggers on pTab, if required */
90673  int tmask;                  /* Mask of trigger times */
90674#endif
90675
90676  db = pParse->db;
90677  memset(&dest, 0, sizeof(dest));
90678  if( pParse->nErr || db->mallocFailed ){
90679    goto insert_cleanup;
90680  }
90681
90682  /* Locate the table into which we will be inserting new information.
90683  */
90684  assert( pTabList->nSrc==1 );
90685  zTab = pTabList->a[0].zName;
90686  if( NEVER(zTab==0) ) goto insert_cleanup;
90687  pTab = sqlite3SrcListLookup(pParse, pTabList);
90688  if( pTab==0 ){
90689    goto insert_cleanup;
90690  }
90691  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
90692  assert( iDb<db->nDb );
90693  pDb = &db->aDb[iDb];
90694  zDb = pDb->zName;
90695  if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
90696    goto insert_cleanup;
90697  }
90698
90699  /* Figure out if we have any triggers and if the table being
90700  ** inserted into is a view
90701  */
90702#ifndef SQLITE_OMIT_TRIGGER
90703  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
90704  isView = pTab->pSelect!=0;
90705#else
90706# define pTrigger 0
90707# define tmask 0
90708# define isView 0
90709#endif
90710#ifdef SQLITE_OMIT_VIEW
90711# undef isView
90712# define isView 0
90713#endif
90714  assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
90715
90716  /* If pTab is really a view, make sure it has been initialized.
90717  ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
90718  ** module table).
90719  */
90720  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
90721    goto insert_cleanup;
90722  }
90723
90724  /* Ensure that:
90725  *  (a) the table is not read-only,
90726  *  (b) that if it is a view then ON INSERT triggers exist
90727  */
90728  if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
90729    goto insert_cleanup;
90730  }
90731
90732  /* Allocate a VDBE
90733  */
90734  v = sqlite3GetVdbe(pParse);
90735  if( v==0 ) goto insert_cleanup;
90736  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
90737  sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
90738
90739#ifndef SQLITE_OMIT_XFER_OPT
90740  /* If the statement is of the form
90741  **
90742  **       INSERT INTO <table1> SELECT * FROM <table2>;
90743  **
90744  ** Then special optimizations can be applied that make the transfer
90745  ** very fast and which reduce fragmentation of indices.
90746  **
90747  ** This is the 2nd template.
90748  */
90749  if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
90750    assert( !pTrigger );
90751    assert( pList==0 );
90752    goto insert_end;
90753  }
90754#endif /* SQLITE_OMIT_XFER_OPT */
90755
90756  /* If this is an AUTOINCREMENT table, look up the sequence number in the
90757  ** sqlite_sequence table and store it in memory cell regAutoinc.
90758  */
90759  regAutoinc = autoIncBegin(pParse, iDb, pTab);
90760
90761  /* Figure out how many columns of data are supplied.  If the data
90762  ** is coming from a SELECT statement, then generate a co-routine that
90763  ** produces a single row of the SELECT on each invocation.  The
90764  ** co-routine is the common header to the 3rd and 4th templates.
90765  */
90766  if( pSelect ){
90767    /* Data is coming from a SELECT.  Generate a co-routine to run that
90768    ** SELECT. */
90769    int rc = sqlite3CodeCoroutine(pParse, pSelect, &dest);
90770    if( rc ) goto insert_cleanup;
90771
90772    regEof = dest.iSDParm + 1;
90773    regFromSelect = dest.iSdst;
90774    assert( pSelect->pEList );
90775    nColumn = pSelect->pEList->nExpr;
90776    assert( dest.nSdst==nColumn );
90777
90778    /* Set useTempTable to TRUE if the result of the SELECT statement
90779    ** should be written into a temporary table (template 4).  Set to
90780    ** FALSE if each* row of the SELECT can be written directly into
90781    ** the destination table (template 3).
90782    **
90783    ** A temp table must be used if the table being updated is also one
90784    ** of the tables being read by the SELECT statement.  Also use a
90785    ** temp table in the case of row triggers.
90786    */
90787    if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
90788      useTempTable = 1;
90789    }
90790
90791    if( useTempTable ){
90792      /* Invoke the coroutine to extract information from the SELECT
90793      ** and add it to a transient table srcTab.  The code generated
90794      ** here is from the 4th template:
90795      **
90796      **      B: open temp table
90797      **      L: yield X
90798      **         if EOF goto M
90799      **         insert row from R..R+n into temp table
90800      **         goto L
90801      **      M: ...
90802      */
90803      int regRec;          /* Register to hold packed record */
90804      int regTempRowid;    /* Register to hold temp table ROWID */
90805      int addrTop;         /* Label "L" */
90806      int addrIf;          /* Address of jump to M */
90807
90808      srcTab = pParse->nTab++;
90809      regRec = sqlite3GetTempReg(pParse);
90810      regTempRowid = sqlite3GetTempReg(pParse);
90811      sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
90812      addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
90813      addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
90814      sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
90815      sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
90816      sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
90817      sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
90818      sqlite3VdbeJumpHere(v, addrIf);
90819      sqlite3ReleaseTempReg(pParse, regRec);
90820      sqlite3ReleaseTempReg(pParse, regTempRowid);
90821    }
90822  }else{
90823    /* This is the case if the data for the INSERT is coming from a VALUES
90824    ** clause
90825    */
90826    NameContext sNC;
90827    memset(&sNC, 0, sizeof(sNC));
90828    sNC.pParse = pParse;
90829    srcTab = -1;
90830    assert( useTempTable==0 );
90831    nColumn = pList ? pList->nExpr : 0;
90832    for(i=0; i<nColumn; i++){
90833      if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
90834        goto insert_cleanup;
90835      }
90836    }
90837  }
90838
90839  /* Make sure the number of columns in the source data matches the number
90840  ** of columns to be inserted into the table.
90841  */
90842  if( IsVirtual(pTab) ){
90843    for(i=0; i<pTab->nCol; i++){
90844      nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
90845    }
90846  }
90847  if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
90848    sqlite3ErrorMsg(pParse,
90849       "table %S has %d columns but %d values were supplied",
90850       pTabList, 0, pTab->nCol-nHidden, nColumn);
90851    goto insert_cleanup;
90852  }
90853  if( pColumn!=0 && nColumn!=pColumn->nId ){
90854    sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
90855    goto insert_cleanup;
90856  }
90857
90858  /* If the INSERT statement included an IDLIST term, then make sure
90859  ** all elements of the IDLIST really are columns of the table and
90860  ** remember the column indices.
90861  **
90862  ** If the table has an INTEGER PRIMARY KEY column and that column
90863  ** is named in the IDLIST, then record in the keyColumn variable
90864  ** the index into IDLIST of the primary key column.  keyColumn is
90865  ** the index of the primary key as it appears in IDLIST, not as
90866  ** is appears in the original table.  (The index of the primary
90867  ** key in the original table is pTab->iPKey.)
90868  */
90869  if( pColumn ){
90870    for(i=0; i<pColumn->nId; i++){
90871      pColumn->a[i].idx = -1;
90872    }
90873    for(i=0; i<pColumn->nId; i++){
90874      for(j=0; j<pTab->nCol; j++){
90875        if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
90876          pColumn->a[i].idx = j;
90877          if( j==pTab->iPKey ){
90878            keyColumn = i;
90879          }
90880          break;
90881        }
90882      }
90883      if( j>=pTab->nCol ){
90884        if( sqlite3IsRowid(pColumn->a[i].zName) ){
90885          keyColumn = i;
90886        }else{
90887          sqlite3ErrorMsg(pParse, "table %S has no column named %s",
90888              pTabList, 0, pColumn->a[i].zName);
90889          pParse->checkSchema = 1;
90890          goto insert_cleanup;
90891        }
90892      }
90893    }
90894  }
90895
90896  /* If there is no IDLIST term but the table has an integer primary
90897  ** key, the set the keyColumn variable to the primary key column index
90898  ** in the original table definition.
90899  */
90900  if( pColumn==0 && nColumn>0 ){
90901    keyColumn = pTab->iPKey;
90902  }
90903
90904  /* Initialize the count of rows to be inserted
90905  */
90906  if( db->flags & SQLITE_CountRows ){
90907    regRowCount = ++pParse->nMem;
90908    sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
90909  }
90910
90911  /* If this is not a view, open the table and and all indices */
90912  if( !isView ){
90913    int nIdx;
90914
90915    baseCur = pParse->nTab;
90916    nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
90917    aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
90918    if( aRegIdx==0 ){
90919      goto insert_cleanup;
90920    }
90921    for(i=0; i<nIdx; i++){
90922      aRegIdx[i] = ++pParse->nMem;
90923    }
90924  }
90925
90926  /* This is the top of the main insertion loop */
90927  if( useTempTable ){
90928    /* This block codes the top of loop only.  The complete loop is the
90929    ** following pseudocode (template 4):
90930    **
90931    **         rewind temp table
90932    **      C: loop over rows of intermediate table
90933    **           transfer values form intermediate table into <table>
90934    **         end loop
90935    **      D: ...
90936    */
90937    addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
90938    addrCont = sqlite3VdbeCurrentAddr(v);
90939  }else if( pSelect ){
90940    /* This block codes the top of loop only.  The complete loop is the
90941    ** following pseudocode (template 3):
90942    **
90943    **      C: yield X
90944    **         if EOF goto D
90945    **         insert the select result into <table> from R..R+n
90946    **         goto C
90947    **      D: ...
90948    */
90949    addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
90950    addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
90951  }
90952
90953  /* Allocate registers for holding the rowid of the new row,
90954  ** the content of the new row, and the assemblied row record.
90955  */
90956  regRowid = regIns = pParse->nMem+1;
90957  pParse->nMem += pTab->nCol + 1;
90958  if( IsVirtual(pTab) ){
90959    regRowid++;
90960    pParse->nMem++;
90961  }
90962  regData = regRowid+1;
90963
90964  /* Run the BEFORE and INSTEAD OF triggers, if there are any
90965  */
90966  endOfLoop = sqlite3VdbeMakeLabel(v);
90967  if( tmask & TRIGGER_BEFORE ){
90968    int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
90969
90970    /* build the NEW.* reference row.  Note that if there is an INTEGER
90971    ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
90972    ** translated into a unique ID for the row.  But on a BEFORE trigger,
90973    ** we do not know what the unique ID will be (because the insert has
90974    ** not happened yet) so we substitute a rowid of -1
90975    */
90976    if( keyColumn<0 ){
90977      sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
90978    }else{
90979      int j1;
90980      if( useTempTable ){
90981        sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
90982      }else{
90983        assert( pSelect==0 );  /* Otherwise useTempTable is true */
90984        sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
90985      }
90986      j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
90987      sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
90988      sqlite3VdbeJumpHere(v, j1);
90989      sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
90990    }
90991
90992    /* Cannot have triggers on a virtual table. If it were possible,
90993    ** this block would have to account for hidden column.
90994    */
90995    assert( !IsVirtual(pTab) );
90996
90997    /* Create the new column data
90998    */
90999    for(i=0; i<pTab->nCol; i++){
91000      if( pColumn==0 ){
91001        j = i;
91002      }else{
91003        for(j=0; j<pColumn->nId; j++){
91004          if( pColumn->a[j].idx==i ) break;
91005        }
91006      }
91007      if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
91008        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
91009      }else if( useTempTable ){
91010        sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
91011      }else{
91012        assert( pSelect==0 ); /* Otherwise useTempTable is true */
91013        sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
91014      }
91015    }
91016
91017    /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
91018    ** do not attempt any conversions before assembling the record.
91019    ** If this is a real table, attempt conversions as required by the
91020    ** table column affinities.
91021    */
91022    if( !isView ){
91023      sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
91024      sqlite3TableAffinityStr(v, pTab);
91025    }
91026
91027    /* Fire BEFORE or INSTEAD OF triggers */
91028    sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
91029        pTab, regCols-pTab->nCol-1, onError, endOfLoop);
91030
91031    sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
91032  }
91033
91034  /* Push the record number for the new entry onto the stack.  The
91035  ** record number is a randomly generate integer created by NewRowid
91036  ** except when the table has an INTEGER PRIMARY KEY column, in which
91037  ** case the record number is the same as that column.
91038  */
91039  if( !isView ){
91040    if( IsVirtual(pTab) ){
91041      /* The row that the VUpdate opcode will delete: none */
91042      sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
91043    }
91044    if( keyColumn>=0 ){
91045      if( useTempTable ){
91046        sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
91047      }else if( pSelect ){
91048        sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
91049      }else{
91050        VdbeOp *pOp;
91051        sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
91052        pOp = sqlite3VdbeGetOp(v, -1);
91053        if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
91054          appendFlag = 1;
91055          pOp->opcode = OP_NewRowid;
91056          pOp->p1 = baseCur;
91057          pOp->p2 = regRowid;
91058          pOp->p3 = regAutoinc;
91059        }
91060      }
91061      /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
91062      ** to generate a unique primary key value.
91063      */
91064      if( !appendFlag ){
91065        int j1;
91066        if( !IsVirtual(pTab) ){
91067          j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
91068          sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
91069          sqlite3VdbeJumpHere(v, j1);
91070        }else{
91071          j1 = sqlite3VdbeCurrentAddr(v);
91072          sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
91073        }
91074        sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
91075      }
91076    }else if( IsVirtual(pTab) ){
91077      sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
91078    }else{
91079      sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
91080      appendFlag = 1;
91081    }
91082    autoIncStep(pParse, regAutoinc, regRowid);
91083
91084    /* Push onto the stack, data for all columns of the new entry, beginning
91085    ** with the first column.
91086    */
91087    nHidden = 0;
91088    for(i=0; i<pTab->nCol; i++){
91089      int iRegStore = regRowid+1+i;
91090      if( i==pTab->iPKey ){
91091        /* The value of the INTEGER PRIMARY KEY column is always a NULL.
91092        ** Whenever this column is read, the record number will be substituted
91093        ** in its place.  So will fill this column with a NULL to avoid
91094        ** taking up data space with information that will never be used. */
91095        sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
91096        continue;
91097      }
91098      if( pColumn==0 ){
91099        if( IsHiddenColumn(&pTab->aCol[i]) ){
91100          assert( IsVirtual(pTab) );
91101          j = -1;
91102          nHidden++;
91103        }else{
91104          j = i - nHidden;
91105        }
91106      }else{
91107        for(j=0; j<pColumn->nId; j++){
91108          if( pColumn->a[j].idx==i ) break;
91109        }
91110      }
91111      if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
91112        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
91113      }else if( useTempTable ){
91114        sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
91115      }else if( pSelect ){
91116        sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
91117      }else{
91118        sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
91119      }
91120    }
91121
91122    /* Generate code to check constraints and generate index keys and
91123    ** do the insertion.
91124    */
91125#ifndef SQLITE_OMIT_VIRTUALTABLE
91126    if( IsVirtual(pTab) ){
91127      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
91128      sqlite3VtabMakeWritable(pParse, pTab);
91129      sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
91130      sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
91131      sqlite3MayAbort(pParse);
91132    }else
91133#endif
91134    {
91135      int isReplace;    /* Set to true if constraints may cause a replace */
91136      sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
91137          keyColumn>=0, 0, onError, endOfLoop, &isReplace
91138      );
91139      sqlite3FkCheck(pParse, pTab, 0, regIns);
91140      sqlite3CompleteInsertion(
91141          pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
91142      );
91143    }
91144  }
91145
91146  /* Update the count of rows that are inserted
91147  */
91148  if( (db->flags & SQLITE_CountRows)!=0 ){
91149    sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
91150  }
91151
91152  if( pTrigger ){
91153    /* Code AFTER triggers */
91154    sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
91155        pTab, regData-2-pTab->nCol, onError, endOfLoop);
91156  }
91157
91158  /* The bottom of the main insertion loop, if the data source
91159  ** is a SELECT statement.
91160  */
91161  sqlite3VdbeResolveLabel(v, endOfLoop);
91162  if( useTempTable ){
91163    sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
91164    sqlite3VdbeJumpHere(v, addrInsTop);
91165    sqlite3VdbeAddOp1(v, OP_Close, srcTab);
91166  }else if( pSelect ){
91167    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
91168    sqlite3VdbeJumpHere(v, addrInsTop);
91169  }
91170
91171  if( !IsVirtual(pTab) && !isView ){
91172    /* Close all tables opened */
91173    sqlite3VdbeAddOp1(v, OP_Close, baseCur);
91174    for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
91175      sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
91176    }
91177  }
91178
91179insert_end:
91180  /* Update the sqlite_sequence table by storing the content of the
91181  ** maximum rowid counter values recorded while inserting into
91182  ** autoincrement tables.
91183  */
91184  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
91185    sqlite3AutoincrementEnd(pParse);
91186  }
91187
91188  /*
91189  ** Return the number of rows inserted. If this routine is
91190  ** generating code because of a call to sqlite3NestedParse(), do not
91191  ** invoke the callback function.
91192  */
91193  if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
91194    sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
91195    sqlite3VdbeSetNumCols(v, 1);
91196    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
91197  }
91198
91199insert_cleanup:
91200  sqlite3SrcListDelete(db, pTabList);
91201  sqlite3ExprListDelete(db, pList);
91202  sqlite3SelectDelete(db, pSelect);
91203  sqlite3IdListDelete(db, pColumn);
91204  sqlite3DbFree(db, aRegIdx);
91205}
91206
91207/* Make sure "isView" and other macros defined above are undefined. Otherwise
91208** thely may interfere with compilation of other functions in this file
91209** (or in another file, if this file becomes part of the amalgamation).  */
91210#ifdef isView
91211 #undef isView
91212#endif
91213#ifdef pTrigger
91214 #undef pTrigger
91215#endif
91216#ifdef tmask
91217 #undef tmask
91218#endif
91219
91220
91221/*
91222** Generate code to do constraint checks prior to an INSERT or an UPDATE.
91223**
91224** The input is a range of consecutive registers as follows:
91225**
91226**    1.  The rowid of the row after the update.
91227**
91228**    2.  The data in the first column of the entry after the update.
91229**
91230**    i.  Data from middle columns...
91231**
91232**    N.  The data in the last column of the entry after the update.
91233**
91234** The regRowid parameter is the index of the register containing (1).
91235**
91236** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
91237** the address of a register containing the rowid before the update takes
91238** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
91239** is false, indicating an INSERT statement, then a non-zero rowidChng
91240** indicates that the rowid was explicitly specified as part of the
91241** INSERT statement. If rowidChng is false, it means that  the rowid is
91242** computed automatically in an insert or that the rowid value is not
91243** modified by an update.
91244**
91245** The code generated by this routine store new index entries into
91246** registers identified by aRegIdx[].  No index entry is created for
91247** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
91248** the same as the order of indices on the linked list of indices
91249** attached to the table.
91250**
91251** This routine also generates code to check constraints.  NOT NULL,
91252** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
91253** then the appropriate action is performed.  There are five possible
91254** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
91255**
91256**  Constraint type  Action       What Happens
91257**  ---------------  ----------   ----------------------------------------
91258**  any              ROLLBACK     The current transaction is rolled back and
91259**                                sqlite3_exec() returns immediately with a
91260**                                return code of SQLITE_CONSTRAINT.
91261**
91262**  any              ABORT        Back out changes from the current command
91263**                                only (do not do a complete rollback) then
91264**                                cause sqlite3_exec() to return immediately
91265**                                with SQLITE_CONSTRAINT.
91266**
91267**  any              FAIL         Sqlite3_exec() returns immediately with a
91268**                                return code of SQLITE_CONSTRAINT.  The
91269**                                transaction is not rolled back and any
91270**                                prior changes are retained.
91271**
91272**  any              IGNORE       The record number and data is popped from
91273**                                the stack and there is an immediate jump
91274**                                to label ignoreDest.
91275**
91276**  NOT NULL         REPLACE      The NULL value is replace by the default
91277**                                value for that column.  If the default value
91278**                                is NULL, the action is the same as ABORT.
91279**
91280**  UNIQUE           REPLACE      The other row that conflicts with the row
91281**                                being inserted is removed.
91282**
91283**  CHECK            REPLACE      Illegal.  The results in an exception.
91284**
91285** Which action to take is determined by the overrideError parameter.
91286** Or if overrideError==OE_Default, then the pParse->onError parameter
91287** is used.  Or if pParse->onError==OE_Default then the onError value
91288** for the constraint is used.
91289**
91290** The calling routine must open a read/write cursor for pTab with
91291** cursor number "baseCur".  All indices of pTab must also have open
91292** read/write cursors with cursor number baseCur+i for the i-th cursor.
91293** Except, if there is no possibility of a REPLACE action then
91294** cursors do not need to be open for indices where aRegIdx[i]==0.
91295*/
91296SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
91297  Parse *pParse,      /* The parser context */
91298  Table *pTab,        /* the table into which we are inserting */
91299  int baseCur,        /* Index of a read/write cursor pointing at pTab */
91300  int regRowid,       /* Index of the range of input registers */
91301  int *aRegIdx,       /* Register used by each index.  0 for unused indices */
91302  int rowidChng,      /* True if the rowid might collide with existing entry */
91303  int isUpdate,       /* True for UPDATE, False for INSERT */
91304  int overrideError,  /* Override onError to this if not OE_Default */
91305  int ignoreDest,     /* Jump to this label on an OE_Ignore resolution */
91306  int *pbMayReplace   /* OUT: Set to true if constraint may cause a replace */
91307){
91308  int i;              /* loop counter */
91309  Vdbe *v;            /* VDBE under constrution */
91310  int nCol;           /* Number of columns */
91311  int onError;        /* Conflict resolution strategy */
91312  int j1;             /* Addresss of jump instruction */
91313  int j2 = 0, j3;     /* Addresses of jump instructions */
91314  int regData;        /* Register containing first data column */
91315  int iCur;           /* Table cursor number */
91316  Index *pIdx;         /* Pointer to one of the indices */
91317  sqlite3 *db;         /* Database connection */
91318  int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
91319  int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
91320
91321  db = pParse->db;
91322  v = sqlite3GetVdbe(pParse);
91323  assert( v!=0 );
91324  assert( pTab->pSelect==0 );  /* This table is not a VIEW */
91325  nCol = pTab->nCol;
91326  regData = regRowid + 1;
91327
91328  /* Test all NOT NULL constraints.
91329  */
91330  for(i=0; i<nCol; i++){
91331    if( i==pTab->iPKey ){
91332      continue;
91333    }
91334    onError = pTab->aCol[i].notNull;
91335    if( onError==OE_None ) continue;
91336    if( overrideError!=OE_Default ){
91337      onError = overrideError;
91338    }else if( onError==OE_Default ){
91339      onError = OE_Abort;
91340    }
91341    if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
91342      onError = OE_Abort;
91343    }
91344    assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
91345        || onError==OE_Ignore || onError==OE_Replace );
91346    switch( onError ){
91347      case OE_Abort:
91348        sqlite3MayAbort(pParse);
91349      case OE_Rollback:
91350      case OE_Fail: {
91351        char *zMsg;
91352        sqlite3VdbeAddOp3(v, OP_HaltIfNull,
91353                          SQLITE_CONSTRAINT_NOTNULL, onError, regData+i);
91354        zMsg = sqlite3MPrintf(db, "%s.%s may not be NULL",
91355                              pTab->zName, pTab->aCol[i].zName);
91356        sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
91357        break;
91358      }
91359      case OE_Ignore: {
91360        sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
91361        break;
91362      }
91363      default: {
91364        assert( onError==OE_Replace );
91365        j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
91366        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
91367        sqlite3VdbeJumpHere(v, j1);
91368        break;
91369      }
91370    }
91371  }
91372
91373  /* Test all CHECK constraints
91374  */
91375#ifndef SQLITE_OMIT_CHECK
91376  if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
91377    ExprList *pCheck = pTab->pCheck;
91378    pParse->ckBase = regData;
91379    onError = overrideError!=OE_Default ? overrideError : OE_Abort;
91380    for(i=0; i<pCheck->nExpr; i++){
91381      int allOk = sqlite3VdbeMakeLabel(v);
91382      sqlite3ExprIfTrue(pParse, pCheck->a[i].pExpr, allOk, SQLITE_JUMPIFNULL);
91383      if( onError==OE_Ignore ){
91384        sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
91385      }else{
91386        char *zConsName = pCheck->a[i].zName;
91387        if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
91388        if( zConsName ){
91389          zConsName = sqlite3MPrintf(db, "constraint %s failed", zConsName);
91390        }else{
91391          zConsName = 0;
91392        }
91393        sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
91394                              onError, zConsName, P4_DYNAMIC);
91395      }
91396      sqlite3VdbeResolveLabel(v, allOk);
91397    }
91398  }
91399#endif /* !defined(SQLITE_OMIT_CHECK) */
91400
91401  /* If we have an INTEGER PRIMARY KEY, make sure the primary key
91402  ** of the new record does not previously exist.  Except, if this
91403  ** is an UPDATE and the primary key is not changing, that is OK.
91404  */
91405  if( rowidChng ){
91406    onError = pTab->keyConf;
91407    if( overrideError!=OE_Default ){
91408      onError = overrideError;
91409    }else if( onError==OE_Default ){
91410      onError = OE_Abort;
91411    }
91412
91413    if( isUpdate ){
91414      j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
91415    }
91416    j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
91417    switch( onError ){
91418      default: {
91419        onError = OE_Abort;
91420        /* Fall thru into the next case */
91421      }
91422      case OE_Rollback:
91423      case OE_Abort:
91424      case OE_Fail: {
91425        sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_PRIMARYKEY,
91426           onError, "PRIMARY KEY must be unique", P4_STATIC);
91427        break;
91428      }
91429      case OE_Replace: {
91430        /* If there are DELETE triggers on this table and the
91431        ** recursive-triggers flag is set, call GenerateRowDelete() to
91432        ** remove the conflicting row from the table. This will fire
91433        ** the triggers and remove both the table and index b-tree entries.
91434        **
91435        ** Otherwise, if there are no triggers or the recursive-triggers
91436        ** flag is not set, but the table has one or more indexes, call
91437        ** GenerateRowIndexDelete(). This removes the index b-tree entries
91438        ** only. The table b-tree entry will be replaced by the new entry
91439        ** when it is inserted.
91440        **
91441        ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
91442        ** also invoke MultiWrite() to indicate that this VDBE may require
91443        ** statement rollback (if the statement is aborted after the delete
91444        ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
91445        ** but being more selective here allows statements like:
91446        **
91447        **   REPLACE INTO t(rowid) VALUES($newrowid)
91448        **
91449        ** to run without a statement journal if there are no indexes on the
91450        ** table.
91451        */
91452        Trigger *pTrigger = 0;
91453        if( db->flags&SQLITE_RecTriggers ){
91454          pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
91455        }
91456        if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
91457          sqlite3MultiWrite(pParse);
91458          sqlite3GenerateRowDelete(
91459              pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
91460          );
91461        }else if( pTab->pIndex ){
91462          sqlite3MultiWrite(pParse);
91463          sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
91464        }
91465        seenReplace = 1;
91466        break;
91467      }
91468      case OE_Ignore: {
91469        assert( seenReplace==0 );
91470        sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
91471        break;
91472      }
91473    }
91474    sqlite3VdbeJumpHere(v, j3);
91475    if( isUpdate ){
91476      sqlite3VdbeJumpHere(v, j2);
91477    }
91478  }
91479
91480  /* Test all UNIQUE constraints by creating entries for each UNIQUE
91481  ** index and making sure that duplicate entries do not already exist.
91482  ** Add the new records to the indices as we go.
91483  */
91484  for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
91485    int regIdx;
91486    int regR;
91487
91488    if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */
91489
91490    /* Create a key for accessing the index entry */
91491    regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
91492    for(i=0; i<pIdx->nColumn; i++){
91493      int idx = pIdx->aiColumn[i];
91494      if( idx==pTab->iPKey ){
91495        sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
91496      }else{
91497        sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
91498      }
91499    }
91500    sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
91501    sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
91502    sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT);
91503    sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
91504
91505    /* Find out what action to take in case there is an indexing conflict */
91506    onError = pIdx->onError;
91507    if( onError==OE_None ){
91508      sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
91509      continue;  /* pIdx is not a UNIQUE index */
91510    }
91511    if( overrideError!=OE_Default ){
91512      onError = overrideError;
91513    }else if( onError==OE_Default ){
91514      onError = OE_Abort;
91515    }
91516    if( seenReplace ){
91517      if( onError==OE_Ignore ) onError = OE_Replace;
91518      else if( onError==OE_Fail ) onError = OE_Abort;
91519    }
91520
91521    /* Check to see if the new index entry will be unique */
91522    regR = sqlite3GetTempReg(pParse);
91523    sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
91524    j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
91525                           regR, SQLITE_INT_TO_PTR(regIdx),
91526                           P4_INT32);
91527    sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
91528
91529    /* Generate code that executes if the new index entry is not unique */
91530    assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
91531        || onError==OE_Ignore || onError==OE_Replace );
91532    switch( onError ){
91533      case OE_Rollback:
91534      case OE_Abort:
91535      case OE_Fail: {
91536        int j;
91537        StrAccum errMsg;
91538        const char *zSep;
91539        char *zErr;
91540
91541        sqlite3StrAccumInit(&errMsg, 0, 0, 200);
91542        errMsg.db = db;
91543        zSep = pIdx->nColumn>1 ? "columns " : "column ";
91544        for(j=0; j<pIdx->nColumn; j++){
91545          char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
91546          sqlite3StrAccumAppend(&errMsg, zSep, -1);
91547          zSep = ", ";
91548          sqlite3StrAccumAppend(&errMsg, zCol, -1);
91549        }
91550        sqlite3StrAccumAppend(&errMsg,
91551            pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
91552        zErr = sqlite3StrAccumFinish(&errMsg);
91553        sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_UNIQUE,
91554                              onError, zErr, 0);
91555        sqlite3DbFree(errMsg.db, zErr);
91556        break;
91557      }
91558      case OE_Ignore: {
91559        assert( seenReplace==0 );
91560        sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
91561        break;
91562      }
91563      default: {
91564        Trigger *pTrigger = 0;
91565        assert( onError==OE_Replace );
91566        sqlite3MultiWrite(pParse);
91567        if( db->flags&SQLITE_RecTriggers ){
91568          pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
91569        }
91570        sqlite3GenerateRowDelete(
91571            pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
91572        );
91573        seenReplace = 1;
91574        break;
91575      }
91576    }
91577    sqlite3VdbeJumpHere(v, j3);
91578    sqlite3ReleaseTempReg(pParse, regR);
91579  }
91580
91581  if( pbMayReplace ){
91582    *pbMayReplace = seenReplace;
91583  }
91584}
91585
91586/*
91587** This routine generates code to finish the INSERT or UPDATE operation
91588** that was started by a prior call to sqlite3GenerateConstraintChecks.
91589** A consecutive range of registers starting at regRowid contains the
91590** rowid and the content to be inserted.
91591**
91592** The arguments to this routine should be the same as the first six
91593** arguments to sqlite3GenerateConstraintChecks.
91594*/
91595SQLITE_PRIVATE void sqlite3CompleteInsertion(
91596  Parse *pParse,      /* The parser context */
91597  Table *pTab,        /* the table into which we are inserting */
91598  int baseCur,        /* Index of a read/write cursor pointing at pTab */
91599  int regRowid,       /* Range of content */
91600  int *aRegIdx,       /* Register used by each index.  0 for unused indices */
91601  int isUpdate,       /* True for UPDATE, False for INSERT */
91602  int appendBias,     /* True if this is likely to be an append */
91603  int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
91604){
91605  int i;
91606  Vdbe *v;
91607  int nIdx;
91608  Index *pIdx;
91609  u8 pik_flags;
91610  int regData;
91611  int regRec;
91612
91613  v = sqlite3GetVdbe(pParse);
91614  assert( v!=0 );
91615  assert( pTab->pSelect==0 );  /* This table is not a VIEW */
91616  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
91617  for(i=nIdx-1; i>=0; i--){
91618    if( aRegIdx[i]==0 ) continue;
91619    sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
91620    if( useSeekResult ){
91621      sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
91622    }
91623  }
91624  regData = regRowid + 1;
91625  regRec = sqlite3GetTempReg(pParse);
91626  sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
91627  sqlite3TableAffinityStr(v, pTab);
91628  sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
91629  if( pParse->nested ){
91630    pik_flags = 0;
91631  }else{
91632    pik_flags = OPFLAG_NCHANGE;
91633    pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
91634  }
91635  if( appendBias ){
91636    pik_flags |= OPFLAG_APPEND;
91637  }
91638  if( useSeekResult ){
91639    pik_flags |= OPFLAG_USESEEKRESULT;
91640  }
91641  sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
91642  if( !pParse->nested ){
91643    sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
91644  }
91645  sqlite3VdbeChangeP5(v, pik_flags);
91646}
91647
91648/*
91649** Generate code that will open cursors for a table and for all
91650** indices of that table.  The "baseCur" parameter is the cursor number used
91651** for the table.  Indices are opened on subsequent cursors.
91652**
91653** Return the number of indices on the table.
91654*/
91655SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
91656  Parse *pParse,   /* Parsing context */
91657  Table *pTab,     /* Table to be opened */
91658  int baseCur,     /* Cursor number assigned to the table */
91659  int op           /* OP_OpenRead or OP_OpenWrite */
91660){
91661  int i;
91662  int iDb;
91663  Index *pIdx;
91664  Vdbe *v;
91665
91666  if( IsVirtual(pTab) ) return 0;
91667  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
91668  v = sqlite3GetVdbe(pParse);
91669  assert( v!=0 );
91670  sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
91671  for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
91672    KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
91673    assert( pIdx->pSchema==pTab->pSchema );
91674    sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
91675                      (char*)pKey, P4_KEYINFO_HANDOFF);
91676    VdbeComment((v, "%s", pIdx->zName));
91677  }
91678  if( pParse->nTab<baseCur+i ){
91679    pParse->nTab = baseCur+i;
91680  }
91681  return i-1;
91682}
91683
91684
91685#ifdef SQLITE_TEST
91686/*
91687** The following global variable is incremented whenever the
91688** transfer optimization is used.  This is used for testing
91689** purposes only - to make sure the transfer optimization really
91690** is happening when it is suppose to.
91691*/
91692SQLITE_API int sqlite3_xferopt_count;
91693#endif /* SQLITE_TEST */
91694
91695
91696#ifndef SQLITE_OMIT_XFER_OPT
91697/*
91698** Check to collation names to see if they are compatible.
91699*/
91700static int xferCompatibleCollation(const char *z1, const char *z2){
91701  if( z1==0 ){
91702    return z2==0;
91703  }
91704  if( z2==0 ){
91705    return 0;
91706  }
91707  return sqlite3StrICmp(z1, z2)==0;
91708}
91709
91710
91711/*
91712** Check to see if index pSrc is compatible as a source of data
91713** for index pDest in an insert transfer optimization.  The rules
91714** for a compatible index:
91715**
91716**    *   The index is over the same set of columns
91717**    *   The same DESC and ASC markings occurs on all columns
91718**    *   The same onError processing (OE_Abort, OE_Ignore, etc)
91719**    *   The same collating sequence on each column
91720*/
91721static int xferCompatibleIndex(Index *pDest, Index *pSrc){
91722  int i;
91723  assert( pDest && pSrc );
91724  assert( pDest->pTable!=pSrc->pTable );
91725  if( pDest->nColumn!=pSrc->nColumn ){
91726    return 0;   /* Different number of columns */
91727  }
91728  if( pDest->onError!=pSrc->onError ){
91729    return 0;   /* Different conflict resolution strategies */
91730  }
91731  for(i=0; i<pSrc->nColumn; i++){
91732    if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
91733      return 0;   /* Different columns indexed */
91734    }
91735    if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
91736      return 0;   /* Different sort orders */
91737    }
91738    if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
91739      return 0;   /* Different collating sequences */
91740    }
91741  }
91742
91743  /* If no test above fails then the indices must be compatible */
91744  return 1;
91745}
91746
91747/*
91748** Attempt the transfer optimization on INSERTs of the form
91749**
91750**     INSERT INTO tab1 SELECT * FROM tab2;
91751**
91752** The xfer optimization transfers raw records from tab2 over to tab1.
91753** Columns are not decoded and reassemblied, which greatly improves
91754** performance.  Raw index records are transferred in the same way.
91755**
91756** The xfer optimization is only attempted if tab1 and tab2 are compatible.
91757** There are lots of rules for determining compatibility - see comments
91758** embedded in the code for details.
91759**
91760** This routine returns TRUE if the optimization is guaranteed to be used.
91761** Sometimes the xfer optimization will only work if the destination table
91762** is empty - a factor that can only be determined at run-time.  In that
91763** case, this routine generates code for the xfer optimization but also
91764** does a test to see if the destination table is empty and jumps over the
91765** xfer optimization code if the test fails.  In that case, this routine
91766** returns FALSE so that the caller will know to go ahead and generate
91767** an unoptimized transfer.  This routine also returns FALSE if there
91768** is no chance that the xfer optimization can be applied.
91769**
91770** This optimization is particularly useful at making VACUUM run faster.
91771*/
91772static int xferOptimization(
91773  Parse *pParse,        /* Parser context */
91774  Table *pDest,         /* The table we are inserting into */
91775  Select *pSelect,      /* A SELECT statement to use as the data source */
91776  int onError,          /* How to handle constraint errors */
91777  int iDbDest           /* The database of pDest */
91778){
91779  ExprList *pEList;                /* The result set of the SELECT */
91780  Table *pSrc;                     /* The table in the FROM clause of SELECT */
91781  Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
91782  struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
91783  int i;                           /* Loop counter */
91784  int iDbSrc;                      /* The database of pSrc */
91785  int iSrc, iDest;                 /* Cursors from source and destination */
91786  int addr1, addr2;                /* Loop addresses */
91787  int emptyDestTest;               /* Address of test for empty pDest */
91788  int emptySrcTest;                /* Address of test for empty pSrc */
91789  Vdbe *v;                         /* The VDBE we are building */
91790  KeyInfo *pKey;                   /* Key information for an index */
91791  int regAutoinc;                  /* Memory register used by AUTOINC */
91792  int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
91793  int regData, regRowid;           /* Registers holding data and rowid */
91794
91795  if( pSelect==0 ){
91796    return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
91797  }
91798  if( sqlite3TriggerList(pParse, pDest) ){
91799    return 0;   /* tab1 must not have triggers */
91800  }
91801#ifndef SQLITE_OMIT_VIRTUALTABLE
91802  if( pDest->tabFlags & TF_Virtual ){
91803    return 0;   /* tab1 must not be a virtual table */
91804  }
91805#endif
91806  if( onError==OE_Default ){
91807    if( pDest->iPKey>=0 ) onError = pDest->keyConf;
91808    if( onError==OE_Default ) onError = OE_Abort;
91809  }
91810  assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
91811  if( pSelect->pSrc->nSrc!=1 ){
91812    return 0;   /* FROM clause must have exactly one term */
91813  }
91814  if( pSelect->pSrc->a[0].pSelect ){
91815    return 0;   /* FROM clause cannot contain a subquery */
91816  }
91817  if( pSelect->pWhere ){
91818    return 0;   /* SELECT may not have a WHERE clause */
91819  }
91820  if( pSelect->pOrderBy ){
91821    return 0;   /* SELECT may not have an ORDER BY clause */
91822  }
91823  /* Do not need to test for a HAVING clause.  If HAVING is present but
91824  ** there is no ORDER BY, we will get an error. */
91825  if( pSelect->pGroupBy ){
91826    return 0;   /* SELECT may not have a GROUP BY clause */
91827  }
91828  if( pSelect->pLimit ){
91829    return 0;   /* SELECT may not have a LIMIT clause */
91830  }
91831  assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
91832  if( pSelect->pPrior ){
91833    return 0;   /* SELECT may not be a compound query */
91834  }
91835  if( pSelect->selFlags & SF_Distinct ){
91836    return 0;   /* SELECT may not be DISTINCT */
91837  }
91838  pEList = pSelect->pEList;
91839  assert( pEList!=0 );
91840  if( pEList->nExpr!=1 ){
91841    return 0;   /* The result set must have exactly one column */
91842  }
91843  assert( pEList->a[0].pExpr );
91844  if( pEList->a[0].pExpr->op!=TK_ALL ){
91845    return 0;   /* The result set must be the special operator "*" */
91846  }
91847
91848  /* At this point we have established that the statement is of the
91849  ** correct syntactic form to participate in this optimization.  Now
91850  ** we have to check the semantics.
91851  */
91852  pItem = pSelect->pSrc->a;
91853  pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
91854  if( pSrc==0 ){
91855    return 0;   /* FROM clause does not contain a real table */
91856  }
91857  if( pSrc==pDest ){
91858    return 0;   /* tab1 and tab2 may not be the same table */
91859  }
91860#ifndef SQLITE_OMIT_VIRTUALTABLE
91861  if( pSrc->tabFlags & TF_Virtual ){
91862    return 0;   /* tab2 must not be a virtual table */
91863  }
91864#endif
91865  if( pSrc->pSelect ){
91866    return 0;   /* tab2 may not be a view */
91867  }
91868  if( pDest->nCol!=pSrc->nCol ){
91869    return 0;   /* Number of columns must be the same in tab1 and tab2 */
91870  }
91871  if( pDest->iPKey!=pSrc->iPKey ){
91872    return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
91873  }
91874  for(i=0; i<pDest->nCol; i++){
91875    if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
91876      return 0;    /* Affinity must be the same on all columns */
91877    }
91878    if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
91879      return 0;    /* Collating sequence must be the same on all columns */
91880    }
91881    if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
91882      return 0;    /* tab2 must be NOT NULL if tab1 is */
91883    }
91884  }
91885  for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
91886    if( pDestIdx->onError!=OE_None ){
91887      destHasUniqueIdx = 1;
91888    }
91889    for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
91890      if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
91891    }
91892    if( pSrcIdx==0 ){
91893      return 0;    /* pDestIdx has no corresponding index in pSrc */
91894    }
91895  }
91896#ifndef SQLITE_OMIT_CHECK
91897  if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck, pDest->pCheck) ){
91898    return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
91899  }
91900#endif
91901#ifndef SQLITE_OMIT_FOREIGN_KEY
91902  /* Disallow the transfer optimization if the destination table constains
91903  ** any foreign key constraints.  This is more restrictive than necessary.
91904  ** But the main beneficiary of the transfer optimization is the VACUUM
91905  ** command, and the VACUUM command disables foreign key constraints.  So
91906  ** the extra complication to make this rule less restrictive is probably
91907  ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
91908  */
91909  if( (pParse->db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
91910    return 0;
91911  }
91912#endif
91913  if( (pParse->db->flags & SQLITE_CountRows)!=0 ){
91914    return 0;  /* xfer opt does not play well with PRAGMA count_changes */
91915  }
91916
91917  /* If we get this far, it means that the xfer optimization is at
91918  ** least a possibility, though it might only work if the destination
91919  ** table (tab1) is initially empty.
91920  */
91921#ifdef SQLITE_TEST
91922  sqlite3_xferopt_count++;
91923#endif
91924  iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
91925  v = sqlite3GetVdbe(pParse);
91926  sqlite3CodeVerifySchema(pParse, iDbSrc);
91927  iSrc = pParse->nTab++;
91928  iDest = pParse->nTab++;
91929  regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
91930  sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
91931  if( (pDest->iPKey<0 && pDest->pIndex!=0)          /* (1) */
91932   || destHasUniqueIdx                              /* (2) */
91933   || (onError!=OE_Abort && onError!=OE_Rollback)   /* (3) */
91934  ){
91935    /* In some circumstances, we are able to run the xfer optimization
91936    ** only if the destination table is initially empty.  This code makes
91937    ** that determination.  Conditions under which the destination must
91938    ** be empty:
91939    **
91940    ** (1) There is no INTEGER PRIMARY KEY but there are indices.
91941    **     (If the destination is not initially empty, the rowid fields
91942    **     of index entries might need to change.)
91943    **
91944    ** (2) The destination has a unique index.  (The xfer optimization
91945    **     is unable to test uniqueness.)
91946    **
91947    ** (3) onError is something other than OE_Abort and OE_Rollback.
91948    */
91949    addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
91950    emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
91951    sqlite3VdbeJumpHere(v, addr1);
91952  }else{
91953    emptyDestTest = 0;
91954  }
91955  sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
91956  emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
91957  regData = sqlite3GetTempReg(pParse);
91958  regRowid = sqlite3GetTempReg(pParse);
91959  if( pDest->iPKey>=0 ){
91960    addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
91961    addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
91962    sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_PRIMARYKEY,
91963        onError, "PRIMARY KEY must be unique", P4_STATIC);
91964    sqlite3VdbeJumpHere(v, addr2);
91965    autoIncStep(pParse, regAutoinc, regRowid);
91966  }else if( pDest->pIndex==0 ){
91967    addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
91968  }else{
91969    addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
91970    assert( (pDest->tabFlags & TF_Autoincrement)==0 );
91971  }
91972  sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
91973  sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
91974  sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
91975  sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
91976  sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
91977  for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
91978    for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
91979      if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
91980    }
91981    assert( pSrcIdx );
91982    sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
91983    sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
91984    pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
91985    sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
91986                      (char*)pKey, P4_KEYINFO_HANDOFF);
91987    VdbeComment((v, "%s", pSrcIdx->zName));
91988    pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
91989    sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
91990                      (char*)pKey, P4_KEYINFO_HANDOFF);
91991    VdbeComment((v, "%s", pDestIdx->zName));
91992    addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
91993    sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
91994    sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
91995    sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
91996    sqlite3VdbeJumpHere(v, addr1);
91997  }
91998  sqlite3VdbeJumpHere(v, emptySrcTest);
91999  sqlite3ReleaseTempReg(pParse, regRowid);
92000  sqlite3ReleaseTempReg(pParse, regData);
92001  sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
92002  sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
92003  if( emptyDestTest ){
92004    sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
92005    sqlite3VdbeJumpHere(v, emptyDestTest);
92006    sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
92007    return 0;
92008  }else{
92009    return 1;
92010  }
92011}
92012#endif /* SQLITE_OMIT_XFER_OPT */
92013
92014/************** End of insert.c **********************************************/
92015/************** Begin file legacy.c ******************************************/
92016/*
92017** 2001 September 15
92018**
92019** The author disclaims copyright to this source code.  In place of
92020** a legal notice, here is a blessing:
92021**
92022**    May you do good and not evil.
92023**    May you find forgiveness for yourself and forgive others.
92024**    May you share freely, never taking more than you give.
92025**
92026*************************************************************************
92027** Main file for the SQLite library.  The routines in this file
92028** implement the programmer interface to the library.  Routines in
92029** other files are for internal use by SQLite and should not be
92030** accessed by users of the library.
92031*/
92032
92033
92034/*
92035** Execute SQL code.  Return one of the SQLITE_ success/failure
92036** codes.  Also write an error message into memory obtained from
92037** malloc() and make *pzErrMsg point to that message.
92038**
92039** If the SQL is a query, then for each row in the query result
92040** the xCallback() function is called.  pArg becomes the first
92041** argument to xCallback().  If xCallback=NULL then no callback
92042** is invoked, even for queries.
92043*/
92044SQLITE_API int sqlite3_exec(
92045  sqlite3 *db,                /* The database on which the SQL executes */
92046  const char *zSql,           /* The SQL to be executed */
92047  sqlite3_callback xCallback, /* Invoke this callback routine */
92048  void *pArg,                 /* First argument to xCallback() */
92049  char **pzErrMsg             /* Write error messages here */
92050){
92051  int rc = SQLITE_OK;         /* Return code */
92052  const char *zLeftover;      /* Tail of unprocessed SQL */
92053  sqlite3_stmt *pStmt = 0;    /* The current SQL statement */
92054  char **azCols = 0;          /* Names of result columns */
92055  int callbackIsInit;         /* True if callback data is initialized */
92056
92057  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
92058  if( zSql==0 ) zSql = "";
92059
92060  sqlite3_mutex_enter(db->mutex);
92061  sqlite3Error(db, SQLITE_OK, 0);
92062  while( rc==SQLITE_OK && zSql[0] ){
92063    int nCol;
92064    char **azVals = 0;
92065
92066    pStmt = 0;
92067    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
92068    assert( rc==SQLITE_OK || pStmt==0 );
92069    if( rc!=SQLITE_OK ){
92070      continue;
92071    }
92072    if( !pStmt ){
92073      /* this happens for a comment or white-space */
92074      zSql = zLeftover;
92075      continue;
92076    }
92077
92078    callbackIsInit = 0;
92079    nCol = sqlite3_column_count(pStmt);
92080
92081    while( 1 ){
92082      int i;
92083      rc = sqlite3_step(pStmt);
92084
92085      /* Invoke the callback function if required */
92086      if( xCallback && (SQLITE_ROW==rc ||
92087          (SQLITE_DONE==rc && !callbackIsInit
92088                           && db->flags&SQLITE_NullCallback)) ){
92089        if( !callbackIsInit ){
92090          azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
92091          if( azCols==0 ){
92092            goto exec_out;
92093          }
92094          for(i=0; i<nCol; i++){
92095            azCols[i] = (char *)sqlite3_column_name(pStmt, i);
92096            /* sqlite3VdbeSetColName() installs column names as UTF8
92097            ** strings so there is no way for sqlite3_column_name() to fail. */
92098            assert( azCols[i]!=0 );
92099          }
92100          callbackIsInit = 1;
92101        }
92102        if( rc==SQLITE_ROW ){
92103          azVals = &azCols[nCol];
92104          for(i=0; i<nCol; i++){
92105            azVals[i] = (char *)sqlite3_column_text(pStmt, i);
92106            if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
92107              db->mallocFailed = 1;
92108              goto exec_out;
92109            }
92110          }
92111        }
92112        if( xCallback(pArg, nCol, azVals, azCols) ){
92113          rc = SQLITE_ABORT;
92114          sqlite3VdbeFinalize((Vdbe *)pStmt);
92115          pStmt = 0;
92116          sqlite3Error(db, SQLITE_ABORT, 0);
92117          goto exec_out;
92118        }
92119      }
92120
92121      if( rc!=SQLITE_ROW ){
92122        rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
92123        pStmt = 0;
92124        zSql = zLeftover;
92125        while( sqlite3Isspace(zSql[0]) ) zSql++;
92126        break;
92127      }
92128    }
92129
92130    sqlite3DbFree(db, azCols);
92131    azCols = 0;
92132  }
92133
92134exec_out:
92135  if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
92136  sqlite3DbFree(db, azCols);
92137
92138  rc = sqlite3ApiExit(db, rc);
92139  if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){
92140    int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
92141    *pzErrMsg = sqlite3Malloc(nErrMsg);
92142    if( *pzErrMsg ){
92143      memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
92144    }else{
92145      rc = SQLITE_NOMEM;
92146      sqlite3Error(db, SQLITE_NOMEM, 0);
92147    }
92148  }else if( pzErrMsg ){
92149    *pzErrMsg = 0;
92150  }
92151
92152  assert( (rc&db->errMask)==rc );
92153  sqlite3_mutex_leave(db->mutex);
92154  return rc;
92155}
92156
92157/************** End of legacy.c **********************************************/
92158/************** Begin file loadext.c *****************************************/
92159/*
92160** 2006 June 7
92161**
92162** The author disclaims copyright to this source code.  In place of
92163** a legal notice, here is a blessing:
92164**
92165**    May you do good and not evil.
92166**    May you find forgiveness for yourself and forgive others.
92167**    May you share freely, never taking more than you give.
92168**
92169*************************************************************************
92170** This file contains code used to dynamically load extensions into
92171** the SQLite library.
92172*/
92173
92174#ifndef SQLITE_CORE
92175  #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
92176#endif
92177/************** Include sqlite3ext.h in the middle of loadext.c **************/
92178/************** Begin file sqlite3ext.h **************************************/
92179/*
92180** 2006 June 7
92181**
92182** The author disclaims copyright to this source code.  In place of
92183** a legal notice, here is a blessing:
92184**
92185**    May you do good and not evil.
92186**    May you find forgiveness for yourself and forgive others.
92187**    May you share freely, never taking more than you give.
92188**
92189*************************************************************************
92190** This header file defines the SQLite interface for use by
92191** shared libraries that want to be imported as extensions into
92192** an SQLite instance.  Shared libraries that intend to be loaded
92193** as extensions by SQLite should #include this file instead of
92194** sqlite3.h.
92195*/
92196#ifndef _SQLITE3EXT_H_
92197#define _SQLITE3EXT_H_
92198
92199typedef struct sqlite3_api_routines sqlite3_api_routines;
92200
92201/*
92202** The following structure holds pointers to all of the SQLite API
92203** routines.
92204**
92205** WARNING:  In order to maintain backwards compatibility, add new
92206** interfaces to the end of this structure only.  If you insert new
92207** interfaces in the middle of this structure, then older different
92208** versions of SQLite will not be able to load each others' shared
92209** libraries!
92210*/
92211struct sqlite3_api_routines {
92212  void * (*aggregate_context)(sqlite3_context*,int nBytes);
92213  int  (*aggregate_count)(sqlite3_context*);
92214  int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
92215  int  (*bind_double)(sqlite3_stmt*,int,double);
92216  int  (*bind_int)(sqlite3_stmt*,int,int);
92217  int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
92218  int  (*bind_null)(sqlite3_stmt*,int);
92219  int  (*bind_parameter_count)(sqlite3_stmt*);
92220  int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
92221  const char * (*bind_parameter_name)(sqlite3_stmt*,int);
92222  int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
92223  int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
92224  int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
92225  int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
92226  int  (*busy_timeout)(sqlite3*,int ms);
92227  int  (*changes)(sqlite3*);
92228  int  (*close)(sqlite3*);
92229  int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
92230                           int eTextRep,const char*));
92231  int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
92232                             int eTextRep,const void*));
92233  const void * (*column_blob)(sqlite3_stmt*,int iCol);
92234  int  (*column_bytes)(sqlite3_stmt*,int iCol);
92235  int  (*column_bytes16)(sqlite3_stmt*,int iCol);
92236  int  (*column_count)(sqlite3_stmt*pStmt);
92237  const char * (*column_database_name)(sqlite3_stmt*,int);
92238  const void * (*column_database_name16)(sqlite3_stmt*,int);
92239  const char * (*column_decltype)(sqlite3_stmt*,int i);
92240  const void * (*column_decltype16)(sqlite3_stmt*,int);
92241  double  (*column_double)(sqlite3_stmt*,int iCol);
92242  int  (*column_int)(sqlite3_stmt*,int iCol);
92243  sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
92244  const char * (*column_name)(sqlite3_stmt*,int);
92245  const void * (*column_name16)(sqlite3_stmt*,int);
92246  const char * (*column_origin_name)(sqlite3_stmt*,int);
92247  const void * (*column_origin_name16)(sqlite3_stmt*,int);
92248  const char * (*column_table_name)(sqlite3_stmt*,int);
92249  const void * (*column_table_name16)(sqlite3_stmt*,int);
92250  const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
92251  const void * (*column_text16)(sqlite3_stmt*,int iCol);
92252  int  (*column_type)(sqlite3_stmt*,int iCol);
92253  sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
92254  void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
92255  int  (*complete)(const char*sql);
92256  int  (*complete16)(const void*sql);
92257  int  (*create_collation)(sqlite3*,const char*,int,void*,
92258                           int(*)(void*,int,const void*,int,const void*));
92259  int  (*create_collation16)(sqlite3*,const void*,int,void*,
92260                             int(*)(void*,int,const void*,int,const void*));
92261  int  (*create_function)(sqlite3*,const char*,int,int,void*,
92262                          void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
92263                          void (*xStep)(sqlite3_context*,int,sqlite3_value**),
92264                          void (*xFinal)(sqlite3_context*));
92265  int  (*create_function16)(sqlite3*,const void*,int,int,void*,
92266                            void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
92267                            void (*xStep)(sqlite3_context*,int,sqlite3_value**),
92268                            void (*xFinal)(sqlite3_context*));
92269  int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
92270  int  (*data_count)(sqlite3_stmt*pStmt);
92271  sqlite3 * (*db_handle)(sqlite3_stmt*);
92272  int (*declare_vtab)(sqlite3*,const char*);
92273  int  (*enable_shared_cache)(int);
92274  int  (*errcode)(sqlite3*db);
92275  const char * (*errmsg)(sqlite3*);
92276  const void * (*errmsg16)(sqlite3*);
92277  int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
92278  int  (*expired)(sqlite3_stmt*);
92279  int  (*finalize)(sqlite3_stmt*pStmt);
92280  void  (*free)(void*);
92281  void  (*free_table)(char**result);
92282  int  (*get_autocommit)(sqlite3*);
92283  void * (*get_auxdata)(sqlite3_context*,int);
92284  int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
92285  int  (*global_recover)(void);
92286  void  (*interruptx)(sqlite3*);
92287  sqlite_int64  (*last_insert_rowid)(sqlite3*);
92288  const char * (*libversion)(void);
92289  int  (*libversion_number)(void);
92290  void *(*malloc)(int);
92291  char * (*mprintf)(const char*,...);
92292  int  (*open)(const char*,sqlite3**);
92293  int  (*open16)(const void*,sqlite3**);
92294  int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
92295  int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
92296  void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
92297  void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
92298  void *(*realloc)(void*,int);
92299  int  (*reset)(sqlite3_stmt*pStmt);
92300  void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
92301  void  (*result_double)(sqlite3_context*,double);
92302  void  (*result_error)(sqlite3_context*,const char*,int);
92303  void  (*result_error16)(sqlite3_context*,const void*,int);
92304  void  (*result_int)(sqlite3_context*,int);
92305  void  (*result_int64)(sqlite3_context*,sqlite_int64);
92306  void  (*result_null)(sqlite3_context*);
92307  void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
92308  void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
92309  void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
92310  void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
92311  void  (*result_value)(sqlite3_context*,sqlite3_value*);
92312  void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
92313  int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
92314                         const char*,const char*),void*);
92315  void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
92316  char * (*snprintf)(int,char*,const char*,...);
92317  int  (*step)(sqlite3_stmt*);
92318  int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
92319                                char const**,char const**,int*,int*,int*);
92320  void  (*thread_cleanup)(void);
92321  int  (*total_changes)(sqlite3*);
92322  void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
92323  int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
92324  void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
92325                                         sqlite_int64),void*);
92326  void * (*user_data)(sqlite3_context*);
92327  const void * (*value_blob)(sqlite3_value*);
92328  int  (*value_bytes)(sqlite3_value*);
92329  int  (*value_bytes16)(sqlite3_value*);
92330  double  (*value_double)(sqlite3_value*);
92331  int  (*value_int)(sqlite3_value*);
92332  sqlite_int64  (*value_int64)(sqlite3_value*);
92333  int  (*value_numeric_type)(sqlite3_value*);
92334  const unsigned char * (*value_text)(sqlite3_value*);
92335  const void * (*value_text16)(sqlite3_value*);
92336  const void * (*value_text16be)(sqlite3_value*);
92337  const void * (*value_text16le)(sqlite3_value*);
92338  int  (*value_type)(sqlite3_value*);
92339  char *(*vmprintf)(const char*,va_list);
92340  /* Added ??? */
92341  int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
92342  /* Added by 3.3.13 */
92343  int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
92344  int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
92345  int (*clear_bindings)(sqlite3_stmt*);
92346  /* Added by 3.4.1 */
92347  int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
92348                          void (*xDestroy)(void *));
92349  /* Added by 3.5.0 */
92350  int (*bind_zeroblob)(sqlite3_stmt*,int,int);
92351  int (*blob_bytes)(sqlite3_blob*);
92352  int (*blob_close)(sqlite3_blob*);
92353  int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
92354                   int,sqlite3_blob**);
92355  int (*blob_read)(sqlite3_blob*,void*,int,int);
92356  int (*blob_write)(sqlite3_blob*,const void*,int,int);
92357  int (*create_collation_v2)(sqlite3*,const char*,int,void*,
92358                             int(*)(void*,int,const void*,int,const void*),
92359                             void(*)(void*));
92360  int (*file_control)(sqlite3*,const char*,int,void*);
92361  sqlite3_int64 (*memory_highwater)(int);
92362  sqlite3_int64 (*memory_used)(void);
92363  sqlite3_mutex *(*mutex_alloc)(int);
92364  void (*mutex_enter)(sqlite3_mutex*);
92365  void (*mutex_free)(sqlite3_mutex*);
92366  void (*mutex_leave)(sqlite3_mutex*);
92367  int (*mutex_try)(sqlite3_mutex*);
92368  int (*open_v2)(const char*,sqlite3**,int,const char*);
92369  int (*release_memory)(int);
92370  void (*result_error_nomem)(sqlite3_context*);
92371  void (*result_error_toobig)(sqlite3_context*);
92372  int (*sleep)(int);
92373  void (*soft_heap_limit)(int);
92374  sqlite3_vfs *(*vfs_find)(const char*);
92375  int (*vfs_register)(sqlite3_vfs*,int);
92376  int (*vfs_unregister)(sqlite3_vfs*);
92377  int (*xthreadsafe)(void);
92378  void (*result_zeroblob)(sqlite3_context*,int);
92379  void (*result_error_code)(sqlite3_context*,int);
92380  int (*test_control)(int, ...);
92381  void (*randomness)(int,void*);
92382  sqlite3 *(*context_db_handle)(sqlite3_context*);
92383  int (*extended_result_codes)(sqlite3*,int);
92384  int (*limit)(sqlite3*,int,int);
92385  sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
92386  const char *(*sql)(sqlite3_stmt*);
92387  int (*status)(int,int*,int*,int);
92388  int (*backup_finish)(sqlite3_backup*);
92389  sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
92390  int (*backup_pagecount)(sqlite3_backup*);
92391  int (*backup_remaining)(sqlite3_backup*);
92392  int (*backup_step)(sqlite3_backup*,int);
92393  const char *(*compileoption_get)(int);
92394  int (*compileoption_used)(const char*);
92395  int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
92396                            void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
92397                            void (*xStep)(sqlite3_context*,int,sqlite3_value**),
92398                            void (*xFinal)(sqlite3_context*),
92399                            void(*xDestroy)(void*));
92400  int (*db_config)(sqlite3*,int,...);
92401  sqlite3_mutex *(*db_mutex)(sqlite3*);
92402  int (*db_status)(sqlite3*,int,int*,int*,int);
92403  int (*extended_errcode)(sqlite3*);
92404  void (*log)(int,const char*,...);
92405  sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
92406  const char *(*sourceid)(void);
92407  int (*stmt_status)(sqlite3_stmt*,int,int);
92408  int (*strnicmp)(const char*,const char*,int);
92409  int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
92410  int (*wal_autocheckpoint)(sqlite3*,int);
92411  int (*wal_checkpoint)(sqlite3*,const char*);
92412  void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
92413  int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
92414  int (*vtab_config)(sqlite3*,int op,...);
92415  int (*vtab_on_conflict)(sqlite3*);
92416  /* Version 3.7.16 and later */
92417  int (*close_v2)(sqlite3*);
92418  const char *(*db_filename)(sqlite3*,const char*);
92419  int (*db_readonly)(sqlite3*,const char*);
92420  int (*db_release_memory)(sqlite3*);
92421  const char *(*errstr)(int);
92422  int (*stmt_busy)(sqlite3_stmt*);
92423  int (*stmt_readonly)(sqlite3_stmt*);
92424  int (*stricmp)(const char*,const char*);
92425  int (*uri_boolean)(const char*,const char*,int);
92426  sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
92427  const char *(*uri_parameter)(const char*,const char*);
92428  char *(*vsnprintf)(int,char*,const char*,va_list);
92429  int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
92430};
92431
92432/*
92433** The following macros redefine the API routines so that they are
92434** redirected throught the global sqlite3_api structure.
92435**
92436** This header file is also used by the loadext.c source file
92437** (part of the main SQLite library - not an extension) so that
92438** it can get access to the sqlite3_api_routines structure
92439** definition.  But the main library does not want to redefine
92440** the API.  So the redefinition macros are only valid if the
92441** SQLITE_CORE macros is undefined.
92442*/
92443#ifndef SQLITE_CORE
92444#define sqlite3_aggregate_context      sqlite3_api->aggregate_context
92445#ifndef SQLITE_OMIT_DEPRECATED
92446#define sqlite3_aggregate_count        sqlite3_api->aggregate_count
92447#endif
92448#define sqlite3_bind_blob              sqlite3_api->bind_blob
92449#define sqlite3_bind_double            sqlite3_api->bind_double
92450#define sqlite3_bind_int               sqlite3_api->bind_int
92451#define sqlite3_bind_int64             sqlite3_api->bind_int64
92452#define sqlite3_bind_null              sqlite3_api->bind_null
92453#define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
92454#define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
92455#define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
92456#define sqlite3_bind_text              sqlite3_api->bind_text
92457#define sqlite3_bind_text16            sqlite3_api->bind_text16
92458#define sqlite3_bind_value             sqlite3_api->bind_value
92459#define sqlite3_busy_handler           sqlite3_api->busy_handler
92460#define sqlite3_busy_timeout           sqlite3_api->busy_timeout
92461#define sqlite3_changes                sqlite3_api->changes
92462#define sqlite3_close                  sqlite3_api->close
92463#define sqlite3_collation_needed       sqlite3_api->collation_needed
92464#define sqlite3_collation_needed16     sqlite3_api->collation_needed16
92465#define sqlite3_column_blob            sqlite3_api->column_blob
92466#define sqlite3_column_bytes           sqlite3_api->column_bytes
92467#define sqlite3_column_bytes16         sqlite3_api->column_bytes16
92468#define sqlite3_column_count           sqlite3_api->column_count
92469#define sqlite3_column_database_name   sqlite3_api->column_database_name
92470#define sqlite3_column_database_name16 sqlite3_api->column_database_name16
92471#define sqlite3_column_decltype        sqlite3_api->column_decltype
92472#define sqlite3_column_decltype16      sqlite3_api->column_decltype16
92473#define sqlite3_column_double          sqlite3_api->column_double
92474#define sqlite3_column_int             sqlite3_api->column_int
92475#define sqlite3_column_int64           sqlite3_api->column_int64
92476#define sqlite3_column_name            sqlite3_api->column_name
92477#define sqlite3_column_name16          sqlite3_api->column_name16
92478#define sqlite3_column_origin_name     sqlite3_api->column_origin_name
92479#define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
92480#define sqlite3_column_table_name      sqlite3_api->column_table_name
92481#define sqlite3_column_table_name16    sqlite3_api->column_table_name16
92482#define sqlite3_column_text            sqlite3_api->column_text
92483#define sqlite3_column_text16          sqlite3_api->column_text16
92484#define sqlite3_column_type            sqlite3_api->column_type
92485#define sqlite3_column_value           sqlite3_api->column_value
92486#define sqlite3_commit_hook            sqlite3_api->commit_hook
92487#define sqlite3_complete               sqlite3_api->complete
92488#define sqlite3_complete16             sqlite3_api->complete16
92489#define sqlite3_create_collation       sqlite3_api->create_collation
92490#define sqlite3_create_collation16     sqlite3_api->create_collation16
92491#define sqlite3_create_function        sqlite3_api->create_function
92492#define sqlite3_create_function16      sqlite3_api->create_function16
92493#define sqlite3_create_module          sqlite3_api->create_module
92494#define sqlite3_create_module_v2       sqlite3_api->create_module_v2
92495#define sqlite3_data_count             sqlite3_api->data_count
92496#define sqlite3_db_handle              sqlite3_api->db_handle
92497#define sqlite3_declare_vtab           sqlite3_api->declare_vtab
92498#define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
92499#define sqlite3_errcode                sqlite3_api->errcode
92500#define sqlite3_errmsg                 sqlite3_api->errmsg
92501#define sqlite3_errmsg16               sqlite3_api->errmsg16
92502#define sqlite3_exec                   sqlite3_api->exec
92503#ifndef SQLITE_OMIT_DEPRECATED
92504#define sqlite3_expired                sqlite3_api->expired
92505#endif
92506#define sqlite3_finalize               sqlite3_api->finalize
92507#define sqlite3_free                   sqlite3_api->free
92508#define sqlite3_free_table             sqlite3_api->free_table
92509#define sqlite3_get_autocommit         sqlite3_api->get_autocommit
92510#define sqlite3_get_auxdata            sqlite3_api->get_auxdata
92511#define sqlite3_get_table              sqlite3_api->get_table
92512#ifndef SQLITE_OMIT_DEPRECATED
92513#define sqlite3_global_recover         sqlite3_api->global_recover
92514#endif
92515#define sqlite3_interrupt              sqlite3_api->interruptx
92516#define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
92517#define sqlite3_libversion             sqlite3_api->libversion
92518#define sqlite3_libversion_number      sqlite3_api->libversion_number
92519#define sqlite3_malloc                 sqlite3_api->malloc
92520#define sqlite3_mprintf                sqlite3_api->mprintf
92521#define sqlite3_open                   sqlite3_api->open
92522#define sqlite3_open16                 sqlite3_api->open16
92523#define sqlite3_prepare                sqlite3_api->prepare
92524#define sqlite3_prepare16              sqlite3_api->prepare16
92525#define sqlite3_prepare_v2             sqlite3_api->prepare_v2
92526#define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
92527#define sqlite3_profile                sqlite3_api->profile
92528#define sqlite3_progress_handler       sqlite3_api->progress_handler
92529#define sqlite3_realloc                sqlite3_api->realloc
92530#define sqlite3_reset                  sqlite3_api->reset
92531#define sqlite3_result_blob            sqlite3_api->result_blob
92532#define sqlite3_result_double          sqlite3_api->result_double
92533#define sqlite3_result_error           sqlite3_api->result_error
92534#define sqlite3_result_error16         sqlite3_api->result_error16
92535#define sqlite3_result_int             sqlite3_api->result_int
92536#define sqlite3_result_int64           sqlite3_api->result_int64
92537#define sqlite3_result_null            sqlite3_api->result_null
92538#define sqlite3_result_text            sqlite3_api->result_text
92539#define sqlite3_result_text16          sqlite3_api->result_text16
92540#define sqlite3_result_text16be        sqlite3_api->result_text16be
92541#define sqlite3_result_text16le        sqlite3_api->result_text16le
92542#define sqlite3_result_value           sqlite3_api->result_value
92543#define sqlite3_rollback_hook          sqlite3_api->rollback_hook
92544#define sqlite3_set_authorizer         sqlite3_api->set_authorizer
92545#define sqlite3_set_auxdata            sqlite3_api->set_auxdata
92546#define sqlite3_snprintf               sqlite3_api->snprintf
92547#define sqlite3_step                   sqlite3_api->step
92548#define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
92549#define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
92550#define sqlite3_total_changes          sqlite3_api->total_changes
92551#define sqlite3_trace                  sqlite3_api->trace
92552#ifndef SQLITE_OMIT_DEPRECATED
92553#define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
92554#endif
92555#define sqlite3_update_hook            sqlite3_api->update_hook
92556#define sqlite3_user_data              sqlite3_api->user_data
92557#define sqlite3_value_blob             sqlite3_api->value_blob
92558#define sqlite3_value_bytes            sqlite3_api->value_bytes
92559#define sqlite3_value_bytes16          sqlite3_api->value_bytes16
92560#define sqlite3_value_double           sqlite3_api->value_double
92561#define sqlite3_value_int              sqlite3_api->value_int
92562#define sqlite3_value_int64            sqlite3_api->value_int64
92563#define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
92564#define sqlite3_value_text             sqlite3_api->value_text
92565#define sqlite3_value_text16           sqlite3_api->value_text16
92566#define sqlite3_value_text16be         sqlite3_api->value_text16be
92567#define sqlite3_value_text16le         sqlite3_api->value_text16le
92568#define sqlite3_value_type             sqlite3_api->value_type
92569#define sqlite3_vmprintf               sqlite3_api->vmprintf
92570#define sqlite3_overload_function      sqlite3_api->overload_function
92571#define sqlite3_prepare_v2             sqlite3_api->prepare_v2
92572#define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
92573#define sqlite3_clear_bindings         sqlite3_api->clear_bindings
92574#define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
92575#define sqlite3_blob_bytes             sqlite3_api->blob_bytes
92576#define sqlite3_blob_close             sqlite3_api->blob_close
92577#define sqlite3_blob_open              sqlite3_api->blob_open
92578#define sqlite3_blob_read              sqlite3_api->blob_read
92579#define sqlite3_blob_write             sqlite3_api->blob_write
92580#define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
92581#define sqlite3_file_control           sqlite3_api->file_control
92582#define sqlite3_memory_highwater       sqlite3_api->memory_highwater
92583#define sqlite3_memory_used            sqlite3_api->memory_used
92584#define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
92585#define sqlite3_mutex_enter            sqlite3_api->mutex_enter
92586#define sqlite3_mutex_free             sqlite3_api->mutex_free
92587#define sqlite3_mutex_leave            sqlite3_api->mutex_leave
92588#define sqlite3_mutex_try              sqlite3_api->mutex_try
92589#define sqlite3_open_v2                sqlite3_api->open_v2
92590#define sqlite3_release_memory         sqlite3_api->release_memory
92591#define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
92592#define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
92593#define sqlite3_sleep                  sqlite3_api->sleep
92594#define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
92595#define sqlite3_vfs_find               sqlite3_api->vfs_find
92596#define sqlite3_vfs_register           sqlite3_api->vfs_register
92597#define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
92598#define sqlite3_threadsafe             sqlite3_api->xthreadsafe
92599#define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
92600#define sqlite3_result_error_code      sqlite3_api->result_error_code
92601#define sqlite3_test_control           sqlite3_api->test_control
92602#define sqlite3_randomness             sqlite3_api->randomness
92603#define sqlite3_context_db_handle      sqlite3_api->context_db_handle
92604#define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
92605#define sqlite3_limit                  sqlite3_api->limit
92606#define sqlite3_next_stmt              sqlite3_api->next_stmt
92607#define sqlite3_sql                    sqlite3_api->sql
92608#define sqlite3_status                 sqlite3_api->status
92609#define sqlite3_backup_finish          sqlite3_api->backup_finish
92610#define sqlite3_backup_init            sqlite3_api->backup_init
92611#define sqlite3_backup_pagecount       sqlite3_api->backup_pagecount
92612#define sqlite3_backup_remaining       sqlite3_api->backup_remaining
92613#define sqlite3_backup_step            sqlite3_api->backup_step
92614#define sqlite3_compileoption_get      sqlite3_api->compileoption_get
92615#define sqlite3_compileoption_used     sqlite3_api->compileoption_used
92616#define sqlite3_create_function_v2     sqlite3_api->create_function_v2
92617#define sqlite3_db_config              sqlite3_api->db_config
92618#define sqlite3_db_mutex               sqlite3_api->db_mutex
92619#define sqlite3_db_status              sqlite3_api->db_status
92620#define sqlite3_extended_errcode       sqlite3_api->extended_errcode
92621#define sqlite3_log                    sqlite3_api->log
92622#define sqlite3_soft_heap_limit64      sqlite3_api->soft_heap_limit64
92623#define sqlite3_sourceid               sqlite3_api->sourceid
92624#define sqlite3_stmt_status            sqlite3_api->stmt_status
92625#define sqlite3_strnicmp               sqlite3_api->strnicmp
92626#define sqlite3_unlock_notify          sqlite3_api->unlock_notify
92627#define sqlite3_wal_autocheckpoint     sqlite3_api->wal_autocheckpoint
92628#define sqlite3_wal_checkpoint         sqlite3_api->wal_checkpoint
92629#define sqlite3_wal_hook               sqlite3_api->wal_hook
92630#define sqlite3_blob_reopen            sqlite3_api->blob_reopen
92631#define sqlite3_vtab_config            sqlite3_api->vtab_config
92632#define sqlite3_vtab_on_conflict       sqlite3_api->vtab_on_conflict
92633/* Version 3.7.16 and later */
92634#define sqlite3_close_v2               sqlite3_api->close_v2
92635#define sqlite3_db_filename            sqlite3_api->db_filename
92636#define sqlite3_db_readonly            sqlite3_api->db_readonly
92637#define sqlite3_db_release_memory      sqlite3_api->db_release_memory
92638#define sqlite3_errstr                 sqlite3_api->errstr
92639#define sqlite3_stmt_busy              sqlite3_api->stmt_busy
92640#define sqlite3_stmt_readonly          sqlite3_api->stmt_readonly
92641#define sqlite3_stricmp                sqlite3_api->stricmp
92642#define sqlite3_uri_boolean            sqlite3_api->uri_boolean
92643#define sqlite3_uri_int64              sqlite3_api->uri_int64
92644#define sqlite3_uri_parameter          sqlite3_api->uri_parameter
92645#define sqlite3_uri_vsnprintf          sqlite3_api->vsnprintf
92646#define sqlite3_wal_checkpoint_v2      sqlite3_api->wal_checkpoint_v2
92647#endif /* SQLITE_CORE */
92648
92649#ifndef SQLITE_CORE
92650  /* This case when the file really is being compiled as a loadable
92651  ** extension */
92652# define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api=0;
92653# define SQLITE_EXTENSION_INIT2(v)  sqlite3_api=v;
92654#else
92655  /* This case when the file is being statically linked into the
92656  ** application */
92657# define SQLITE_EXTENSION_INIT1     /*no-op*/
92658# define SQLITE_EXTENSION_INIT2(v)  (void)v; /* unused parameter */
92659#endif
92660
92661#endif /* _SQLITE3EXT_H_ */
92662
92663/************** End of sqlite3ext.h ******************************************/
92664/************** Continuing where we left off in loadext.c ********************/
92665/* #include <string.h> */
92666
92667#ifndef SQLITE_OMIT_LOAD_EXTENSION
92668
92669/*
92670** Some API routines are omitted when various features are
92671** excluded from a build of SQLite.  Substitute a NULL pointer
92672** for any missing APIs.
92673*/
92674#ifndef SQLITE_ENABLE_COLUMN_METADATA
92675# define sqlite3_column_database_name   0
92676# define sqlite3_column_database_name16 0
92677# define sqlite3_column_table_name      0
92678# define sqlite3_column_table_name16    0
92679# define sqlite3_column_origin_name     0
92680# define sqlite3_column_origin_name16   0
92681# define sqlite3_table_column_metadata  0
92682#endif
92683
92684#ifdef SQLITE_OMIT_AUTHORIZATION
92685# define sqlite3_set_authorizer         0
92686#endif
92687
92688#ifdef SQLITE_OMIT_UTF16
92689# define sqlite3_bind_text16            0
92690# define sqlite3_collation_needed16     0
92691# define sqlite3_column_decltype16      0
92692# define sqlite3_column_name16          0
92693# define sqlite3_column_text16          0
92694# define sqlite3_complete16             0
92695# define sqlite3_create_collation16     0
92696# define sqlite3_create_function16      0
92697# define sqlite3_errmsg16               0
92698# define sqlite3_open16                 0
92699# define sqlite3_prepare16              0
92700# define sqlite3_prepare16_v2           0
92701# define sqlite3_result_error16         0
92702# define sqlite3_result_text16          0
92703# define sqlite3_result_text16be        0
92704# define sqlite3_result_text16le        0
92705# define sqlite3_value_text16           0
92706# define sqlite3_value_text16be         0
92707# define sqlite3_value_text16le         0
92708# define sqlite3_column_database_name16 0
92709# define sqlite3_column_table_name16    0
92710# define sqlite3_column_origin_name16   0
92711#endif
92712
92713#ifdef SQLITE_OMIT_COMPLETE
92714# define sqlite3_complete 0
92715# define sqlite3_complete16 0
92716#endif
92717
92718#ifdef SQLITE_OMIT_DECLTYPE
92719# define sqlite3_column_decltype16      0
92720# define sqlite3_column_decltype        0
92721#endif
92722
92723#ifdef SQLITE_OMIT_PROGRESS_CALLBACK
92724# define sqlite3_progress_handler 0
92725#endif
92726
92727#ifdef SQLITE_OMIT_VIRTUALTABLE
92728# define sqlite3_create_module 0
92729# define sqlite3_create_module_v2 0
92730# define sqlite3_declare_vtab 0
92731# define sqlite3_vtab_config 0
92732# define sqlite3_vtab_on_conflict 0
92733#endif
92734
92735#ifdef SQLITE_OMIT_SHARED_CACHE
92736# define sqlite3_enable_shared_cache 0
92737#endif
92738
92739#ifdef SQLITE_OMIT_TRACE
92740# define sqlite3_profile       0
92741# define sqlite3_trace         0
92742#endif
92743
92744#ifdef SQLITE_OMIT_GET_TABLE
92745# define sqlite3_free_table    0
92746# define sqlite3_get_table     0
92747#endif
92748
92749#ifdef SQLITE_OMIT_INCRBLOB
92750#define sqlite3_bind_zeroblob  0
92751#define sqlite3_blob_bytes     0
92752#define sqlite3_blob_close     0
92753#define sqlite3_blob_open      0
92754#define sqlite3_blob_read      0
92755#define sqlite3_blob_write     0
92756#define sqlite3_blob_reopen    0
92757#endif
92758
92759/*
92760** The following structure contains pointers to all SQLite API routines.
92761** A pointer to this structure is passed into extensions when they are
92762** loaded so that the extension can make calls back into the SQLite
92763** library.
92764**
92765** When adding new APIs, add them to the bottom of this structure
92766** in order to preserve backwards compatibility.
92767**
92768** Extensions that use newer APIs should first call the
92769** sqlite3_libversion_number() to make sure that the API they
92770** intend to use is supported by the library.  Extensions should
92771** also check to make sure that the pointer to the function is
92772** not NULL before calling it.
92773*/
92774static const sqlite3_api_routines sqlite3Apis = {
92775  sqlite3_aggregate_context,
92776#ifndef SQLITE_OMIT_DEPRECATED
92777  sqlite3_aggregate_count,
92778#else
92779  0,
92780#endif
92781  sqlite3_bind_blob,
92782  sqlite3_bind_double,
92783  sqlite3_bind_int,
92784  sqlite3_bind_int64,
92785  sqlite3_bind_null,
92786  sqlite3_bind_parameter_count,
92787  sqlite3_bind_parameter_index,
92788  sqlite3_bind_parameter_name,
92789  sqlite3_bind_text,
92790  sqlite3_bind_text16,
92791  sqlite3_bind_value,
92792  sqlite3_busy_handler,
92793  sqlite3_busy_timeout,
92794  sqlite3_changes,
92795  sqlite3_close,
92796  sqlite3_collation_needed,
92797  sqlite3_collation_needed16,
92798  sqlite3_column_blob,
92799  sqlite3_column_bytes,
92800  sqlite3_column_bytes16,
92801  sqlite3_column_count,
92802  sqlite3_column_database_name,
92803  sqlite3_column_database_name16,
92804  sqlite3_column_decltype,
92805  sqlite3_column_decltype16,
92806  sqlite3_column_double,
92807  sqlite3_column_int,
92808  sqlite3_column_int64,
92809  sqlite3_column_name,
92810  sqlite3_column_name16,
92811  sqlite3_column_origin_name,
92812  sqlite3_column_origin_name16,
92813  sqlite3_column_table_name,
92814  sqlite3_column_table_name16,
92815  sqlite3_column_text,
92816  sqlite3_column_text16,
92817  sqlite3_column_type,
92818  sqlite3_column_value,
92819  sqlite3_commit_hook,
92820  sqlite3_complete,
92821  sqlite3_complete16,
92822  sqlite3_create_collation,
92823  sqlite3_create_collation16,
92824  sqlite3_create_function,
92825  sqlite3_create_function16,
92826  sqlite3_create_module,
92827  sqlite3_data_count,
92828  sqlite3_db_handle,
92829  sqlite3_declare_vtab,
92830  sqlite3_enable_shared_cache,
92831  sqlite3_errcode,
92832  sqlite3_errmsg,
92833  sqlite3_errmsg16,
92834  sqlite3_exec,
92835#ifndef SQLITE_OMIT_DEPRECATED
92836  sqlite3_expired,
92837#else
92838  0,
92839#endif
92840  sqlite3_finalize,
92841  sqlite3_free,
92842  sqlite3_free_table,
92843  sqlite3_get_autocommit,
92844  sqlite3_get_auxdata,
92845  sqlite3_get_table,
92846  0,     /* Was sqlite3_global_recover(), but that function is deprecated */
92847  sqlite3_interrupt,
92848  sqlite3_last_insert_rowid,
92849  sqlite3_libversion,
92850  sqlite3_libversion_number,
92851  sqlite3_malloc,
92852  sqlite3_mprintf,
92853  sqlite3_open,
92854  sqlite3_open16,
92855  sqlite3_prepare,
92856  sqlite3_prepare16,
92857  sqlite3_profile,
92858  sqlite3_progress_handler,
92859  sqlite3_realloc,
92860  sqlite3_reset,
92861  sqlite3_result_blob,
92862  sqlite3_result_double,
92863  sqlite3_result_error,
92864  sqlite3_result_error16,
92865  sqlite3_result_int,
92866  sqlite3_result_int64,
92867  sqlite3_result_null,
92868  sqlite3_result_text,
92869  sqlite3_result_text16,
92870  sqlite3_result_text16be,
92871  sqlite3_result_text16le,
92872  sqlite3_result_value,
92873  sqlite3_rollback_hook,
92874  sqlite3_set_authorizer,
92875  sqlite3_set_auxdata,
92876  sqlite3_snprintf,
92877  sqlite3_step,
92878  sqlite3_table_column_metadata,
92879#ifndef SQLITE_OMIT_DEPRECATED
92880  sqlite3_thread_cleanup,
92881#else
92882  0,
92883#endif
92884  sqlite3_total_changes,
92885  sqlite3_trace,
92886#ifndef SQLITE_OMIT_DEPRECATED
92887  sqlite3_transfer_bindings,
92888#else
92889  0,
92890#endif
92891  sqlite3_update_hook,
92892  sqlite3_user_data,
92893  sqlite3_value_blob,
92894  sqlite3_value_bytes,
92895  sqlite3_value_bytes16,
92896  sqlite3_value_double,
92897  sqlite3_value_int,
92898  sqlite3_value_int64,
92899  sqlite3_value_numeric_type,
92900  sqlite3_value_text,
92901  sqlite3_value_text16,
92902  sqlite3_value_text16be,
92903  sqlite3_value_text16le,
92904  sqlite3_value_type,
92905  sqlite3_vmprintf,
92906  /*
92907  ** The original API set ends here.  All extensions can call any
92908  ** of the APIs above provided that the pointer is not NULL.  But
92909  ** before calling APIs that follow, extension should check the
92910  ** sqlite3_libversion_number() to make sure they are dealing with
92911  ** a library that is new enough to support that API.
92912  *************************************************************************
92913  */
92914  sqlite3_overload_function,
92915
92916  /*
92917  ** Added after 3.3.13
92918  */
92919  sqlite3_prepare_v2,
92920  sqlite3_prepare16_v2,
92921  sqlite3_clear_bindings,
92922
92923  /*
92924  ** Added for 3.4.1
92925  */
92926  sqlite3_create_module_v2,
92927
92928  /*
92929  ** Added for 3.5.0
92930  */
92931  sqlite3_bind_zeroblob,
92932  sqlite3_blob_bytes,
92933  sqlite3_blob_close,
92934  sqlite3_blob_open,
92935  sqlite3_blob_read,
92936  sqlite3_blob_write,
92937  sqlite3_create_collation_v2,
92938  sqlite3_file_control,
92939  sqlite3_memory_highwater,
92940  sqlite3_memory_used,
92941#ifdef SQLITE_MUTEX_OMIT
92942  0,
92943  0,
92944  0,
92945  0,
92946  0,
92947#else
92948  sqlite3_mutex_alloc,
92949  sqlite3_mutex_enter,
92950  sqlite3_mutex_free,
92951  sqlite3_mutex_leave,
92952  sqlite3_mutex_try,
92953#endif
92954  sqlite3_open_v2,
92955  sqlite3_release_memory,
92956  sqlite3_result_error_nomem,
92957  sqlite3_result_error_toobig,
92958  sqlite3_sleep,
92959  sqlite3_soft_heap_limit,
92960  sqlite3_vfs_find,
92961  sqlite3_vfs_register,
92962  sqlite3_vfs_unregister,
92963
92964  /*
92965  ** Added for 3.5.8
92966  */
92967  sqlite3_threadsafe,
92968  sqlite3_result_zeroblob,
92969  sqlite3_result_error_code,
92970  sqlite3_test_control,
92971  sqlite3_randomness,
92972  sqlite3_context_db_handle,
92973
92974  /*
92975  ** Added for 3.6.0
92976  */
92977  sqlite3_extended_result_codes,
92978  sqlite3_limit,
92979  sqlite3_next_stmt,
92980  sqlite3_sql,
92981  sqlite3_status,
92982
92983  /*
92984  ** Added for 3.7.4
92985  */
92986  sqlite3_backup_finish,
92987  sqlite3_backup_init,
92988  sqlite3_backup_pagecount,
92989  sqlite3_backup_remaining,
92990  sqlite3_backup_step,
92991#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
92992  sqlite3_compileoption_get,
92993  sqlite3_compileoption_used,
92994#else
92995  0,
92996  0,
92997#endif
92998  sqlite3_create_function_v2,
92999  sqlite3_db_config,
93000  sqlite3_db_mutex,
93001  sqlite3_db_status,
93002  sqlite3_extended_errcode,
93003  sqlite3_log,
93004  sqlite3_soft_heap_limit64,
93005  sqlite3_sourceid,
93006  sqlite3_stmt_status,
93007  sqlite3_strnicmp,
93008#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
93009  sqlite3_unlock_notify,
93010#else
93011  0,
93012#endif
93013#ifndef SQLITE_OMIT_WAL
93014  sqlite3_wal_autocheckpoint,
93015  sqlite3_wal_checkpoint,
93016  sqlite3_wal_hook,
93017#else
93018  0,
93019  0,
93020  0,
93021#endif
93022  sqlite3_blob_reopen,
93023  sqlite3_vtab_config,
93024  sqlite3_vtab_on_conflict,
93025  sqlite3_close_v2,
93026  sqlite3_db_filename,
93027  sqlite3_db_readonly,
93028  sqlite3_db_release_memory,
93029  sqlite3_errstr,
93030  sqlite3_stmt_busy,
93031  sqlite3_stmt_readonly,
93032  sqlite3_stricmp,
93033  sqlite3_uri_boolean,
93034  sqlite3_uri_int64,
93035  sqlite3_uri_parameter,
93036  sqlite3_vsnprintf,
93037  sqlite3_wal_checkpoint_v2
93038};
93039
93040/*
93041** Attempt to load an SQLite extension library contained in the file
93042** zFile.  The entry point is zProc.  zProc may be 0 in which case a
93043** default entry point name (sqlite3_extension_init) is used.  Use
93044** of the default name is recommended.
93045**
93046** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
93047**
93048** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
93049** error message text.  The calling function should free this memory
93050** by calling sqlite3DbFree(db, ).
93051*/
93052static int sqlite3LoadExtension(
93053  sqlite3 *db,          /* Load the extension into this database connection */
93054  const char *zFile,    /* Name of the shared library containing extension */
93055  const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
93056  char **pzErrMsg       /* Put error message here if not 0 */
93057){
93058  sqlite3_vfs *pVfs = db->pVfs;
93059  void *handle;
93060  int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
93061  char *zErrmsg = 0;
93062  const char *zEntry;
93063  char *zAltEntry = 0;
93064  void **aHandle;
93065  int nMsg = 300 + sqlite3Strlen30(zFile);
93066  int ii;
93067
93068  /* Shared library endings to try if zFile cannot be loaded as written */
93069  static const char *azEndings[] = {
93070#if SQLITE_OS_WIN
93071     "dll"
93072#elif defined(__APPLE__)
93073     "dylib"
93074#else
93075     "so"
93076#endif
93077  };
93078
93079
93080  if( pzErrMsg ) *pzErrMsg = 0;
93081
93082  /* Ticket #1863.  To avoid a creating security problems for older
93083  ** applications that relink against newer versions of SQLite, the
93084  ** ability to run load_extension is turned off by default.  One
93085  ** must call sqlite3_enable_load_extension() to turn on extension
93086  ** loading.  Otherwise you get the following error.
93087  */
93088  if( (db->flags & SQLITE_LoadExtension)==0 ){
93089    if( pzErrMsg ){
93090      *pzErrMsg = sqlite3_mprintf("not authorized");
93091    }
93092    return SQLITE_ERROR;
93093  }
93094
93095  zEntry = zProc ? zProc : "sqlite3_extension_init";
93096
93097  handle = sqlite3OsDlOpen(pVfs, zFile);
93098#if SQLITE_OS_UNIX || SQLITE_OS_WIN
93099  for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
93100    char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
93101    if( zAltFile==0 ) return SQLITE_NOMEM;
93102    handle = sqlite3OsDlOpen(pVfs, zAltFile);
93103    sqlite3_free(zAltFile);
93104  }
93105#endif
93106  if( handle==0 ){
93107    if( pzErrMsg ){
93108      *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
93109      if( zErrmsg ){
93110        sqlite3_snprintf(nMsg, zErrmsg,
93111            "unable to open shared library [%s]", zFile);
93112        sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
93113      }
93114    }
93115    return SQLITE_ERROR;
93116  }
93117  xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
93118                   sqlite3OsDlSym(pVfs, handle, zEntry);
93119
93120  /* If no entry point was specified and the default legacy
93121  ** entry point name "sqlite3_extension_init" was not found, then
93122  ** construct an entry point name "sqlite3_X_init" where the X is
93123  ** replaced by the lowercase value of every ASCII alphabetic
93124  ** character in the filename after the last "/" upto the first ".",
93125  ** and eliding the first three characters if they are "lib".
93126  ** Examples:
93127  **
93128  **    /usr/local/lib/libExample5.4.3.so ==>  sqlite3_example_init
93129  **    C:/lib/mathfuncs.dll              ==>  sqlite3_mathfuncs_init
93130  */
93131  if( xInit==0 && zProc==0 ){
93132    int iFile, iEntry, c;
93133    int ncFile = sqlite3Strlen30(zFile);
93134    zAltEntry = sqlite3_malloc(ncFile+30);
93135    if( zAltEntry==0 ){
93136      sqlite3OsDlClose(pVfs, handle);
93137      return SQLITE_NOMEM;
93138    }
93139    memcpy(zAltEntry, "sqlite3_", 8);
93140    for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){}
93141    iFile++;
93142    if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
93143    for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
93144      if( sqlite3Isalpha(c) ){
93145        zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c];
93146      }
93147    }
93148    memcpy(zAltEntry+iEntry, "_init", 6);
93149    zEntry = zAltEntry;
93150    xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
93151                     sqlite3OsDlSym(pVfs, handle, zEntry);
93152  }
93153  if( xInit==0 ){
93154    if( pzErrMsg ){
93155      nMsg += sqlite3Strlen30(zEntry);
93156      *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
93157      if( zErrmsg ){
93158        sqlite3_snprintf(nMsg, zErrmsg,
93159            "no entry point [%s] in shared library [%s]", zEntry, zFile);
93160        sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
93161      }
93162    }
93163    sqlite3OsDlClose(pVfs, handle);
93164    sqlite3_free(zAltEntry);
93165    return SQLITE_ERROR;
93166  }
93167  sqlite3_free(zAltEntry);
93168  if( xInit(db, &zErrmsg, &sqlite3Apis) ){
93169    if( pzErrMsg ){
93170      *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
93171    }
93172    sqlite3_free(zErrmsg);
93173    sqlite3OsDlClose(pVfs, handle);
93174    return SQLITE_ERROR;
93175  }
93176
93177  /* Append the new shared library handle to the db->aExtension array. */
93178  aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
93179  if( aHandle==0 ){
93180    return SQLITE_NOMEM;
93181  }
93182  if( db->nExtension>0 ){
93183    memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
93184  }
93185  sqlite3DbFree(db, db->aExtension);
93186  db->aExtension = aHandle;
93187
93188  db->aExtension[db->nExtension++] = handle;
93189  return SQLITE_OK;
93190}
93191SQLITE_API int sqlite3_load_extension(
93192  sqlite3 *db,          /* Load the extension into this database connection */
93193  const char *zFile,    /* Name of the shared library containing extension */
93194  const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
93195  char **pzErrMsg       /* Put error message here if not 0 */
93196){
93197  int rc;
93198  sqlite3_mutex_enter(db->mutex);
93199  rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
93200  rc = sqlite3ApiExit(db, rc);
93201  sqlite3_mutex_leave(db->mutex);
93202  return rc;
93203}
93204
93205/*
93206** Call this routine when the database connection is closing in order
93207** to clean up loaded extensions
93208*/
93209SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
93210  int i;
93211  assert( sqlite3_mutex_held(db->mutex) );
93212  for(i=0; i<db->nExtension; i++){
93213    sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
93214  }
93215  sqlite3DbFree(db, db->aExtension);
93216}
93217
93218/*
93219** Enable or disable extension loading.  Extension loading is disabled by
93220** default so as not to open security holes in older applications.
93221*/
93222SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
93223  sqlite3_mutex_enter(db->mutex);
93224  if( onoff ){
93225    db->flags |= SQLITE_LoadExtension;
93226  }else{
93227    db->flags &= ~SQLITE_LoadExtension;
93228  }
93229  sqlite3_mutex_leave(db->mutex);
93230  return SQLITE_OK;
93231}
93232
93233#endif /* SQLITE_OMIT_LOAD_EXTENSION */
93234
93235/*
93236** The auto-extension code added regardless of whether or not extension
93237** loading is supported.  We need a dummy sqlite3Apis pointer for that
93238** code if regular extension loading is not available.  This is that
93239** dummy pointer.
93240*/
93241#ifdef SQLITE_OMIT_LOAD_EXTENSION
93242static const sqlite3_api_routines sqlite3Apis = { 0 };
93243#endif
93244
93245
93246/*
93247** The following object holds the list of automatically loaded
93248** extensions.
93249**
93250** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
93251** mutex must be held while accessing this list.
93252*/
93253typedef struct sqlite3AutoExtList sqlite3AutoExtList;
93254static SQLITE_WSD struct sqlite3AutoExtList {
93255  int nExt;              /* Number of entries in aExt[] */
93256  void (**aExt)(void);   /* Pointers to the extension init functions */
93257} sqlite3Autoext = { 0, 0 };
93258
93259/* The "wsdAutoext" macro will resolve to the autoextension
93260** state vector.  If writable static data is unsupported on the target,
93261** we have to locate the state vector at run-time.  In the more common
93262** case where writable static data is supported, wsdStat can refer directly
93263** to the "sqlite3Autoext" state vector declared above.
93264*/
93265#ifdef SQLITE_OMIT_WSD
93266# define wsdAutoextInit \
93267  sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
93268# define wsdAutoext x[0]
93269#else
93270# define wsdAutoextInit
93271# define wsdAutoext sqlite3Autoext
93272#endif
93273
93274
93275/*
93276** Register a statically linked extension that is automatically
93277** loaded by every new database connection.
93278*/
93279SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
93280  int rc = SQLITE_OK;
93281#ifndef SQLITE_OMIT_AUTOINIT
93282  rc = sqlite3_initialize();
93283  if( rc ){
93284    return rc;
93285  }else
93286#endif
93287  {
93288    int i;
93289#if SQLITE_THREADSAFE
93290    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
93291#endif
93292    wsdAutoextInit;
93293    sqlite3_mutex_enter(mutex);
93294    for(i=0; i<wsdAutoext.nExt; i++){
93295      if( wsdAutoext.aExt[i]==xInit ) break;
93296    }
93297    if( i==wsdAutoext.nExt ){
93298      int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
93299      void (**aNew)(void);
93300      aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
93301      if( aNew==0 ){
93302        rc = SQLITE_NOMEM;
93303      }else{
93304        wsdAutoext.aExt = aNew;
93305        wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
93306        wsdAutoext.nExt++;
93307      }
93308    }
93309    sqlite3_mutex_leave(mutex);
93310    assert( (rc&0xff)==rc );
93311    return rc;
93312  }
93313}
93314
93315/*
93316** Reset the automatic extension loading mechanism.
93317*/
93318SQLITE_API void sqlite3_reset_auto_extension(void){
93319#ifndef SQLITE_OMIT_AUTOINIT
93320  if( sqlite3_initialize()==SQLITE_OK )
93321#endif
93322  {
93323#if SQLITE_THREADSAFE
93324    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
93325#endif
93326    wsdAutoextInit;
93327    sqlite3_mutex_enter(mutex);
93328    sqlite3_free(wsdAutoext.aExt);
93329    wsdAutoext.aExt = 0;
93330    wsdAutoext.nExt = 0;
93331    sqlite3_mutex_leave(mutex);
93332  }
93333}
93334
93335/*
93336** Load all automatic extensions.
93337**
93338** If anything goes wrong, set an error in the database connection.
93339*/
93340SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
93341  int i;
93342  int go = 1;
93343  int rc;
93344  int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
93345
93346  wsdAutoextInit;
93347  if( wsdAutoext.nExt==0 ){
93348    /* Common case: early out without every having to acquire a mutex */
93349    return;
93350  }
93351  for(i=0; go; i++){
93352    char *zErrmsg;
93353#if SQLITE_THREADSAFE
93354    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
93355#endif
93356    sqlite3_mutex_enter(mutex);
93357    if( i>=wsdAutoext.nExt ){
93358      xInit = 0;
93359      go = 0;
93360    }else{
93361      xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
93362              wsdAutoext.aExt[i];
93363    }
93364    sqlite3_mutex_leave(mutex);
93365    zErrmsg = 0;
93366    if( xInit && (rc = xInit(db, &zErrmsg, &sqlite3Apis))!=0 ){
93367      sqlite3Error(db, rc,
93368            "automatic extension loading failed: %s", zErrmsg);
93369      go = 0;
93370    }
93371    sqlite3_free(zErrmsg);
93372  }
93373}
93374
93375/************** End of loadext.c *********************************************/
93376/************** Begin file pragma.c ******************************************/
93377/*
93378** 2003 April 6
93379**
93380** The author disclaims copyright to this source code.  In place of
93381** a legal notice, here is a blessing:
93382**
93383**    May you do good and not evil.
93384**    May you find forgiveness for yourself and forgive others.
93385**    May you share freely, never taking more than you give.
93386**
93387*************************************************************************
93388** This file contains code used to implement the PRAGMA command.
93389*/
93390
93391/*
93392** Interpret the given string as a safety level.  Return 0 for OFF,
93393** 1 for ON or NORMAL and 2 for FULL.  Return 1 for an empty or
93394** unrecognized string argument.  The FULL option is disallowed
93395** if the omitFull parameter it 1.
93396**
93397** Note that the values returned are one less that the values that
93398** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
93399** to support legacy SQL code.  The safety level used to be boolean
93400** and older scripts may have used numbers 0 for OFF and 1 for ON.
93401*/
93402static u8 getSafetyLevel(const char *z, int omitFull, int dflt){
93403                             /* 123456789 123456789 */
93404  static const char zText[] = "onoffalseyestruefull";
93405  static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
93406  static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
93407  static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};
93408  int i, n;
93409  if( sqlite3Isdigit(*z) ){
93410    return (u8)sqlite3Atoi(z);
93411  }
93412  n = sqlite3Strlen30(z);
93413  for(i=0; i<ArraySize(iLength)-omitFull; i++){
93414    if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
93415      return iValue[i];
93416    }
93417  }
93418  return dflt;
93419}
93420
93421/*
93422** Interpret the given string as a boolean value.
93423*/
93424SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, int dflt){
93425  return getSafetyLevel(z,1,dflt)!=0;
93426}
93427
93428/* The sqlite3GetBoolean() function is used by other modules but the
93429** remainder of this file is specific to PRAGMA processing.  So omit
93430** the rest of the file if PRAGMAs are omitted from the build.
93431*/
93432#if !defined(SQLITE_OMIT_PRAGMA)
93433
93434/*
93435** Interpret the given string as a locking mode value.
93436*/
93437static int getLockingMode(const char *z){
93438  if( z ){
93439    if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
93440    if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
93441  }
93442  return PAGER_LOCKINGMODE_QUERY;
93443}
93444
93445#ifndef SQLITE_OMIT_AUTOVACUUM
93446/*
93447** Interpret the given string as an auto-vacuum mode value.
93448**
93449** The following strings, "none", "full" and "incremental" are
93450** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
93451*/
93452static int getAutoVacuum(const char *z){
93453  int i;
93454  if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
93455  if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
93456  if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
93457  i = sqlite3Atoi(z);
93458  return (u8)((i>=0&&i<=2)?i:0);
93459}
93460#endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
93461
93462#ifndef SQLITE_OMIT_PAGER_PRAGMAS
93463/*
93464** Interpret the given string as a temp db location. Return 1 for file
93465** backed temporary databases, 2 for the Red-Black tree in memory database
93466** and 0 to use the compile-time default.
93467*/
93468static int getTempStore(const char *z){
93469  if( z[0]>='0' && z[0]<='2' ){
93470    return z[0] - '0';
93471  }else if( sqlite3StrICmp(z, "file")==0 ){
93472    return 1;
93473  }else if( sqlite3StrICmp(z, "memory")==0 ){
93474    return 2;
93475  }else{
93476    return 0;
93477  }
93478}
93479#endif /* SQLITE_PAGER_PRAGMAS */
93480
93481#ifndef SQLITE_OMIT_PAGER_PRAGMAS
93482/*
93483** Invalidate temp storage, either when the temp storage is changed
93484** from default, or when 'file' and the temp_store_directory has changed
93485*/
93486static int invalidateTempStorage(Parse *pParse){
93487  sqlite3 *db = pParse->db;
93488  if( db->aDb[1].pBt!=0 ){
93489    if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
93490      sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
93491        "from within a transaction");
93492      return SQLITE_ERROR;
93493    }
93494    sqlite3BtreeClose(db->aDb[1].pBt);
93495    db->aDb[1].pBt = 0;
93496    sqlite3ResetAllSchemasOfConnection(db);
93497  }
93498  return SQLITE_OK;
93499}
93500#endif /* SQLITE_PAGER_PRAGMAS */
93501
93502#ifndef SQLITE_OMIT_PAGER_PRAGMAS
93503/*
93504** If the TEMP database is open, close it and mark the database schema
93505** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
93506** or DEFAULT_TEMP_STORE pragmas.
93507*/
93508static int changeTempStorage(Parse *pParse, const char *zStorageType){
93509  int ts = getTempStore(zStorageType);
93510  sqlite3 *db = pParse->db;
93511  if( db->temp_store==ts ) return SQLITE_OK;
93512  if( invalidateTempStorage( pParse ) != SQLITE_OK ){
93513    return SQLITE_ERROR;
93514  }
93515  db->temp_store = (u8)ts;
93516  return SQLITE_OK;
93517}
93518#endif /* SQLITE_PAGER_PRAGMAS */
93519
93520/*
93521** Generate code to return a single integer value.
93522*/
93523static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
93524  Vdbe *v = sqlite3GetVdbe(pParse);
93525  int mem = ++pParse->nMem;
93526  i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
93527  if( pI64 ){
93528    memcpy(pI64, &value, sizeof(value));
93529  }
93530  sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
93531  sqlite3VdbeSetNumCols(v, 1);
93532  sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
93533  sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
93534}
93535
93536#ifndef SQLITE_OMIT_FLAG_PRAGMAS
93537/*
93538** Check to see if zRight and zLeft refer to a pragma that queries
93539** or changes one of the flags in db->flags.  Return 1 if so and 0 if not.
93540** Also, implement the pragma.
93541*/
93542static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
93543  static const struct sPragmaType {
93544    const char *zName;  /* Name of the pragma */
93545    int mask;           /* Mask for the db->flags value */
93546  } aPragma[] = {
93547    { "full_column_names",        SQLITE_FullColNames  },
93548    { "short_column_names",       SQLITE_ShortColNames },
93549    { "count_changes",            SQLITE_CountRows     },
93550    { "empty_result_callbacks",   SQLITE_NullCallback  },
93551    { "legacy_file_format",       SQLITE_LegacyFileFmt },
93552    { "fullfsync",                SQLITE_FullFSync     },
93553    { "checkpoint_fullfsync",     SQLITE_CkptFullFSync },
93554    { "reverse_unordered_selects", SQLITE_ReverseOrder  },
93555#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
93556    { "automatic_index",          SQLITE_AutoIndex     },
93557#endif
93558#ifdef SQLITE_DEBUG
93559    { "sql_trace",                SQLITE_SqlTrace      },
93560    { "vdbe_listing",             SQLITE_VdbeListing   },
93561    { "vdbe_trace",               SQLITE_VdbeTrace     },
93562    { "vdbe_addoptrace",          SQLITE_VdbeAddopTrace},
93563    { "vdbe_debug",    SQLITE_SqlTrace | SQLITE_VdbeListing
93564                               | SQLITE_VdbeTrace      },
93565#endif
93566#ifndef SQLITE_OMIT_CHECK
93567    { "ignore_check_constraints", SQLITE_IgnoreChecks  },
93568#endif
93569    /* The following is VERY experimental */
93570    { "writable_schema",          SQLITE_WriteSchema|SQLITE_RecoveryMode },
93571
93572    /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
93573    ** flag if there are any active statements. */
93574    { "read_uncommitted",         SQLITE_ReadUncommitted },
93575    { "recursive_triggers",       SQLITE_RecTriggers },
93576
93577    /* This flag may only be set if both foreign-key and trigger support
93578    ** are present in the build.  */
93579#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
93580    { "foreign_keys",             SQLITE_ForeignKeys },
93581#endif
93582  };
93583  int i;
93584  const struct sPragmaType *p;
93585  for(i=0, p=aPragma; i<ArraySize(aPragma); i++, p++){
93586    if( sqlite3StrICmp(zLeft, p->zName)==0 ){
93587      sqlite3 *db = pParse->db;
93588      Vdbe *v;
93589      v = sqlite3GetVdbe(pParse);
93590      assert( v!=0 );  /* Already allocated by sqlite3Pragma() */
93591      if( ALWAYS(v) ){
93592        if( zRight==0 ){
93593          returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
93594        }else{
93595          int mask = p->mask;          /* Mask of bits to set or clear. */
93596          if( db->autoCommit==0 ){
93597            /* Foreign key support may not be enabled or disabled while not
93598            ** in auto-commit mode.  */
93599            mask &= ~(SQLITE_ForeignKeys);
93600          }
93601
93602          if( sqlite3GetBoolean(zRight, 0) ){
93603            db->flags |= mask;
93604          }else{
93605            db->flags &= ~mask;
93606          }
93607
93608          /* Many of the flag-pragmas modify the code generated by the SQL
93609          ** compiler (eg. count_changes). So add an opcode to expire all
93610          ** compiled SQL statements after modifying a pragma value.
93611          */
93612          sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
93613        }
93614      }
93615
93616      return 1;
93617    }
93618  }
93619  return 0;
93620}
93621#endif /* SQLITE_OMIT_FLAG_PRAGMAS */
93622
93623/*
93624** Return a human-readable name for a constraint resolution action.
93625*/
93626#ifndef SQLITE_OMIT_FOREIGN_KEY
93627static const char *actionName(u8 action){
93628  const char *zName;
93629  switch( action ){
93630    case OE_SetNull:  zName = "SET NULL";        break;
93631    case OE_SetDflt:  zName = "SET DEFAULT";     break;
93632    case OE_Cascade:  zName = "CASCADE";         break;
93633    case OE_Restrict: zName = "RESTRICT";        break;
93634    default:          zName = "NO ACTION";
93635                      assert( action==OE_None ); break;
93636  }
93637  return zName;
93638}
93639#endif
93640
93641
93642/*
93643** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
93644** defined in pager.h. This function returns the associated lowercase
93645** journal-mode name.
93646*/
93647SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
93648  static char * const azModeName[] = {
93649    "delete", "persist", "off", "truncate", "memory"
93650#ifndef SQLITE_OMIT_WAL
93651     , "wal"
93652#endif
93653  };
93654  assert( PAGER_JOURNALMODE_DELETE==0 );
93655  assert( PAGER_JOURNALMODE_PERSIST==1 );
93656  assert( PAGER_JOURNALMODE_OFF==2 );
93657  assert( PAGER_JOURNALMODE_TRUNCATE==3 );
93658  assert( PAGER_JOURNALMODE_MEMORY==4 );
93659  assert( PAGER_JOURNALMODE_WAL==5 );
93660  assert( eMode>=0 && eMode<=ArraySize(azModeName) );
93661
93662  if( eMode==ArraySize(azModeName) ) return 0;
93663  return azModeName[eMode];
93664}
93665
93666/*
93667** Process a pragma statement.
93668**
93669** Pragmas are of this form:
93670**
93671**      PRAGMA [database.]id [= value]
93672**
93673** The identifier might also be a string.  The value is a string, and
93674** identifier, or a number.  If minusFlag is true, then the value is
93675** a number that was preceded by a minus sign.
93676**
93677** If the left side is "database.id" then pId1 is the database name
93678** and pId2 is the id.  If the left side is just "id" then pId1 is the
93679** id and pId2 is any empty string.
93680*/
93681SQLITE_PRIVATE void sqlite3Pragma(
93682  Parse *pParse,
93683  Token *pId1,        /* First part of [database.]id field */
93684  Token *pId2,        /* Second part of [database.]id field, or NULL */
93685  Token *pValue,      /* Token for <value>, or NULL */
93686  int minusFlag       /* True if a '-' sign preceded <value> */
93687){
93688  char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
93689  char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
93690  const char *zDb = 0;   /* The database name */
93691  Token *pId;            /* Pointer to <id> token */
93692  int iDb;               /* Database index for <database> */
93693  char *aFcntl[4];       /* Argument to SQLITE_FCNTL_PRAGMA */
93694  int rc;                      /* return value form SQLITE_FCNTL_PRAGMA */
93695  sqlite3 *db = pParse->db;    /* The database connection */
93696  Db *pDb;                     /* The specific database being pragmaed */
93697  Vdbe *v = sqlite3GetVdbe(pParse);  /* Prepared statement */
93698
93699  if( v==0 ) return;
93700  sqlite3VdbeRunOnlyOnce(v);
93701  pParse->nMem = 2;
93702
93703  /* Interpret the [database.] part of the pragma statement. iDb is the
93704  ** index of the database this pragma is being applied to in db.aDb[]. */
93705  iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
93706  if( iDb<0 ) return;
93707  pDb = &db->aDb[iDb];
93708
93709  /* If the temp database has been explicitly named as part of the
93710  ** pragma, make sure it is open.
93711  */
93712  if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
93713    return;
93714  }
93715
93716  zLeft = sqlite3NameFromToken(db, pId);
93717  if( !zLeft ) return;
93718  if( minusFlag ){
93719    zRight = sqlite3MPrintf(db, "-%T", pValue);
93720  }else{
93721    zRight = sqlite3NameFromToken(db, pValue);
93722  }
93723
93724  assert( pId2 );
93725  zDb = pId2->n>0 ? pDb->zName : 0;
93726  if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
93727    goto pragma_out;
93728  }
93729
93730  /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
93731  ** connection.  If it returns SQLITE_OK, then assume that the VFS
93732  ** handled the pragma and generate a no-op prepared statement.
93733  */
93734  aFcntl[0] = 0;
93735  aFcntl[1] = zLeft;
93736  aFcntl[2] = zRight;
93737  aFcntl[3] = 0;
93738  db->busyHandler.nBusy = 0;
93739  rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
93740  if( rc==SQLITE_OK ){
93741    if( aFcntl[0] ){
93742      int mem = ++pParse->nMem;
93743      sqlite3VdbeAddOp4(v, OP_String8, 0, mem, 0, aFcntl[0], 0);
93744      sqlite3VdbeSetNumCols(v, 1);
93745      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "result", SQLITE_STATIC);
93746      sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
93747      sqlite3_free(aFcntl[0]);
93748    }
93749  }else if( rc!=SQLITE_NOTFOUND ){
93750    if( aFcntl[0] ){
93751      sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
93752      sqlite3_free(aFcntl[0]);
93753    }
93754    pParse->nErr++;
93755    pParse->rc = rc;
93756  }else
93757
93758
93759#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
93760  /*
93761  **  PRAGMA [database.]default_cache_size
93762  **  PRAGMA [database.]default_cache_size=N
93763  **
93764  ** The first form reports the current persistent setting for the
93765  ** page cache size.  The value returned is the maximum number of
93766  ** pages in the page cache.  The second form sets both the current
93767  ** page cache size value and the persistent page cache size value
93768  ** stored in the database file.
93769  **
93770  ** Older versions of SQLite would set the default cache size to a
93771  ** negative number to indicate synchronous=OFF.  These days, synchronous
93772  ** is always on by default regardless of the sign of the default cache
93773  ** size.  But continue to take the absolute value of the default cache
93774  ** size of historical compatibility.
93775  */
93776  if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
93777    static const VdbeOpList getCacheSize[] = {
93778      { OP_Transaction, 0, 0,        0},                         /* 0 */
93779      { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
93780      { OP_IfPos,       1, 8,        0},
93781      { OP_Integer,     0, 2,        0},
93782      { OP_Subtract,    1, 2,        1},
93783      { OP_IfPos,       1, 8,        0},
93784      { OP_Integer,     0, 1,        0},                         /* 6 */
93785      { OP_Noop,        0, 0,        0},
93786      { OP_ResultRow,   1, 1,        0},
93787    };
93788    int addr;
93789    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
93790    sqlite3VdbeUsesBtree(v, iDb);
93791    if( !zRight ){
93792      sqlite3VdbeSetNumCols(v, 1);
93793      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
93794      pParse->nMem += 2;
93795      addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
93796      sqlite3VdbeChangeP1(v, addr, iDb);
93797      sqlite3VdbeChangeP1(v, addr+1, iDb);
93798      sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
93799    }else{
93800      int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
93801      sqlite3BeginWriteOperation(pParse, 0, iDb);
93802      sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
93803      sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
93804      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
93805      pDb->pSchema->cache_size = size;
93806      sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
93807    }
93808  }else
93809#endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
93810
93811#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
93812  /*
93813  **  PRAGMA [database.]page_size
93814  **  PRAGMA [database.]page_size=N
93815  **
93816  ** The first form reports the current setting for the
93817  ** database page size in bytes.  The second form sets the
93818  ** database page size value.  The value can only be set if
93819  ** the database has not yet been created.
93820  */
93821  if( sqlite3StrICmp(zLeft,"page_size")==0 ){
93822    Btree *pBt = pDb->pBt;
93823    assert( pBt!=0 );
93824    if( !zRight ){
93825      int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
93826      returnSingleInt(pParse, "page_size", size);
93827    }else{
93828      /* Malloc may fail when setting the page-size, as there is an internal
93829      ** buffer that the pager module resizes using sqlite3_realloc().
93830      */
93831      db->nextPagesize = sqlite3Atoi(zRight);
93832      if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
93833        db->mallocFailed = 1;
93834      }
93835    }
93836  }else
93837
93838  /*
93839  **  PRAGMA [database.]secure_delete
93840  **  PRAGMA [database.]secure_delete=ON/OFF
93841  **
93842  ** The first form reports the current setting for the
93843  ** secure_delete flag.  The second form changes the secure_delete
93844  ** flag setting and reports thenew value.
93845  */
93846  if( sqlite3StrICmp(zLeft,"secure_delete")==0 ){
93847    Btree *pBt = pDb->pBt;
93848    int b = -1;
93849    assert( pBt!=0 );
93850    if( zRight ){
93851      b = sqlite3GetBoolean(zRight, 0);
93852    }
93853    if( pId2->n==0 && b>=0 ){
93854      int ii;
93855      for(ii=0; ii<db->nDb; ii++){
93856        sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
93857      }
93858    }
93859    b = sqlite3BtreeSecureDelete(pBt, b);
93860    returnSingleInt(pParse, "secure_delete", b);
93861  }else
93862
93863  /*
93864  **  PRAGMA [database.]max_page_count
93865  **  PRAGMA [database.]max_page_count=N
93866  **
93867  ** The first form reports the current setting for the
93868  ** maximum number of pages in the database file.  The
93869  ** second form attempts to change this setting.  Both
93870  ** forms return the current setting.
93871  **
93872  ** The absolute value of N is used.  This is undocumented and might
93873  ** change.  The only purpose is to provide an easy way to test
93874  ** the sqlite3AbsInt32() function.
93875  **
93876  **  PRAGMA [database.]page_count
93877  **
93878  ** Return the number of pages in the specified database.
93879  */
93880  if( sqlite3StrICmp(zLeft,"page_count")==0
93881   || sqlite3StrICmp(zLeft,"max_page_count")==0
93882  ){
93883    int iReg;
93884    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
93885    sqlite3CodeVerifySchema(pParse, iDb);
93886    iReg = ++pParse->nMem;
93887    if( sqlite3Tolower(zLeft[0])=='p' ){
93888      sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
93889    }else{
93890      sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg,
93891                        sqlite3AbsInt32(sqlite3Atoi(zRight)));
93892    }
93893    sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
93894    sqlite3VdbeSetNumCols(v, 1);
93895    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
93896  }else
93897
93898  /*
93899  **  PRAGMA [database.]locking_mode
93900  **  PRAGMA [database.]locking_mode = (normal|exclusive)
93901  */
93902  if( sqlite3StrICmp(zLeft,"locking_mode")==0 ){
93903    const char *zRet = "normal";
93904    int eMode = getLockingMode(zRight);
93905
93906    if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
93907      /* Simple "PRAGMA locking_mode;" statement. This is a query for
93908      ** the current default locking mode (which may be different to
93909      ** the locking-mode of the main database).
93910      */
93911      eMode = db->dfltLockMode;
93912    }else{
93913      Pager *pPager;
93914      if( pId2->n==0 ){
93915        /* This indicates that no database name was specified as part
93916        ** of the PRAGMA command. In this case the locking-mode must be
93917        ** set on all attached databases, as well as the main db file.
93918        **
93919        ** Also, the sqlite3.dfltLockMode variable is set so that
93920        ** any subsequently attached databases also use the specified
93921        ** locking mode.
93922        */
93923        int ii;
93924        assert(pDb==&db->aDb[0]);
93925        for(ii=2; ii<db->nDb; ii++){
93926          pPager = sqlite3BtreePager(db->aDb[ii].pBt);
93927          sqlite3PagerLockingMode(pPager, eMode);
93928        }
93929        db->dfltLockMode = (u8)eMode;
93930      }
93931      pPager = sqlite3BtreePager(pDb->pBt);
93932      eMode = sqlite3PagerLockingMode(pPager, eMode);
93933    }
93934
93935    assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
93936    if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
93937      zRet = "exclusive";
93938    }
93939    sqlite3VdbeSetNumCols(v, 1);
93940    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
93941    sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
93942    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
93943  }else
93944
93945  /*
93946  **  PRAGMA [database.]journal_mode
93947  **  PRAGMA [database.]journal_mode =
93948  **                      (delete|persist|off|truncate|memory|wal|off)
93949  */
93950  if( sqlite3StrICmp(zLeft,"journal_mode")==0 ){
93951    int eMode;        /* One of the PAGER_JOURNALMODE_XXX symbols */
93952    int ii;           /* Loop counter */
93953
93954    /* Force the schema to be loaded on all databases.  This causes all
93955    ** database files to be opened and the journal_modes set.  This is
93956    ** necessary because subsequent processing must know if the databases
93957    ** are in WAL mode. */
93958    if( sqlite3ReadSchema(pParse) ){
93959      goto pragma_out;
93960    }
93961
93962    sqlite3VdbeSetNumCols(v, 1);
93963    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
93964
93965    if( zRight==0 ){
93966      /* If there is no "=MODE" part of the pragma, do a query for the
93967      ** current mode */
93968      eMode = PAGER_JOURNALMODE_QUERY;
93969    }else{
93970      const char *zMode;
93971      int n = sqlite3Strlen30(zRight);
93972      for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
93973        if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
93974      }
93975      if( !zMode ){
93976        /* If the "=MODE" part does not match any known journal mode,
93977        ** then do a query */
93978        eMode = PAGER_JOURNALMODE_QUERY;
93979      }
93980    }
93981    if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
93982      /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
93983      iDb = 0;
93984      pId2->n = 1;
93985    }
93986    for(ii=db->nDb-1; ii>=0; ii--){
93987      if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
93988        sqlite3VdbeUsesBtree(v, ii);
93989        sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
93990      }
93991    }
93992    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
93993  }else
93994
93995  /*
93996  **  PRAGMA [database.]journal_size_limit
93997  **  PRAGMA [database.]journal_size_limit=N
93998  **
93999  ** Get or set the size limit on rollback journal files.
94000  */
94001  if( sqlite3StrICmp(zLeft,"journal_size_limit")==0 ){
94002    Pager *pPager = sqlite3BtreePager(pDb->pBt);
94003    i64 iLimit = -2;
94004    if( zRight ){
94005      sqlite3Atoi64(zRight, &iLimit, 1000000, SQLITE_UTF8);
94006      if( iLimit<-1 ) iLimit = -1;
94007    }
94008    iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
94009    returnSingleInt(pParse, "journal_size_limit", iLimit);
94010  }else
94011
94012#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
94013
94014  /*
94015  **  PRAGMA [database.]auto_vacuum
94016  **  PRAGMA [database.]auto_vacuum=N
94017  **
94018  ** Get or set the value of the database 'auto-vacuum' parameter.
94019  ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
94020  */
94021#ifndef SQLITE_OMIT_AUTOVACUUM
94022  if( sqlite3StrICmp(zLeft,"auto_vacuum")==0 ){
94023    Btree *pBt = pDb->pBt;
94024    assert( pBt!=0 );
94025    if( sqlite3ReadSchema(pParse) ){
94026      goto pragma_out;
94027    }
94028    if( !zRight ){
94029      int auto_vacuum;
94030      if( ALWAYS(pBt) ){
94031         auto_vacuum = sqlite3BtreeGetAutoVacuum(pBt);
94032      }else{
94033         auto_vacuum = SQLITE_DEFAULT_AUTOVACUUM;
94034      }
94035      returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
94036    }else{
94037      int eAuto = getAutoVacuum(zRight);
94038      assert( eAuto>=0 && eAuto<=2 );
94039      db->nextAutovac = (u8)eAuto;
94040      if( ALWAYS(eAuto>=0) ){
94041        /* Call SetAutoVacuum() to set initialize the internal auto and
94042        ** incr-vacuum flags. This is required in case this connection
94043        ** creates the database file. It is important that it is created
94044        ** as an auto-vacuum capable db.
94045        */
94046        rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
94047        if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
94048          /* When setting the auto_vacuum mode to either "full" or
94049          ** "incremental", write the value of meta[6] in the database
94050          ** file. Before writing to meta[6], check that meta[3] indicates
94051          ** that this really is an auto-vacuum capable database.
94052          */
94053          static const VdbeOpList setMeta6[] = {
94054            { OP_Transaction,    0,         1,                 0},    /* 0 */
94055            { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
94056            { OP_If,             1,         0,                 0},    /* 2 */
94057            { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
94058            { OP_Integer,        0,         1,                 0},    /* 4 */
94059            { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 1},    /* 5 */
94060          };
94061          int iAddr;
94062          iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
94063          sqlite3VdbeChangeP1(v, iAddr, iDb);
94064          sqlite3VdbeChangeP1(v, iAddr+1, iDb);
94065          sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
94066          sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
94067          sqlite3VdbeChangeP1(v, iAddr+5, iDb);
94068          sqlite3VdbeUsesBtree(v, iDb);
94069        }
94070      }
94071    }
94072  }else
94073#endif
94074
94075  /*
94076  **  PRAGMA [database.]incremental_vacuum(N)
94077  **
94078  ** Do N steps of incremental vacuuming on a database.
94079  */
94080#ifndef SQLITE_OMIT_AUTOVACUUM
94081  if( sqlite3StrICmp(zLeft,"incremental_vacuum")==0 ){
94082    int iLimit, addr;
94083    if( sqlite3ReadSchema(pParse) ){
94084      goto pragma_out;
94085    }
94086    if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
94087      iLimit = 0x7fffffff;
94088    }
94089    sqlite3BeginWriteOperation(pParse, 0, iDb);
94090    sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
94091    addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
94092    sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
94093    sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
94094    sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
94095    sqlite3VdbeJumpHere(v, addr);
94096  }else
94097#endif
94098
94099#ifndef SQLITE_OMIT_PAGER_PRAGMAS
94100  /*
94101  **  PRAGMA [database.]cache_size
94102  **  PRAGMA [database.]cache_size=N
94103  **
94104  ** The first form reports the current local setting for the
94105  ** page cache size. The second form sets the local
94106  ** page cache size value.  If N is positive then that is the
94107  ** number of pages in the cache.  If N is negative, then the
94108  ** number of pages is adjusted so that the cache uses -N kibibytes
94109  ** of memory.
94110  */
94111  if( sqlite3StrICmp(zLeft,"cache_size")==0 ){
94112    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
94113    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
94114    if( !zRight ){
94115      returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
94116    }else{
94117      int size = sqlite3Atoi(zRight);
94118      pDb->pSchema->cache_size = size;
94119      sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
94120    }
94121  }else
94122
94123  /*
94124  **  PRAGMA [database.]mmap_size(N)
94125  **
94126  ** Used to set mapping size limit. The mapping size limit is
94127  ** used to limit the aggregate size of all memory mapped regions of the
94128  ** database file. If this parameter is set to zero, then memory mapping
94129  ** is not used at all.  If N is negative, then the default memory map
94130  ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
94131  ** The parameter N is measured in bytes.
94132  **
94133  ** This value is advisory.  The underlying VFS is free to memory map
94134  ** as little or as much as it wants.  Except, if N is set to 0 then the
94135  ** upper layers will never invoke the xFetch interfaces to the VFS.
94136  */
94137  if( sqlite3StrICmp(zLeft,"mmap_size")==0 ){
94138    sqlite3_int64 sz;
94139    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
94140    if( zRight ){
94141      int ii;
94142      sqlite3Atoi64(zRight, &sz, 1000, SQLITE_UTF8);
94143      if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
94144      if( pId2->n==0 ) db->szMmap = sz;
94145      for(ii=db->nDb-1; ii>=0; ii--){
94146        if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
94147          sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
94148        }
94149      }
94150    }
94151    sz = -1;
94152    if( sqlite3_file_control(db,zDb,SQLITE_FCNTL_MMAP_SIZE,&sz)==SQLITE_OK ){
94153#if SQLITE_MAX_MMAP_SIZE==0
94154      sz = 0;
94155#endif
94156      returnSingleInt(pParse, "mmap_size", sz);
94157    }
94158  }else
94159
94160  /*
94161  **   PRAGMA temp_store
94162  **   PRAGMA temp_store = "default"|"memory"|"file"
94163  **
94164  ** Return or set the local value of the temp_store flag.  Changing
94165  ** the local value does not make changes to the disk file and the default
94166  ** value will be restored the next time the database is opened.
94167  **
94168  ** Note that it is possible for the library compile-time options to
94169  ** override this setting
94170  */
94171  if( sqlite3StrICmp(zLeft, "temp_store")==0 ){
94172    if( !zRight ){
94173      returnSingleInt(pParse, "temp_store", db->temp_store);
94174    }else{
94175      changeTempStorage(pParse, zRight);
94176    }
94177  }else
94178
94179  /*
94180  **   PRAGMA temp_store_directory
94181  **   PRAGMA temp_store_directory = ""|"directory_name"
94182  **
94183  ** Return or set the local value of the temp_store_directory flag.  Changing
94184  ** the value sets a specific directory to be used for temporary files.
94185  ** Setting to a null string reverts to the default temporary directory search.
94186  ** If temporary directory is changed, then invalidateTempStorage.
94187  **
94188  */
94189  if( sqlite3StrICmp(zLeft, "temp_store_directory")==0 ){
94190    if( !zRight ){
94191      if( sqlite3_temp_directory ){
94192        sqlite3VdbeSetNumCols(v, 1);
94193        sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
94194            "temp_store_directory", SQLITE_STATIC);
94195        sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
94196        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
94197      }
94198    }else{
94199#ifndef SQLITE_OMIT_WSD
94200      if( zRight[0] ){
94201        int res;
94202        rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
94203        if( rc!=SQLITE_OK || res==0 ){
94204          sqlite3ErrorMsg(pParse, "not a writable directory");
94205          goto pragma_out;
94206        }
94207      }
94208      if( SQLITE_TEMP_STORE==0
94209       || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
94210       || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
94211      ){
94212        invalidateTempStorage(pParse);
94213      }
94214      sqlite3_free(sqlite3_temp_directory);
94215      if( zRight[0] ){
94216        sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
94217      }else{
94218        sqlite3_temp_directory = 0;
94219      }
94220#endif /* SQLITE_OMIT_WSD */
94221    }
94222  }else
94223
94224#if SQLITE_OS_WIN
94225  /*
94226  **   PRAGMA data_store_directory
94227  **   PRAGMA data_store_directory = ""|"directory_name"
94228  **
94229  ** Return or set the local value of the data_store_directory flag.  Changing
94230  ** the value sets a specific directory to be used for database files that
94231  ** were specified with a relative pathname.  Setting to a null string reverts
94232  ** to the default database directory, which for database files specified with
94233  ** a relative path will probably be based on the current directory for the
94234  ** process.  Database file specified with an absolute path are not impacted
94235  ** by this setting, regardless of its value.
94236  **
94237  */
94238  if( sqlite3StrICmp(zLeft, "data_store_directory")==0 ){
94239    if( !zRight ){
94240      if( sqlite3_data_directory ){
94241        sqlite3VdbeSetNumCols(v, 1);
94242        sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
94243            "data_store_directory", SQLITE_STATIC);
94244        sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_data_directory, 0);
94245        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
94246      }
94247    }else{
94248#ifndef SQLITE_OMIT_WSD
94249      if( zRight[0] ){
94250        int res;
94251        rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
94252        if( rc!=SQLITE_OK || res==0 ){
94253          sqlite3ErrorMsg(pParse, "not a writable directory");
94254          goto pragma_out;
94255        }
94256      }
94257      sqlite3_free(sqlite3_data_directory);
94258      if( zRight[0] ){
94259        sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
94260      }else{
94261        sqlite3_data_directory = 0;
94262      }
94263#endif /* SQLITE_OMIT_WSD */
94264    }
94265  }else
94266#endif
94267
94268#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
94269#  if defined(__APPLE__)
94270#    define SQLITE_ENABLE_LOCKING_STYLE 1
94271#  else
94272#    define SQLITE_ENABLE_LOCKING_STYLE 0
94273#  endif
94274#endif
94275#if SQLITE_ENABLE_LOCKING_STYLE
94276  /*
94277   **   PRAGMA [database.]lock_proxy_file
94278   **   PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
94279   **
94280   ** Return or set the value of the lock_proxy_file flag.  Changing
94281   ** the value sets a specific file to be used for database access locks.
94282   **
94283   */
94284  if( sqlite3StrICmp(zLeft, "lock_proxy_file")==0 ){
94285    if( !zRight ){
94286      Pager *pPager = sqlite3BtreePager(pDb->pBt);
94287      char *proxy_file_path = NULL;
94288      sqlite3_file *pFile = sqlite3PagerFile(pPager);
94289      sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
94290                           &proxy_file_path);
94291
94292      if( proxy_file_path ){
94293        sqlite3VdbeSetNumCols(v, 1);
94294        sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
94295                              "lock_proxy_file", SQLITE_STATIC);
94296        sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
94297        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
94298      }
94299    }else{
94300      Pager *pPager = sqlite3BtreePager(pDb->pBt);
94301      sqlite3_file *pFile = sqlite3PagerFile(pPager);
94302      int res;
94303      if( zRight[0] ){
94304        res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
94305                                     zRight);
94306      } else {
94307        res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
94308                                     NULL);
94309      }
94310      if( res!=SQLITE_OK ){
94311        sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
94312        goto pragma_out;
94313      }
94314    }
94315  }else
94316#endif /* SQLITE_ENABLE_LOCKING_STYLE */
94317
94318  /*
94319  **   PRAGMA [database.]synchronous
94320  **   PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
94321  **
94322  ** Return or set the local value of the synchronous flag.  Changing
94323  ** the local value does not make changes to the disk file and the
94324  ** default value will be restored the next time the database is
94325  ** opened.
94326  */
94327  if( sqlite3StrICmp(zLeft,"synchronous")==0 ){
94328    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
94329    if( !zRight ){
94330      returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
94331    }else{
94332      if( !db->autoCommit ){
94333        sqlite3ErrorMsg(pParse,
94334            "Safety level may not be changed inside a transaction");
94335      }else{
94336        pDb->safety_level = getSafetyLevel(zRight,0,1)+1;
94337      }
94338    }
94339  }else
94340#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
94341
94342#ifndef SQLITE_OMIT_FLAG_PRAGMAS
94343  if( flagPragma(pParse, zLeft, zRight) ){
94344    /* The flagPragma() subroutine also generates any necessary code
94345    ** there is nothing more to do here */
94346  }else
94347#endif /* SQLITE_OMIT_FLAG_PRAGMAS */
94348
94349#ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
94350  /*
94351  **   PRAGMA table_info(<table>)
94352  **
94353  ** Return a single row for each column of the named table. The columns of
94354  ** the returned data set are:
94355  **
94356  ** cid:        Column id (numbered from left to right, starting at 0)
94357  ** name:       Column name
94358  ** type:       Column declaration type.
94359  ** notnull:    True if 'NOT NULL' is part of column declaration
94360  ** dflt_value: The default value for the column, if any.
94361  */
94362  if( sqlite3StrICmp(zLeft, "table_info")==0 && zRight ){
94363    Table *pTab;
94364    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
94365    pTab = sqlite3FindTable(db, zRight, zDb);
94366    if( pTab ){
94367      int i, k;
94368      int nHidden = 0;
94369      Column *pCol;
94370      Index *pPk;
94371      for(pPk=pTab->pIndex; pPk && pPk->autoIndex!=2; pPk=pPk->pNext){}
94372      sqlite3VdbeSetNumCols(v, 6);
94373      pParse->nMem = 6;
94374      sqlite3CodeVerifySchema(pParse, iDb);
94375      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
94376      sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
94377      sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
94378      sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
94379      sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
94380      sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
94381      sqlite3ViewGetColumnNames(pParse, pTab);
94382      for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
94383        if( IsHiddenColumn(pCol) ){
94384          nHidden++;
94385          continue;
94386        }
94387        sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
94388        sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
94389        sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
94390           pCol->zType ? pCol->zType : "", 0);
94391        sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
94392        if( pCol->zDflt ){
94393          sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
94394        }else{
94395          sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
94396        }
94397        if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
94398          k = 0;
94399        }else if( pPk==0 ){
94400          k = 1;
94401        }else{
94402          for(k=1; ALWAYS(k<=pTab->nCol) && pPk->aiColumn[k-1]!=i; k++){}
94403        }
94404        sqlite3VdbeAddOp2(v, OP_Integer, k, 6);
94405        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
94406      }
94407    }
94408  }else
94409
94410  if( sqlite3StrICmp(zLeft, "index_info")==0 && zRight ){
94411    Index *pIdx;
94412    Table *pTab;
94413    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
94414    pIdx = sqlite3FindIndex(db, zRight, zDb);
94415    if( pIdx ){
94416      int i;
94417      pTab = pIdx->pTable;
94418      sqlite3VdbeSetNumCols(v, 3);
94419      pParse->nMem = 3;
94420      sqlite3CodeVerifySchema(pParse, iDb);
94421      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
94422      sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
94423      sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
94424      for(i=0; i<pIdx->nColumn; i++){
94425        int cnum = pIdx->aiColumn[i];
94426        sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
94427        sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
94428        assert( pTab->nCol>cnum );
94429        sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
94430        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
94431      }
94432    }
94433  }else
94434
94435  if( sqlite3StrICmp(zLeft, "index_list")==0 && zRight ){
94436    Index *pIdx;
94437    Table *pTab;
94438    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
94439    pTab = sqlite3FindTable(db, zRight, zDb);
94440    if( pTab ){
94441      v = sqlite3GetVdbe(pParse);
94442      pIdx = pTab->pIndex;
94443      if( pIdx ){
94444        int i = 0;
94445        sqlite3VdbeSetNumCols(v, 3);
94446        pParse->nMem = 3;
94447        sqlite3CodeVerifySchema(pParse, iDb);
94448        sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
94449        sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
94450        sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
94451        while(pIdx){
94452          sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
94453          sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
94454          sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
94455          sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
94456          ++i;
94457          pIdx = pIdx->pNext;
94458        }
94459      }
94460    }
94461  }else
94462
94463  if( sqlite3StrICmp(zLeft, "database_list")==0 ){
94464    int i;
94465    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
94466    sqlite3VdbeSetNumCols(v, 3);
94467    pParse->nMem = 3;
94468    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
94469    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
94470    sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
94471    for(i=0; i<db->nDb; i++){
94472      if( db->aDb[i].pBt==0 ) continue;
94473      assert( db->aDb[i].zName!=0 );
94474      sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
94475      sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
94476      sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
94477           sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
94478      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
94479    }
94480  }else
94481
94482  if( sqlite3StrICmp(zLeft, "collation_list")==0 ){
94483    int i = 0;
94484    HashElem *p;
94485    sqlite3VdbeSetNumCols(v, 2);
94486    pParse->nMem = 2;
94487    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
94488    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
94489    for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
94490      CollSeq *pColl = (CollSeq *)sqliteHashData(p);
94491      sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
94492      sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
94493      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
94494    }
94495  }else
94496#endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
94497
94498#ifndef SQLITE_OMIT_FOREIGN_KEY
94499  if( sqlite3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
94500    FKey *pFK;
94501    Table *pTab;
94502    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
94503    pTab = sqlite3FindTable(db, zRight, zDb);
94504    if( pTab ){
94505      v = sqlite3GetVdbe(pParse);
94506      pFK = pTab->pFKey;
94507      if( pFK ){
94508        int i = 0;
94509        sqlite3VdbeSetNumCols(v, 8);
94510        pParse->nMem = 8;
94511        sqlite3CodeVerifySchema(pParse, iDb);
94512        sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
94513        sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
94514        sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
94515        sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
94516        sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
94517        sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
94518        sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
94519        sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
94520        while(pFK){
94521          int j;
94522          for(j=0; j<pFK->nCol; j++){
94523            char *zCol = pFK->aCol[j].zCol;
94524            char *zOnDelete = (char *)actionName(pFK->aAction[0]);
94525            char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
94526            sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
94527            sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
94528            sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
94529            sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
94530                              pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
94531            sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
94532            sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
94533            sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
94534            sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
94535            sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
94536          }
94537          ++i;
94538          pFK = pFK->pNextFrom;
94539        }
94540      }
94541    }
94542  }else
94543#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
94544
94545#ifndef SQLITE_OMIT_FOREIGN_KEY
94546#ifndef SQLITE_OMIT_TRIGGER
94547  if( sqlite3StrICmp(zLeft, "foreign_key_check")==0 ){
94548    FKey *pFK;             /* A foreign key constraint */
94549    Table *pTab;           /* Child table contain "REFERENCES" keyword */
94550    Table *pParent;        /* Parent table that child points to */
94551    Index *pIdx;           /* Index in the parent table */
94552    int i;                 /* Loop counter:  Foreign key number for pTab */
94553    int j;                 /* Loop counter:  Field of the foreign key */
94554    HashElem *k;           /* Loop counter:  Next table in schema */
94555    int x;                 /* result variable */
94556    int regResult;         /* 3 registers to hold a result row */
94557    int regKey;            /* Register to hold key for checking the FK */
94558    int regRow;            /* Registers to hold a row from pTab */
94559    int addrTop;           /* Top of a loop checking foreign keys */
94560    int addrOk;            /* Jump here if the key is OK */
94561    int *aiCols;           /* child to parent column mapping */
94562
94563    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
94564    regResult = pParse->nMem+1;
94565    pParse->nMem += 4;
94566    regKey = ++pParse->nMem;
94567    regRow = ++pParse->nMem;
94568    v = sqlite3GetVdbe(pParse);
94569    sqlite3VdbeSetNumCols(v, 4);
94570    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "table", SQLITE_STATIC);
94571    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "rowid", SQLITE_STATIC);
94572    sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "parent", SQLITE_STATIC);
94573    sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "fkid", SQLITE_STATIC);
94574    sqlite3CodeVerifySchema(pParse, iDb);
94575    k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
94576    while( k ){
94577      if( zRight ){
94578        pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
94579        k = 0;
94580      }else{
94581        pTab = (Table*)sqliteHashData(k);
94582        k = sqliteHashNext(k);
94583      }
94584      if( pTab==0 || pTab->pFKey==0 ) continue;
94585      sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
94586      if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
94587      sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
94588      sqlite3VdbeAddOp4(v, OP_String8, 0, regResult, 0, pTab->zName,
94589                        P4_TRANSIENT);
94590      for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
94591        pParent = sqlite3LocateTable(pParse, 0, pFK->zTo, zDb);
94592        if( pParent==0 ) break;
94593        pIdx = 0;
94594        sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
94595        x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
94596        if( x==0 ){
94597          if( pIdx==0 ){
94598            sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
94599          }else{
94600            KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
94601            sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
94602            sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
94603          }
94604        }else{
94605          k = 0;
94606          break;
94607        }
94608      }
94609      if( pFK ) break;
94610      if( pParse->nTab<i ) pParse->nTab = i;
94611      addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0);
94612      for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
94613        pParent = sqlite3LocateTable(pParse, 0, pFK->zTo, zDb);
94614        assert( pParent!=0 );
94615        pIdx = 0;
94616        aiCols = 0;
94617        x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
94618        assert( x==0 );
94619        addrOk = sqlite3VdbeMakeLabel(v);
94620        if( pIdx==0 ){
94621          int iKey = pFK->aCol[0].iFrom;
94622          assert( iKey>=0 && iKey<pTab->nCol );
94623          if( iKey!=pTab->iPKey ){
94624            sqlite3VdbeAddOp3(v, OP_Column, 0, iKey, regRow);
94625            sqlite3ColumnDefault(v, pTab, iKey, regRow);
94626            sqlite3VdbeAddOp2(v, OP_IsNull, regRow, addrOk);
94627            sqlite3VdbeAddOp2(v, OP_MustBeInt, regRow,
94628               sqlite3VdbeCurrentAddr(v)+3);
94629          }else{
94630            sqlite3VdbeAddOp2(v, OP_Rowid, 0, regRow);
94631          }
94632          sqlite3VdbeAddOp3(v, OP_NotExists, i, 0, regRow);
94633          sqlite3VdbeAddOp2(v, OP_Goto, 0, addrOk);
94634          sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
94635        }else{
94636          for(j=0; j<pFK->nCol; j++){
94637            sqlite3ExprCodeGetColumnOfTable(v, pTab, 0,
94638                            aiCols ? aiCols[j] : pFK->aCol[0].iFrom, regRow+j);
94639            sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk);
94640          }
94641          sqlite3VdbeAddOp3(v, OP_MakeRecord, regRow, pFK->nCol, regKey);
94642          sqlite3VdbeChangeP4(v, -1,
94643                   sqlite3IndexAffinityStr(v,pIdx), P4_TRANSIENT);
94644          sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
94645        }
94646        sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
94647        sqlite3VdbeAddOp4(v, OP_String8, 0, regResult+2, 0,
94648                          pFK->zTo, P4_TRANSIENT);
94649        sqlite3VdbeAddOp2(v, OP_Integer, i-1, regResult+3);
94650        sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
94651        sqlite3VdbeResolveLabel(v, addrOk);
94652        sqlite3DbFree(db, aiCols);
94653      }
94654      sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1);
94655      sqlite3VdbeJumpHere(v, addrTop);
94656    }
94657  }else
94658#endif /* !defined(SQLITE_OMIT_TRIGGER) */
94659#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
94660
94661#ifndef NDEBUG
94662  if( sqlite3StrICmp(zLeft, "parser_trace")==0 ){
94663    if( zRight ){
94664      if( sqlite3GetBoolean(zRight, 0) ){
94665        sqlite3ParserTrace(stderr, "parser: ");
94666      }else{
94667        sqlite3ParserTrace(0, 0);
94668      }
94669    }
94670  }else
94671#endif
94672
94673  /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
94674  ** used will be case sensitive or not depending on the RHS.
94675  */
94676  if( sqlite3StrICmp(zLeft, "case_sensitive_like")==0 ){
94677    if( zRight ){
94678      sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
94679    }
94680  }else
94681
94682#ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
94683# define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
94684#endif
94685
94686#ifndef SQLITE_OMIT_INTEGRITY_CHECK
94687  /* Pragma "quick_check" is an experimental reduced version of
94688  ** integrity_check designed to detect most database corruption
94689  ** without most of the overhead of a full integrity-check.
94690  */
94691  if( sqlite3StrICmp(zLeft, "integrity_check")==0
94692   || sqlite3StrICmp(zLeft, "quick_check")==0
94693  ){
94694    int i, j, addr, mxErr;
94695
94696    /* Code that appears at the end of the integrity check.  If no error
94697    ** messages have been generated, output OK.  Otherwise output the
94698    ** error message
94699    */
94700    static const VdbeOpList endCode[] = {
94701      { OP_AddImm,      1, 0,        0},    /* 0 */
94702      { OP_IfNeg,       1, 0,        0},    /* 1 */
94703      { OP_String8,     0, 3,        0},    /* 2 */
94704      { OP_ResultRow,   3, 1,        0},
94705    };
94706
94707    int isQuick = (sqlite3Tolower(zLeft[0])=='q');
94708
94709    /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
94710    ** then iDb is set to the index of the database identified by <db>.
94711    ** In this case, the integrity of database iDb only is verified by
94712    ** the VDBE created below.
94713    **
94714    ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
94715    ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
94716    ** to -1 here, to indicate that the VDBE should verify the integrity
94717    ** of all attached databases.  */
94718    assert( iDb>=0 );
94719    assert( iDb==0 || pId2->z );
94720    if( pId2->z==0 ) iDb = -1;
94721
94722    /* Initialize the VDBE program */
94723    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
94724    pParse->nMem = 6;
94725    sqlite3VdbeSetNumCols(v, 1);
94726    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
94727
94728    /* Set the maximum error count */
94729    mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
94730    if( zRight ){
94731      sqlite3GetInt32(zRight, &mxErr);
94732      if( mxErr<=0 ){
94733        mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
94734      }
94735    }
94736    sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
94737
94738    /* Do an integrity check on each database file */
94739    for(i=0; i<db->nDb; i++){
94740      HashElem *x;
94741      Hash *pTbls;
94742      int cnt = 0;
94743
94744      if( OMIT_TEMPDB && i==1 ) continue;
94745      if( iDb>=0 && i!=iDb ) continue;
94746
94747      sqlite3CodeVerifySchema(pParse, i);
94748      addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
94749      sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
94750      sqlite3VdbeJumpHere(v, addr);
94751
94752      /* Do an integrity check of the B-Tree
94753      **
94754      ** Begin by filling registers 2, 3, ... with the root pages numbers
94755      ** for all tables and indices in the database.
94756      */
94757      assert( sqlite3SchemaMutexHeld(db, i, 0) );
94758      pTbls = &db->aDb[i].pSchema->tblHash;
94759      for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
94760        Table *pTab = sqliteHashData(x);
94761        Index *pIdx;
94762        sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
94763        cnt++;
94764        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
94765          sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
94766          cnt++;
94767        }
94768      }
94769
94770      /* Make sure sufficient number of registers have been allocated */
94771      if( pParse->nMem < cnt+4 ){
94772        pParse->nMem = cnt+4;
94773      }
94774
94775      /* Do the b-tree integrity checks */
94776      sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
94777      sqlite3VdbeChangeP5(v, (u8)i);
94778      addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
94779      sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
94780         sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
94781         P4_DYNAMIC);
94782      sqlite3VdbeAddOp2(v, OP_Move, 2, 4);
94783      sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
94784      sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
94785      sqlite3VdbeJumpHere(v, addr);
94786
94787      /* Make sure all the indices are constructed correctly.
94788      */
94789      for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
94790        Table *pTab = sqliteHashData(x);
94791        Index *pIdx;
94792        int loopTop;
94793
94794        if( pTab->pIndex==0 ) continue;
94795        addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
94796        sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
94797        sqlite3VdbeJumpHere(v, addr);
94798        sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
94799        sqlite3VdbeAddOp2(v, OP_Integer, 0, 2);  /* reg(2) will count entries */
94800        loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0);
94801        sqlite3VdbeAddOp2(v, OP_AddImm, 2, 1);   /* increment entry count */
94802        for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
94803          int jmp2;
94804          int r1;
94805          static const VdbeOpList idxErr[] = {
94806            { OP_AddImm,      1, -1,  0},
94807            { OP_String8,     0,  3,  0},    /* 1 */
94808            { OP_Rowid,       1,  4,  0},
94809            { OP_String8,     0,  5,  0},    /* 3 */
94810            { OP_String8,     0,  6,  0},    /* 4 */
94811            { OP_Concat,      4,  3,  3},
94812            { OP_Concat,      5,  3,  3},
94813            { OP_Concat,      6,  3,  3},
94814            { OP_ResultRow,   3,  1,  0},
94815            { OP_IfPos,       1,  0,  0},    /* 9 */
94816            { OP_Halt,        0,  0,  0},
94817          };
94818          r1 = sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 0);
94819          jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, j+2, 0, r1, pIdx->nColumn+1);
94820          addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
94821          sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
94822          sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
94823          sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_TRANSIENT);
94824          sqlite3VdbeJumpHere(v, addr+9);
94825          sqlite3VdbeJumpHere(v, jmp2);
94826        }
94827        sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop+1);
94828        sqlite3VdbeJumpHere(v, loopTop);
94829        for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
94830          static const VdbeOpList cntIdx[] = {
94831             { OP_Integer,      0,  3,  0},
94832             { OP_Rewind,       0,  0,  0},  /* 1 */
94833             { OP_AddImm,       3,  1,  0},
94834             { OP_Next,         0,  0,  0},  /* 3 */
94835             { OP_Eq,           2,  0,  3},  /* 4 */
94836             { OP_AddImm,       1, -1,  0},
94837             { OP_String8,      0,  2,  0},  /* 6 */
94838             { OP_String8,      0,  3,  0},  /* 7 */
94839             { OP_Concat,       3,  2,  2},
94840             { OP_ResultRow,    2,  1,  0},
94841          };
94842          addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);
94843          sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
94844          sqlite3VdbeJumpHere(v, addr);
94845          addr = sqlite3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
94846          sqlite3VdbeChangeP1(v, addr+1, j+2);
94847          sqlite3VdbeChangeP2(v, addr+1, addr+4);
94848          sqlite3VdbeChangeP1(v, addr+3, j+2);
94849          sqlite3VdbeChangeP2(v, addr+3, addr+2);
94850          sqlite3VdbeJumpHere(v, addr+4);
94851          sqlite3VdbeChangeP4(v, addr+6,
94852                     "wrong # of entries in index ", P4_STATIC);
94853          sqlite3VdbeChangeP4(v, addr+7, pIdx->zName, P4_TRANSIENT);
94854        }
94855      }
94856    }
94857    addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
94858    sqlite3VdbeChangeP2(v, addr, -mxErr);
94859    sqlite3VdbeJumpHere(v, addr+1);
94860    sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
94861  }else
94862#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
94863
94864#ifndef SQLITE_OMIT_UTF16
94865  /*
94866  **   PRAGMA encoding
94867  **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
94868  **
94869  ** In its first form, this pragma returns the encoding of the main
94870  ** database. If the database is not initialized, it is initialized now.
94871  **
94872  ** The second form of this pragma is a no-op if the main database file
94873  ** has not already been initialized. In this case it sets the default
94874  ** encoding that will be used for the main database file if a new file
94875  ** is created. If an existing main database file is opened, then the
94876  ** default text encoding for the existing database is used.
94877  **
94878  ** In all cases new databases created using the ATTACH command are
94879  ** created to use the same default text encoding as the main database. If
94880  ** the main database has not been initialized and/or created when ATTACH
94881  ** is executed, this is done before the ATTACH operation.
94882  **
94883  ** In the second form this pragma sets the text encoding to be used in
94884  ** new database files created using this database handle. It is only
94885  ** useful if invoked immediately after the main database i
94886  */
94887  if( sqlite3StrICmp(zLeft, "encoding")==0 ){
94888    static const struct EncName {
94889      char *zName;
94890      u8 enc;
94891    } encnames[] = {
94892      { "UTF8",     SQLITE_UTF8        },
94893      { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
94894      { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
94895      { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
94896      { "UTF16le",  SQLITE_UTF16LE     },
94897      { "UTF16be",  SQLITE_UTF16BE     },
94898      { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
94899      { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
94900      { 0, 0 }
94901    };
94902    const struct EncName *pEnc;
94903    if( !zRight ){    /* "PRAGMA encoding" */
94904      if( sqlite3ReadSchema(pParse) ) goto pragma_out;
94905      sqlite3VdbeSetNumCols(v, 1);
94906      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
94907      sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
94908      assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
94909      assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
94910      assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
94911      sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
94912      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
94913    }else{                        /* "PRAGMA encoding = XXX" */
94914      /* Only change the value of sqlite.enc if the database handle is not
94915      ** initialized. If the main database exists, the new sqlite.enc value
94916      ** will be overwritten when the schema is next loaded. If it does not
94917      ** already exists, it will be created to use the new encoding value.
94918      */
94919      if(
94920        !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
94921        DbHasProperty(db, 0, DB_Empty)
94922      ){
94923        for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
94924          if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
94925            ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
94926            break;
94927          }
94928        }
94929        if( !pEnc->zName ){
94930          sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
94931        }
94932      }
94933    }
94934  }else
94935#endif /* SQLITE_OMIT_UTF16 */
94936
94937#ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
94938  /*
94939  **   PRAGMA [database.]schema_version
94940  **   PRAGMA [database.]schema_version = <integer>
94941  **
94942  **   PRAGMA [database.]user_version
94943  **   PRAGMA [database.]user_version = <integer>
94944  **
94945  **   PRAGMA [database.]freelist_count = <integer>
94946  **
94947  **   PRAGMA [database.]application_id
94948  **   PRAGMA [database.]application_id = <integer>
94949  **
94950  ** The pragma's schema_version and user_version are used to set or get
94951  ** the value of the schema-version and user-version, respectively. Both
94952  ** the schema-version and the user-version are 32-bit signed integers
94953  ** stored in the database header.
94954  **
94955  ** The schema-cookie is usually only manipulated internally by SQLite. It
94956  ** is incremented by SQLite whenever the database schema is modified (by
94957  ** creating or dropping a table or index). The schema version is used by
94958  ** SQLite each time a query is executed to ensure that the internal cache
94959  ** of the schema used when compiling the SQL query matches the schema of
94960  ** the database against which the compiled query is actually executed.
94961  ** Subverting this mechanism by using "PRAGMA schema_version" to modify
94962  ** the schema-version is potentially dangerous and may lead to program
94963  ** crashes or database corruption. Use with caution!
94964  **
94965  ** The user-version is not used internally by SQLite. It may be used by
94966  ** applications for any purpose.
94967  */
94968  if( sqlite3StrICmp(zLeft, "schema_version")==0
94969   || sqlite3StrICmp(zLeft, "user_version")==0
94970   || sqlite3StrICmp(zLeft, "freelist_count")==0
94971   || sqlite3StrICmp(zLeft, "application_id")==0
94972  ){
94973    int iCookie;   /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
94974    sqlite3VdbeUsesBtree(v, iDb);
94975    switch( zLeft[0] ){
94976      case 'a': case 'A':
94977        iCookie = BTREE_APPLICATION_ID;
94978        break;
94979      case 'f': case 'F':
94980        iCookie = BTREE_FREE_PAGE_COUNT;
94981        break;
94982      case 's': case 'S':
94983        iCookie = BTREE_SCHEMA_VERSION;
94984        break;
94985      default:
94986        iCookie = BTREE_USER_VERSION;
94987        break;
94988    }
94989
94990    if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
94991      /* Write the specified cookie value */
94992      static const VdbeOpList setCookie[] = {
94993        { OP_Transaction,    0,  1,  0},    /* 0 */
94994        { OP_Integer,        0,  1,  0},    /* 1 */
94995        { OP_SetCookie,      0,  0,  1},    /* 2 */
94996      };
94997      int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
94998      sqlite3VdbeChangeP1(v, addr, iDb);
94999      sqlite3VdbeChangeP1(v, addr+1, sqlite3Atoi(zRight));
95000      sqlite3VdbeChangeP1(v, addr+2, iDb);
95001      sqlite3VdbeChangeP2(v, addr+2, iCookie);
95002    }else{
95003      /* Read the specified cookie value */
95004      static const VdbeOpList readCookie[] = {
95005        { OP_Transaction,     0,  0,  0},    /* 0 */
95006        { OP_ReadCookie,      0,  1,  0},    /* 1 */
95007        { OP_ResultRow,       1,  1,  0}
95008      };
95009      int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
95010      sqlite3VdbeChangeP1(v, addr, iDb);
95011      sqlite3VdbeChangeP1(v, addr+1, iDb);
95012      sqlite3VdbeChangeP3(v, addr+1, iCookie);
95013      sqlite3VdbeSetNumCols(v, 1);
95014      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
95015    }
95016  }else
95017#endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
95018
95019#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
95020  /*
95021  **   PRAGMA compile_options
95022  **
95023  ** Return the names of all compile-time options used in this build,
95024  ** one option per row.
95025  */
95026  if( sqlite3StrICmp(zLeft, "compile_options")==0 ){
95027    int i = 0;
95028    const char *zOpt;
95029    sqlite3VdbeSetNumCols(v, 1);
95030    pParse->nMem = 1;
95031    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC);
95032    while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
95033      sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
95034      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
95035    }
95036  }else
95037#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
95038
95039#ifndef SQLITE_OMIT_WAL
95040  /*
95041  **   PRAGMA [database.]wal_checkpoint = passive|full|restart
95042  **
95043  ** Checkpoint the database.
95044  */
95045  if( sqlite3StrICmp(zLeft, "wal_checkpoint")==0 ){
95046    int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
95047    int eMode = SQLITE_CHECKPOINT_PASSIVE;
95048    if( zRight ){
95049      if( sqlite3StrICmp(zRight, "full")==0 ){
95050        eMode = SQLITE_CHECKPOINT_FULL;
95051      }else if( sqlite3StrICmp(zRight, "restart")==0 ){
95052        eMode = SQLITE_CHECKPOINT_RESTART;
95053      }
95054    }
95055    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
95056    sqlite3VdbeSetNumCols(v, 3);
95057    pParse->nMem = 3;
95058    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "busy", SQLITE_STATIC);
95059    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "log", SQLITE_STATIC);
95060    sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "checkpointed", SQLITE_STATIC);
95061
95062    sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
95063    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
95064  }else
95065
95066  /*
95067  **   PRAGMA wal_autocheckpoint
95068  **   PRAGMA wal_autocheckpoint = N
95069  **
95070  ** Configure a database connection to automatically checkpoint a database
95071  ** after accumulating N frames in the log. Or query for the current value
95072  ** of N.
95073  */
95074  if( sqlite3StrICmp(zLeft, "wal_autocheckpoint")==0 ){
95075    if( zRight ){
95076      sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
95077    }
95078    returnSingleInt(pParse, "wal_autocheckpoint",
95079       db->xWalCallback==sqlite3WalDefaultHook ?
95080           SQLITE_PTR_TO_INT(db->pWalArg) : 0);
95081  }else
95082#endif
95083
95084  /*
95085  **  PRAGMA shrink_memory
95086  **
95087  ** This pragma attempts to free as much memory as possible from the
95088  ** current database connection.
95089  */
95090  if( sqlite3StrICmp(zLeft, "shrink_memory")==0 ){
95091    sqlite3_db_release_memory(db);
95092  }else
95093
95094  /*
95095  **   PRAGMA busy_timeout
95096  **   PRAGMA busy_timeout = N
95097  **
95098  ** Call sqlite3_busy_timeout(db, N).  Return the current timeout value
95099  ** if one is set.  If no busy handler or a different busy handler is set
95100  ** then 0 is returned.  Setting the busy_timeout to 0 or negative
95101  ** disables the timeout.
95102  */
95103  if( sqlite3StrICmp(zLeft, "busy_timeout")==0 ){
95104    if( zRight ){
95105      sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
95106    }
95107    returnSingleInt(pParse, "timeout",  db->busyTimeout);
95108  }else
95109
95110#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
95111  /*
95112  ** Report the current state of file logs for all databases
95113  */
95114  if( sqlite3StrICmp(zLeft, "lock_status")==0 ){
95115    static const char *const azLockName[] = {
95116      "unlocked", "shared", "reserved", "pending", "exclusive"
95117    };
95118    int i;
95119    sqlite3VdbeSetNumCols(v, 2);
95120    pParse->nMem = 2;
95121    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
95122    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
95123    for(i=0; i<db->nDb; i++){
95124      Btree *pBt;
95125      const char *zState = "unknown";
95126      int j;
95127      if( db->aDb[i].zName==0 ) continue;
95128      sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
95129      pBt = db->aDb[i].pBt;
95130      if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
95131        zState = "closed";
95132      }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0,
95133                                     SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
95134         zState = azLockName[j];
95135      }
95136      sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
95137      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
95138    }
95139
95140  }else
95141#endif
95142
95143#ifdef SQLITE_HAS_CODEC
95144  if( sqlite3StrICmp(zLeft, "key")==0 && zRight ){
95145    sqlite3_key(db, zRight, sqlite3Strlen30(zRight));
95146  }else
95147  if( sqlite3StrICmp(zLeft, "rekey")==0 && zRight ){
95148    sqlite3_rekey(db, zRight, sqlite3Strlen30(zRight));
95149  }else
95150  if( zRight && (sqlite3StrICmp(zLeft, "hexkey")==0 ||
95151                 sqlite3StrICmp(zLeft, "hexrekey")==0) ){
95152    int i, h1, h2;
95153    char zKey[40];
95154    for(i=0; (h1 = zRight[i])!=0 && (h2 = zRight[i+1])!=0; i+=2){
95155      h1 += 9*(1&(h1>>6));
95156      h2 += 9*(1&(h2>>6));
95157      zKey[i/2] = (h2 & 0x0f) | ((h1 & 0xf)<<4);
95158    }
95159    if( (zLeft[3] & 0xf)==0xb ){
95160      sqlite3_key(db, zKey, i/2);
95161    }else{
95162      sqlite3_rekey(db, zKey, i/2);
95163    }
95164  }else
95165#endif
95166#if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
95167  if( sqlite3StrICmp(zLeft, "activate_extensions")==0 && zRight ){
95168#ifdef SQLITE_HAS_CODEC
95169    if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
95170      sqlite3_activate_see(&zRight[4]);
95171    }
95172#endif
95173#ifdef SQLITE_ENABLE_CEROD
95174    if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
95175      sqlite3_activate_cerod(&zRight[6]);
95176    }
95177#endif
95178  }else
95179#endif
95180
95181
95182  {/* Empty ELSE clause */}
95183
95184  /*
95185  ** Reset the safety level, in case the fullfsync flag or synchronous
95186  ** setting changed.
95187  */
95188#ifndef SQLITE_OMIT_PAGER_PRAGMAS
95189  if( db->autoCommit ){
95190    sqlite3BtreeSetSafetyLevel(pDb->pBt, pDb->safety_level,
95191               (db->flags&SQLITE_FullFSync)!=0,
95192               (db->flags&SQLITE_CkptFullFSync)!=0);
95193  }
95194#endif
95195pragma_out:
95196  sqlite3DbFree(db, zLeft);
95197  sqlite3DbFree(db, zRight);
95198}
95199
95200#endif /* SQLITE_OMIT_PRAGMA */
95201
95202/************** End of pragma.c **********************************************/
95203/************** Begin file prepare.c *****************************************/
95204/*
95205** 2005 May 25
95206**
95207** The author disclaims copyright to this source code.  In place of
95208** a legal notice, here is a blessing:
95209**
95210**    May you do good and not evil.
95211**    May you find forgiveness for yourself and forgive others.
95212**    May you share freely, never taking more than you give.
95213**
95214*************************************************************************
95215** This file contains the implementation of the sqlite3_prepare()
95216** interface, and routines that contribute to loading the database schema
95217** from disk.
95218*/
95219
95220/*
95221** Fill the InitData structure with an error message that indicates
95222** that the database is corrupt.
95223*/
95224static void corruptSchema(
95225  InitData *pData,     /* Initialization context */
95226  const char *zObj,    /* Object being parsed at the point of error */
95227  const char *zExtra   /* Error information */
95228){
95229  sqlite3 *db = pData->db;
95230  if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
95231    if( zObj==0 ) zObj = "?";
95232    sqlite3SetString(pData->pzErrMsg, db,
95233      "malformed database schema (%s)", zObj);
95234    if( zExtra ){
95235      *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg,
95236                                 "%s - %s", *pData->pzErrMsg, zExtra);
95237    }
95238  }
95239  pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT;
95240}
95241
95242/*
95243** This is the callback routine for the code that initializes the
95244** database.  See sqlite3Init() below for additional information.
95245** This routine is also called from the OP_ParseSchema opcode of the VDBE.
95246**
95247** Each callback contains the following information:
95248**
95249**     argv[0] = name of thing being created
95250**     argv[1] = root page number for table or index. 0 for trigger or view.
95251**     argv[2] = SQL text for the CREATE statement.
95252**
95253*/
95254SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
95255  InitData *pData = (InitData*)pInit;
95256  sqlite3 *db = pData->db;
95257  int iDb = pData->iDb;
95258
95259  assert( argc==3 );
95260  UNUSED_PARAMETER2(NotUsed, argc);
95261  assert( sqlite3_mutex_held(db->mutex) );
95262  DbClearProperty(db, iDb, DB_Empty);
95263  if( db->mallocFailed ){
95264    corruptSchema(pData, argv[0], 0);
95265    return 1;
95266  }
95267
95268  assert( iDb>=0 && iDb<db->nDb );
95269  if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
95270  if( argv[1]==0 ){
95271    corruptSchema(pData, argv[0], 0);
95272  }else if( argv[2] && argv[2][0] ){
95273    /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
95274    ** But because db->init.busy is set to 1, no VDBE code is generated
95275    ** or executed.  All the parser does is build the internal data
95276    ** structures that describe the table, index, or view.
95277    */
95278    int rc;
95279    sqlite3_stmt *pStmt;
95280    TESTONLY(int rcp);            /* Return code from sqlite3_prepare() */
95281
95282    assert( db->init.busy );
95283    db->init.iDb = iDb;
95284    db->init.newTnum = sqlite3Atoi(argv[1]);
95285    db->init.orphanTrigger = 0;
95286    TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
95287    rc = db->errCode;
95288    assert( (rc&0xFF)==(rcp&0xFF) );
95289    db->init.iDb = 0;
95290    if( SQLITE_OK!=rc ){
95291      if( db->init.orphanTrigger ){
95292        assert( iDb==1 );
95293      }else{
95294        pData->rc = rc;
95295        if( rc==SQLITE_NOMEM ){
95296          db->mallocFailed = 1;
95297        }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
95298          corruptSchema(pData, argv[0], sqlite3_errmsg(db));
95299        }
95300      }
95301    }
95302    sqlite3_finalize(pStmt);
95303  }else if( argv[0]==0 ){
95304    corruptSchema(pData, 0, 0);
95305  }else{
95306    /* If the SQL column is blank it means this is an index that
95307    ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
95308    ** constraint for a CREATE TABLE.  The index should have already
95309    ** been created when we processed the CREATE TABLE.  All we have
95310    ** to do here is record the root page number for that index.
95311    */
95312    Index *pIndex;
95313    pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
95314    if( pIndex==0 ){
95315      /* This can occur if there exists an index on a TEMP table which
95316      ** has the same name as another index on a permanent index.  Since
95317      ** the permanent table is hidden by the TEMP table, we can also
95318      ** safely ignore the index on the permanent table.
95319      */
95320      /* Do Nothing */;
95321    }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
95322      corruptSchema(pData, argv[0], "invalid rootpage");
95323    }
95324  }
95325  return 0;
95326}
95327
95328/*
95329** Attempt to read the database schema and initialize internal
95330** data structures for a single database file.  The index of the
95331** database file is given by iDb.  iDb==0 is used for the main
95332** database.  iDb==1 should never be used.  iDb>=2 is used for
95333** auxiliary databases.  Return one of the SQLITE_ error codes to
95334** indicate success or failure.
95335*/
95336static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
95337  int rc;
95338  int i;
95339#ifndef SQLITE_OMIT_DEPRECATED
95340  int size;
95341#endif
95342  Table *pTab;
95343  Db *pDb;
95344  char const *azArg[4];
95345  int meta[5];
95346  InitData initData;
95347  char const *zMasterSchema;
95348  char const *zMasterName;
95349  int openedTransaction = 0;
95350
95351  /*
95352  ** The master database table has a structure like this
95353  */
95354  static const char master_schema[] =
95355     "CREATE TABLE sqlite_master(\n"
95356     "  type text,\n"
95357     "  name text,\n"
95358     "  tbl_name text,\n"
95359     "  rootpage integer,\n"
95360     "  sql text\n"
95361     ")"
95362  ;
95363#ifndef SQLITE_OMIT_TEMPDB
95364  static const char temp_master_schema[] =
95365     "CREATE TEMP TABLE sqlite_temp_master(\n"
95366     "  type text,\n"
95367     "  name text,\n"
95368     "  tbl_name text,\n"
95369     "  rootpage integer,\n"
95370     "  sql text\n"
95371     ")"
95372  ;
95373#else
95374  #define temp_master_schema 0
95375#endif
95376
95377  assert( iDb>=0 && iDb<db->nDb );
95378  assert( db->aDb[iDb].pSchema );
95379  assert( sqlite3_mutex_held(db->mutex) );
95380  assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
95381
95382  /* zMasterSchema and zInitScript are set to point at the master schema
95383  ** and initialisation script appropriate for the database being
95384  ** initialized. zMasterName is the name of the master table.
95385  */
95386  if( !OMIT_TEMPDB && iDb==1 ){
95387    zMasterSchema = temp_master_schema;
95388  }else{
95389    zMasterSchema = master_schema;
95390  }
95391  zMasterName = SCHEMA_TABLE(iDb);
95392
95393  /* Construct the schema tables.  */
95394  azArg[0] = zMasterName;
95395  azArg[1] = "1";
95396  azArg[2] = zMasterSchema;
95397  azArg[3] = 0;
95398  initData.db = db;
95399  initData.iDb = iDb;
95400  initData.rc = SQLITE_OK;
95401  initData.pzErrMsg = pzErrMsg;
95402  sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
95403  if( initData.rc ){
95404    rc = initData.rc;
95405    goto error_out;
95406  }
95407  pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
95408  if( ALWAYS(pTab) ){
95409    pTab->tabFlags |= TF_Readonly;
95410  }
95411
95412  /* Create a cursor to hold the database open
95413  */
95414  pDb = &db->aDb[iDb];
95415  if( pDb->pBt==0 ){
95416    if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
95417      DbSetProperty(db, 1, DB_SchemaLoaded);
95418    }
95419    return SQLITE_OK;
95420  }
95421
95422  /* If there is not already a read-only (or read-write) transaction opened
95423  ** on the b-tree database, open one now. If a transaction is opened, it
95424  ** will be closed before this function returns.  */
95425  sqlite3BtreeEnter(pDb->pBt);
95426  if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
95427    rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
95428    if( rc!=SQLITE_OK ){
95429      sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
95430      goto initone_error_out;
95431    }
95432    openedTransaction = 1;
95433  }
95434
95435  /* Get the database meta information.
95436  **
95437  ** Meta values are as follows:
95438  **    meta[0]   Schema cookie.  Changes with each schema change.
95439  **    meta[1]   File format of schema layer.
95440  **    meta[2]   Size of the page cache.
95441  **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
95442  **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
95443  **    meta[5]   User version
95444  **    meta[6]   Incremental vacuum mode
95445  **    meta[7]   unused
95446  **    meta[8]   unused
95447  **    meta[9]   unused
95448  **
95449  ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
95450  ** the possible values of meta[4].
95451  */
95452  for(i=0; i<ArraySize(meta); i++){
95453    sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
95454  }
95455  pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
95456
95457  /* If opening a non-empty database, check the text encoding. For the
95458  ** main database, set sqlite3.enc to the encoding of the main database.
95459  ** For an attached db, it is an error if the encoding is not the same
95460  ** as sqlite3.enc.
95461  */
95462  if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
95463    if( iDb==0 ){
95464#ifndef SQLITE_OMIT_UTF16
95465      u8 encoding;
95466      /* If opening the main database, set ENC(db). */
95467      encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
95468      if( encoding==0 ) encoding = SQLITE_UTF8;
95469      ENC(db) = encoding;
95470#else
95471      ENC(db) = SQLITE_UTF8;
95472#endif
95473    }else{
95474      /* If opening an attached database, the encoding much match ENC(db) */
95475      if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
95476        sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
95477            " text encoding as main database");
95478        rc = SQLITE_ERROR;
95479        goto initone_error_out;
95480      }
95481    }
95482  }else{
95483    DbSetProperty(db, iDb, DB_Empty);
95484  }
95485  pDb->pSchema->enc = ENC(db);
95486
95487  if( pDb->pSchema->cache_size==0 ){
95488#ifndef SQLITE_OMIT_DEPRECATED
95489    size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
95490    if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
95491    pDb->pSchema->cache_size = size;
95492#else
95493    pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
95494#endif
95495    sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
95496  }
95497
95498  /*
95499  ** file_format==1    Version 3.0.0.
95500  ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
95501  ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
95502  ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
95503  */
95504  pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
95505  if( pDb->pSchema->file_format==0 ){
95506    pDb->pSchema->file_format = 1;
95507  }
95508  if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
95509    sqlite3SetString(pzErrMsg, db, "unsupported file format");
95510    rc = SQLITE_ERROR;
95511    goto initone_error_out;
95512  }
95513
95514  /* Ticket #2804:  When we open a database in the newer file format,
95515  ** clear the legacy_file_format pragma flag so that a VACUUM will
95516  ** not downgrade the database and thus invalidate any descending
95517  ** indices that the user might have created.
95518  */
95519  if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
95520    db->flags &= ~SQLITE_LegacyFileFmt;
95521  }
95522
95523  /* Read the schema information out of the schema tables
95524  */
95525  assert( db->init.busy );
95526  {
95527    char *zSql;
95528    zSql = sqlite3MPrintf(db,
95529        "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
95530        db->aDb[iDb].zName, zMasterName);
95531#ifndef SQLITE_OMIT_AUTHORIZATION
95532    {
95533      int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
95534      xAuth = db->xAuth;
95535      db->xAuth = 0;
95536#endif
95537      rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
95538#ifndef SQLITE_OMIT_AUTHORIZATION
95539      db->xAuth = xAuth;
95540    }
95541#endif
95542    if( rc==SQLITE_OK ) rc = initData.rc;
95543    sqlite3DbFree(db, zSql);
95544#ifndef SQLITE_OMIT_ANALYZE
95545    if( rc==SQLITE_OK ){
95546      sqlite3AnalysisLoad(db, iDb);
95547    }
95548#endif
95549  }
95550  if( db->mallocFailed ){
95551    rc = SQLITE_NOMEM;
95552    sqlite3ResetAllSchemasOfConnection(db);
95553  }
95554  if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
95555    /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
95556    ** the schema loaded, even if errors occurred. In this situation the
95557    ** current sqlite3_prepare() operation will fail, but the following one
95558    ** will attempt to compile the supplied statement against whatever subset
95559    ** of the schema was loaded before the error occurred. The primary
95560    ** purpose of this is to allow access to the sqlite_master table
95561    ** even when its contents have been corrupted.
95562    */
95563    DbSetProperty(db, iDb, DB_SchemaLoaded);
95564    rc = SQLITE_OK;
95565  }
95566
95567  /* Jump here for an error that occurs after successfully allocating
95568  ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
95569  ** before that point, jump to error_out.
95570  */
95571initone_error_out:
95572  if( openedTransaction ){
95573    sqlite3BtreeCommit(pDb->pBt);
95574  }
95575  sqlite3BtreeLeave(pDb->pBt);
95576
95577error_out:
95578  if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
95579    db->mallocFailed = 1;
95580  }
95581  return rc;
95582}
95583
95584/*
95585** Initialize all database files - the main database file, the file
95586** used to store temporary tables, and any additional database files
95587** created using ATTACH statements.  Return a success code.  If an
95588** error occurs, write an error message into *pzErrMsg.
95589**
95590** After a database is initialized, the DB_SchemaLoaded bit is set
95591** bit is set in the flags field of the Db structure. If the database
95592** file was of zero-length, then the DB_Empty flag is also set.
95593*/
95594SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
95595  int i, rc;
95596  int commit_internal = !(db->flags&SQLITE_InternChanges);
95597
95598  assert( sqlite3_mutex_held(db->mutex) );
95599  rc = SQLITE_OK;
95600  db->init.busy = 1;
95601  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
95602    if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
95603    rc = sqlite3InitOne(db, i, pzErrMsg);
95604    if( rc ){
95605      sqlite3ResetOneSchema(db, i);
95606    }
95607  }
95608
95609  /* Once all the other databases have been initialized, load the schema
95610  ** for the TEMP database. This is loaded last, as the TEMP database
95611  ** schema may contain references to objects in other databases.
95612  */
95613#ifndef SQLITE_OMIT_TEMPDB
95614  if( rc==SQLITE_OK && ALWAYS(db->nDb>1)
95615                    && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
95616    rc = sqlite3InitOne(db, 1, pzErrMsg);
95617    if( rc ){
95618      sqlite3ResetOneSchema(db, 1);
95619    }
95620  }
95621#endif
95622
95623  db->init.busy = 0;
95624  if( rc==SQLITE_OK && commit_internal ){
95625    sqlite3CommitInternalChanges(db);
95626  }
95627
95628  return rc;
95629}
95630
95631/*
95632** This routine is a no-op if the database schema is already initialized.
95633** Otherwise, the schema is loaded. An error code is returned.
95634*/
95635SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
95636  int rc = SQLITE_OK;
95637  sqlite3 *db = pParse->db;
95638  assert( sqlite3_mutex_held(db->mutex) );
95639  if( !db->init.busy ){
95640    rc = sqlite3Init(db, &pParse->zErrMsg);
95641  }
95642  if( rc!=SQLITE_OK ){
95643    pParse->rc = rc;
95644    pParse->nErr++;
95645  }
95646  return rc;
95647}
95648
95649
95650/*
95651** Check schema cookies in all databases.  If any cookie is out
95652** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies
95653** make no changes to pParse->rc.
95654*/
95655static void schemaIsValid(Parse *pParse){
95656  sqlite3 *db = pParse->db;
95657  int iDb;
95658  int rc;
95659  int cookie;
95660
95661  assert( pParse->checkSchema );
95662  assert( sqlite3_mutex_held(db->mutex) );
95663  for(iDb=0; iDb<db->nDb; iDb++){
95664    int openedTransaction = 0;         /* True if a transaction is opened */
95665    Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
95666    if( pBt==0 ) continue;
95667
95668    /* If there is not already a read-only (or read-write) transaction opened
95669    ** on the b-tree database, open one now. If a transaction is opened, it
95670    ** will be closed immediately after reading the meta-value. */
95671    if( !sqlite3BtreeIsInReadTrans(pBt) ){
95672      rc = sqlite3BtreeBeginTrans(pBt, 0);
95673      if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
95674        db->mallocFailed = 1;
95675      }
95676      if( rc!=SQLITE_OK ) return;
95677      openedTransaction = 1;
95678    }
95679
95680    /* Read the schema cookie from the database. If it does not match the
95681    ** value stored as part of the in-memory schema representation,
95682    ** set Parse.rc to SQLITE_SCHEMA. */
95683    sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
95684    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
95685    if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
95686      sqlite3ResetOneSchema(db, iDb);
95687      pParse->rc = SQLITE_SCHEMA;
95688    }
95689
95690    /* Close the transaction, if one was opened. */
95691    if( openedTransaction ){
95692      sqlite3BtreeCommit(pBt);
95693    }
95694  }
95695}
95696
95697/*
95698** Convert a schema pointer into the iDb index that indicates
95699** which database file in db->aDb[] the schema refers to.
95700**
95701** If the same database is attached more than once, the first
95702** attached database is returned.
95703*/
95704SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
95705  int i = -1000000;
95706
95707  /* If pSchema is NULL, then return -1000000. This happens when code in
95708  ** expr.c is trying to resolve a reference to a transient table (i.e. one
95709  ** created by a sub-select). In this case the return value of this
95710  ** function should never be used.
95711  **
95712  ** We return -1000000 instead of the more usual -1 simply because using
95713  ** -1000000 as the incorrect index into db->aDb[] is much
95714  ** more likely to cause a segfault than -1 (of course there are assert()
95715  ** statements too, but it never hurts to play the odds).
95716  */
95717  assert( sqlite3_mutex_held(db->mutex) );
95718  if( pSchema ){
95719    for(i=0; ALWAYS(i<db->nDb); i++){
95720      if( db->aDb[i].pSchema==pSchema ){
95721        break;
95722      }
95723    }
95724    assert( i>=0 && i<db->nDb );
95725  }
95726  return i;
95727}
95728
95729/*
95730** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
95731*/
95732static int sqlite3Prepare(
95733  sqlite3 *db,              /* Database handle. */
95734  const char *zSql,         /* UTF-8 encoded SQL statement. */
95735  int nBytes,               /* Length of zSql in bytes. */
95736  int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
95737  Vdbe *pReprepare,         /* VM being reprepared */
95738  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
95739  const char **pzTail       /* OUT: End of parsed string */
95740){
95741  Parse *pParse;            /* Parsing context */
95742  char *zErrMsg = 0;        /* Error message */
95743  int rc = SQLITE_OK;       /* Result code */
95744  int i;                    /* Loop counter */
95745
95746  /* Allocate the parsing context */
95747  pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
95748  if( pParse==0 ){
95749    rc = SQLITE_NOMEM;
95750    goto end_prepare;
95751  }
95752  pParse->pReprepare = pReprepare;
95753  assert( ppStmt && *ppStmt==0 );
95754  assert( !db->mallocFailed );
95755  assert( sqlite3_mutex_held(db->mutex) );
95756
95757  /* Check to verify that it is possible to get a read lock on all
95758  ** database schemas.  The inability to get a read lock indicates that
95759  ** some other database connection is holding a write-lock, which in
95760  ** turn means that the other connection has made uncommitted changes
95761  ** to the schema.
95762  **
95763  ** Were we to proceed and prepare the statement against the uncommitted
95764  ** schema changes and if those schema changes are subsequently rolled
95765  ** back and different changes are made in their place, then when this
95766  ** prepared statement goes to run the schema cookie would fail to detect
95767  ** the schema change.  Disaster would follow.
95768  **
95769  ** This thread is currently holding mutexes on all Btrees (because
95770  ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
95771  ** is not possible for another thread to start a new schema change
95772  ** while this routine is running.  Hence, we do not need to hold
95773  ** locks on the schema, we just need to make sure nobody else is
95774  ** holding them.
95775  **
95776  ** Note that setting READ_UNCOMMITTED overrides most lock detection,
95777  ** but it does *not* override schema lock detection, so this all still
95778  ** works even if READ_UNCOMMITTED is set.
95779  */
95780  for(i=0; i<db->nDb; i++) {
95781    Btree *pBt = db->aDb[i].pBt;
95782    if( pBt ){
95783      assert( sqlite3BtreeHoldsMutex(pBt) );
95784      rc = sqlite3BtreeSchemaLocked(pBt);
95785      if( rc ){
95786        const char *zDb = db->aDb[i].zName;
95787        sqlite3Error(db, rc, "database schema is locked: %s", zDb);
95788        testcase( db->flags & SQLITE_ReadUncommitted );
95789        goto end_prepare;
95790      }
95791    }
95792  }
95793
95794  sqlite3VtabUnlockList(db);
95795
95796  pParse->db = db;
95797  pParse->nQueryLoop = (double)1;
95798  if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
95799    char *zSqlCopy;
95800    int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
95801    testcase( nBytes==mxLen );
95802    testcase( nBytes==mxLen+1 );
95803    if( nBytes>mxLen ){
95804      sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
95805      rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
95806      goto end_prepare;
95807    }
95808    zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
95809    if( zSqlCopy ){
95810      sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
95811      sqlite3DbFree(db, zSqlCopy);
95812      pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
95813    }else{
95814      pParse->zTail = &zSql[nBytes];
95815    }
95816  }else{
95817    sqlite3RunParser(pParse, zSql, &zErrMsg);
95818  }
95819  assert( 1==(int)pParse->nQueryLoop );
95820
95821  if( db->mallocFailed ){
95822    pParse->rc = SQLITE_NOMEM;
95823  }
95824  if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
95825  if( pParse->checkSchema ){
95826    schemaIsValid(pParse);
95827  }
95828  if( db->mallocFailed ){
95829    pParse->rc = SQLITE_NOMEM;
95830  }
95831  if( pzTail ){
95832    *pzTail = pParse->zTail;
95833  }
95834  rc = pParse->rc;
95835
95836#ifndef SQLITE_OMIT_EXPLAIN
95837  if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
95838    static const char * const azColName[] = {
95839       "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
95840       "selectid", "order", "from", "detail"
95841    };
95842    int iFirst, mx;
95843    if( pParse->explain==2 ){
95844      sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
95845      iFirst = 8;
95846      mx = 12;
95847    }else{
95848      sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
95849      iFirst = 0;
95850      mx = 8;
95851    }
95852    for(i=iFirst; i<mx; i++){
95853      sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
95854                            azColName[i], SQLITE_STATIC);
95855    }
95856  }
95857#endif
95858
95859  if( db->init.busy==0 ){
95860    Vdbe *pVdbe = pParse->pVdbe;
95861    sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
95862  }
95863  if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
95864    sqlite3VdbeFinalize(pParse->pVdbe);
95865    assert(!(*ppStmt));
95866  }else{
95867    *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
95868  }
95869
95870  if( zErrMsg ){
95871    sqlite3Error(db, rc, "%s", zErrMsg);
95872    sqlite3DbFree(db, zErrMsg);
95873  }else{
95874    sqlite3Error(db, rc, 0);
95875  }
95876
95877  /* Delete any TriggerPrg structures allocated while parsing this statement. */
95878  while( pParse->pTriggerPrg ){
95879    TriggerPrg *pT = pParse->pTriggerPrg;
95880    pParse->pTriggerPrg = pT->pNext;
95881    sqlite3DbFree(db, pT);
95882  }
95883
95884end_prepare:
95885
95886  sqlite3StackFree(db, pParse);
95887  rc = sqlite3ApiExit(db, rc);
95888  assert( (rc&db->errMask)==rc );
95889  return rc;
95890}
95891static int sqlite3LockAndPrepare(
95892  sqlite3 *db,              /* Database handle. */
95893  const char *zSql,         /* UTF-8 encoded SQL statement. */
95894  int nBytes,               /* Length of zSql in bytes. */
95895  int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
95896  Vdbe *pOld,               /* VM being reprepared */
95897  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
95898  const char **pzTail       /* OUT: End of parsed string */
95899){
95900  int rc;
95901  assert( ppStmt!=0 );
95902  *ppStmt = 0;
95903  if( !sqlite3SafetyCheckOk(db) ){
95904    return SQLITE_MISUSE_BKPT;
95905  }
95906  sqlite3_mutex_enter(db->mutex);
95907  sqlite3BtreeEnterAll(db);
95908  rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
95909  if( rc==SQLITE_SCHEMA ){
95910    sqlite3_finalize(*ppStmt);
95911    rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
95912  }
95913  sqlite3BtreeLeaveAll(db);
95914  sqlite3_mutex_leave(db->mutex);
95915  assert( rc==SQLITE_OK || *ppStmt==0 );
95916  return rc;
95917}
95918
95919/*
95920** Rerun the compilation of a statement after a schema change.
95921**
95922** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
95923** if the statement cannot be recompiled because another connection has
95924** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
95925** occurs, return SQLITE_SCHEMA.
95926*/
95927SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
95928  int rc;
95929  sqlite3_stmt *pNew;
95930  const char *zSql;
95931  sqlite3 *db;
95932
95933  assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
95934  zSql = sqlite3_sql((sqlite3_stmt *)p);
95935  assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
95936  db = sqlite3VdbeDb(p);
95937  assert( sqlite3_mutex_held(db->mutex) );
95938  rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
95939  if( rc ){
95940    if( rc==SQLITE_NOMEM ){
95941      db->mallocFailed = 1;
95942    }
95943    assert( pNew==0 );
95944    return rc;
95945  }else{
95946    assert( pNew!=0 );
95947  }
95948  sqlite3VdbeSwap((Vdbe*)pNew, p);
95949  sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
95950  sqlite3VdbeResetStepResult((Vdbe*)pNew);
95951  sqlite3VdbeFinalize((Vdbe*)pNew);
95952  return SQLITE_OK;
95953}
95954
95955
95956/*
95957** Two versions of the official API.  Legacy and new use.  In the legacy
95958** version, the original SQL text is not saved in the prepared statement
95959** and so if a schema change occurs, SQLITE_SCHEMA is returned by
95960** sqlite3_step().  In the new version, the original SQL text is retained
95961** and the statement is automatically recompiled if an schema change
95962** occurs.
95963*/
95964SQLITE_API int sqlite3_prepare(
95965  sqlite3 *db,              /* Database handle. */
95966  const char *zSql,         /* UTF-8 encoded SQL statement. */
95967  int nBytes,               /* Length of zSql in bytes. */
95968  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
95969  const char **pzTail       /* OUT: End of parsed string */
95970){
95971  int rc;
95972  rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
95973  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
95974  return rc;
95975}
95976SQLITE_API int sqlite3_prepare_v2(
95977  sqlite3 *db,              /* Database handle. */
95978  const char *zSql,         /* UTF-8 encoded SQL statement. */
95979  int nBytes,               /* Length of zSql in bytes. */
95980  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
95981  const char **pzTail       /* OUT: End of parsed string */
95982){
95983  int rc;
95984  rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
95985  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
95986  return rc;
95987}
95988
95989
95990#ifndef SQLITE_OMIT_UTF16
95991/*
95992** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
95993*/
95994static int sqlite3Prepare16(
95995  sqlite3 *db,              /* Database handle. */
95996  const void *zSql,         /* UTF-16 encoded SQL statement. */
95997  int nBytes,               /* Length of zSql in bytes. */
95998  int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
95999  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
96000  const void **pzTail       /* OUT: End of parsed string */
96001){
96002  /* This function currently works by first transforming the UTF-16
96003  ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
96004  ** tricky bit is figuring out the pointer to return in *pzTail.
96005  */
96006  char *zSql8;
96007  const char *zTail8 = 0;
96008  int rc = SQLITE_OK;
96009
96010  assert( ppStmt );
96011  *ppStmt = 0;
96012  if( !sqlite3SafetyCheckOk(db) ){
96013    return SQLITE_MISUSE_BKPT;
96014  }
96015  sqlite3_mutex_enter(db->mutex);
96016  zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
96017  if( zSql8 ){
96018    rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
96019  }
96020
96021  if( zTail8 && pzTail ){
96022    /* If sqlite3_prepare returns a tail pointer, we calculate the
96023    ** equivalent pointer into the UTF-16 string by counting the unicode
96024    ** characters between zSql8 and zTail8, and then returning a pointer
96025    ** the same number of characters into the UTF-16 string.
96026    */
96027    int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
96028    *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
96029  }
96030  sqlite3DbFree(db, zSql8);
96031  rc = sqlite3ApiExit(db, rc);
96032  sqlite3_mutex_leave(db->mutex);
96033  return rc;
96034}
96035
96036/*
96037** Two versions of the official API.  Legacy and new use.  In the legacy
96038** version, the original SQL text is not saved in the prepared statement
96039** and so if a schema change occurs, SQLITE_SCHEMA is returned by
96040** sqlite3_step().  In the new version, the original SQL text is retained
96041** and the statement is automatically recompiled if an schema change
96042** occurs.
96043*/
96044SQLITE_API int sqlite3_prepare16(
96045  sqlite3 *db,              /* Database handle. */
96046  const void *zSql,         /* UTF-16 encoded SQL statement. */
96047  int nBytes,               /* Length of zSql in bytes. */
96048  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
96049  const void **pzTail       /* OUT: End of parsed string */
96050){
96051  int rc;
96052  rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
96053  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
96054  return rc;
96055}
96056SQLITE_API int sqlite3_prepare16_v2(
96057  sqlite3 *db,              /* Database handle. */
96058  const void *zSql,         /* UTF-16 encoded SQL statement. */
96059  int nBytes,               /* Length of zSql in bytes. */
96060  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
96061  const void **pzTail       /* OUT: End of parsed string */
96062){
96063  int rc;
96064  rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
96065  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
96066  return rc;
96067}
96068
96069#endif /* SQLITE_OMIT_UTF16 */
96070
96071/************** End of prepare.c *********************************************/
96072/************** Begin file select.c ******************************************/
96073/*
96074** 2001 September 15
96075**
96076** The author disclaims copyright to this source code.  In place of
96077** a legal notice, here is a blessing:
96078**
96079**    May you do good and not evil.
96080**    May you find forgiveness for yourself and forgive others.
96081**    May you share freely, never taking more than you give.
96082**
96083*************************************************************************
96084** This file contains C code routines that are called by the parser
96085** to handle SELECT statements in SQLite.
96086*/
96087
96088
96089/*
96090** Delete all the content of a Select structure but do not deallocate
96091** the select structure itself.
96092*/
96093static void clearSelect(sqlite3 *db, Select *p){
96094  sqlite3ExprListDelete(db, p->pEList);
96095  sqlite3SrcListDelete(db, p->pSrc);
96096  sqlite3ExprDelete(db, p->pWhere);
96097  sqlite3ExprListDelete(db, p->pGroupBy);
96098  sqlite3ExprDelete(db, p->pHaving);
96099  sqlite3ExprListDelete(db, p->pOrderBy);
96100  sqlite3SelectDelete(db, p->pPrior);
96101  sqlite3ExprDelete(db, p->pLimit);
96102  sqlite3ExprDelete(db, p->pOffset);
96103}
96104
96105/*
96106** Initialize a SelectDest structure.
96107*/
96108SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
96109  pDest->eDest = (u8)eDest;
96110  pDest->iSDParm = iParm;
96111  pDest->affSdst = 0;
96112  pDest->iSdst = 0;
96113  pDest->nSdst = 0;
96114}
96115
96116
96117/*
96118** Allocate a new Select structure and return a pointer to that
96119** structure.
96120*/
96121SQLITE_PRIVATE Select *sqlite3SelectNew(
96122  Parse *pParse,        /* Parsing context */
96123  ExprList *pEList,     /* which columns to include in the result */
96124  SrcList *pSrc,        /* the FROM clause -- which tables to scan */
96125  Expr *pWhere,         /* the WHERE clause */
96126  ExprList *pGroupBy,   /* the GROUP BY clause */
96127  Expr *pHaving,        /* the HAVING clause */
96128  ExprList *pOrderBy,   /* the ORDER BY clause */
96129  u16 selFlags,         /* Flag parameters, such as SF_Distinct */
96130  Expr *pLimit,         /* LIMIT value.  NULL means not used */
96131  Expr *pOffset         /* OFFSET value.  NULL means no offset */
96132){
96133  Select *pNew;
96134  Select standin;
96135  sqlite3 *db = pParse->db;
96136  pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
96137  assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
96138  if( pNew==0 ){
96139    assert( db->mallocFailed );
96140    pNew = &standin;
96141    memset(pNew, 0, sizeof(*pNew));
96142  }
96143  if( pEList==0 ){
96144    pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
96145  }
96146  pNew->pEList = pEList;
96147  if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));
96148  pNew->pSrc = pSrc;
96149  pNew->pWhere = pWhere;
96150  pNew->pGroupBy = pGroupBy;
96151  pNew->pHaving = pHaving;
96152  pNew->pOrderBy = pOrderBy;
96153  pNew->selFlags = selFlags;
96154  pNew->op = TK_SELECT;
96155  pNew->pLimit = pLimit;
96156  pNew->pOffset = pOffset;
96157  assert( pOffset==0 || pLimit!=0 );
96158  pNew->addrOpenEphm[0] = -1;
96159  pNew->addrOpenEphm[1] = -1;
96160  pNew->addrOpenEphm[2] = -1;
96161  if( db->mallocFailed ) {
96162    clearSelect(db, pNew);
96163    if( pNew!=&standin ) sqlite3DbFree(db, pNew);
96164    pNew = 0;
96165  }else{
96166    assert( pNew->pSrc!=0 || pParse->nErr>0 );
96167  }
96168  assert( pNew!=&standin );
96169  return pNew;
96170}
96171
96172/*
96173** Delete the given Select structure and all of its substructures.
96174*/
96175SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
96176  if( p ){
96177    clearSelect(db, p);
96178    sqlite3DbFree(db, p);
96179  }
96180}
96181
96182/*
96183** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
96184** type of join.  Return an integer constant that expresses that type
96185** in terms of the following bit values:
96186**
96187**     JT_INNER
96188**     JT_CROSS
96189**     JT_OUTER
96190**     JT_NATURAL
96191**     JT_LEFT
96192**     JT_RIGHT
96193**
96194** A full outer join is the combination of JT_LEFT and JT_RIGHT.
96195**
96196** If an illegal or unsupported join type is seen, then still return
96197** a join type, but put an error in the pParse structure.
96198*/
96199SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
96200  int jointype = 0;
96201  Token *apAll[3];
96202  Token *p;
96203                             /*   0123456789 123456789 123456789 123 */
96204  static const char zKeyText[] = "naturaleftouterightfullinnercross";
96205  static const struct {
96206    u8 i;        /* Beginning of keyword text in zKeyText[] */
96207    u8 nChar;    /* Length of the keyword in characters */
96208    u8 code;     /* Join type mask */
96209  } aKeyword[] = {
96210    /* natural */ { 0,  7, JT_NATURAL                },
96211    /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
96212    /* outer   */ { 10, 5, JT_OUTER                  },
96213    /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
96214    /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
96215    /* inner   */ { 23, 5, JT_INNER                  },
96216    /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
96217  };
96218  int i, j;
96219  apAll[0] = pA;
96220  apAll[1] = pB;
96221  apAll[2] = pC;
96222  for(i=0; i<3 && apAll[i]; i++){
96223    p = apAll[i];
96224    for(j=0; j<ArraySize(aKeyword); j++){
96225      if( p->n==aKeyword[j].nChar
96226          && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
96227        jointype |= aKeyword[j].code;
96228        break;
96229      }
96230    }
96231    testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
96232    if( j>=ArraySize(aKeyword) ){
96233      jointype |= JT_ERROR;
96234      break;
96235    }
96236  }
96237  if(
96238     (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
96239     (jointype & JT_ERROR)!=0
96240  ){
96241    const char *zSp = " ";
96242    assert( pB!=0 );
96243    if( pC==0 ){ zSp++; }
96244    sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
96245       "%T %T%s%T", pA, pB, zSp, pC);
96246    jointype = JT_INNER;
96247  }else if( (jointype & JT_OUTER)!=0
96248         && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
96249    sqlite3ErrorMsg(pParse,
96250      "RIGHT and FULL OUTER JOINs are not currently supported");
96251    jointype = JT_INNER;
96252  }
96253  return jointype;
96254}
96255
96256/*
96257** Return the index of a column in a table.  Return -1 if the column
96258** is not contained in the table.
96259*/
96260static int columnIndex(Table *pTab, const char *zCol){
96261  int i;
96262  for(i=0; i<pTab->nCol; i++){
96263    if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
96264  }
96265  return -1;
96266}
96267
96268/*
96269** Search the first N tables in pSrc, from left to right, looking for a
96270** table that has a column named zCol.
96271**
96272** When found, set *piTab and *piCol to the table index and column index
96273** of the matching column and return TRUE.
96274**
96275** If not found, return FALSE.
96276*/
96277static int tableAndColumnIndex(
96278  SrcList *pSrc,       /* Array of tables to search */
96279  int N,               /* Number of tables in pSrc->a[] to search */
96280  const char *zCol,    /* Name of the column we are looking for */
96281  int *piTab,          /* Write index of pSrc->a[] here */
96282  int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
96283){
96284  int i;               /* For looping over tables in pSrc */
96285  int iCol;            /* Index of column matching zCol */
96286
96287  assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
96288  for(i=0; i<N; i++){
96289    iCol = columnIndex(pSrc->a[i].pTab, zCol);
96290    if( iCol>=0 ){
96291      if( piTab ){
96292        *piTab = i;
96293        *piCol = iCol;
96294      }
96295      return 1;
96296    }
96297  }
96298  return 0;
96299}
96300
96301/*
96302** This function is used to add terms implied by JOIN syntax to the
96303** WHERE clause expression of a SELECT statement. The new term, which
96304** is ANDed with the existing WHERE clause, is of the form:
96305**
96306**    (tab1.col1 = tab2.col2)
96307**
96308** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
96309** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
96310** column iColRight of tab2.
96311*/
96312static void addWhereTerm(
96313  Parse *pParse,                  /* Parsing context */
96314  SrcList *pSrc,                  /* List of tables in FROM clause */
96315  int iLeft,                      /* Index of first table to join in pSrc */
96316  int iColLeft,                   /* Index of column in first table */
96317  int iRight,                     /* Index of second table in pSrc */
96318  int iColRight,                  /* Index of column in second table */
96319  int isOuterJoin,                /* True if this is an OUTER join */
96320  Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
96321){
96322  sqlite3 *db = pParse->db;
96323  Expr *pE1;
96324  Expr *pE2;
96325  Expr *pEq;
96326
96327  assert( iLeft<iRight );
96328  assert( pSrc->nSrc>iRight );
96329  assert( pSrc->a[iLeft].pTab );
96330  assert( pSrc->a[iRight].pTab );
96331
96332  pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
96333  pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
96334
96335  pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
96336  if( pEq && isOuterJoin ){
96337    ExprSetProperty(pEq, EP_FromJoin);
96338    assert( !ExprHasAnyProperty(pEq, EP_TokenOnly|EP_Reduced) );
96339    ExprSetIrreducible(pEq);
96340    pEq->iRightJoinTable = (i16)pE2->iTable;
96341  }
96342  *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
96343}
96344
96345/*
96346** Set the EP_FromJoin property on all terms of the given expression.
96347** And set the Expr.iRightJoinTable to iTable for every term in the
96348** expression.
96349**
96350** The EP_FromJoin property is used on terms of an expression to tell
96351** the LEFT OUTER JOIN processing logic that this term is part of the
96352** join restriction specified in the ON or USING clause and not a part
96353** of the more general WHERE clause.  These terms are moved over to the
96354** WHERE clause during join processing but we need to remember that they
96355** originated in the ON or USING clause.
96356**
96357** The Expr.iRightJoinTable tells the WHERE clause processing that the
96358** expression depends on table iRightJoinTable even if that table is not
96359** explicitly mentioned in the expression.  That information is needed
96360** for cases like this:
96361**
96362**    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
96363**
96364** The where clause needs to defer the handling of the t1.x=5
96365** term until after the t2 loop of the join.  In that way, a
96366** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
96367** defer the handling of t1.x=5, it will be processed immediately
96368** after the t1 loop and rows with t1.x!=5 will never appear in
96369** the output, which is incorrect.
96370*/
96371static void setJoinExpr(Expr *p, int iTable){
96372  while( p ){
96373    ExprSetProperty(p, EP_FromJoin);
96374    assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
96375    ExprSetIrreducible(p);
96376    p->iRightJoinTable = (i16)iTable;
96377    setJoinExpr(p->pLeft, iTable);
96378    p = p->pRight;
96379  }
96380}
96381
96382/*
96383** This routine processes the join information for a SELECT statement.
96384** ON and USING clauses are converted into extra terms of the WHERE clause.
96385** NATURAL joins also create extra WHERE clause terms.
96386**
96387** The terms of a FROM clause are contained in the Select.pSrc structure.
96388** The left most table is the first entry in Select.pSrc.  The right-most
96389** table is the last entry.  The join operator is held in the entry to
96390** the left.  Thus entry 0 contains the join operator for the join between
96391** entries 0 and 1.  Any ON or USING clauses associated with the join are
96392** also attached to the left entry.
96393**
96394** This routine returns the number of errors encountered.
96395*/
96396static int sqliteProcessJoin(Parse *pParse, Select *p){
96397  SrcList *pSrc;                  /* All tables in the FROM clause */
96398  int i, j;                       /* Loop counters */
96399  struct SrcList_item *pLeft;     /* Left table being joined */
96400  struct SrcList_item *pRight;    /* Right table being joined */
96401
96402  pSrc = p->pSrc;
96403  pLeft = &pSrc->a[0];
96404  pRight = &pLeft[1];
96405  for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
96406    Table *pLeftTab = pLeft->pTab;
96407    Table *pRightTab = pRight->pTab;
96408    int isOuter;
96409
96410    if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
96411    isOuter = (pRight->jointype & JT_OUTER)!=0;
96412
96413    /* When the NATURAL keyword is present, add WHERE clause terms for
96414    ** every column that the two tables have in common.
96415    */
96416    if( pRight->jointype & JT_NATURAL ){
96417      if( pRight->pOn || pRight->pUsing ){
96418        sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
96419           "an ON or USING clause", 0);
96420        return 1;
96421      }
96422      for(j=0; j<pRightTab->nCol; j++){
96423        char *zName;   /* Name of column in the right table */
96424        int iLeft;     /* Matching left table */
96425        int iLeftCol;  /* Matching column in the left table */
96426
96427        zName = pRightTab->aCol[j].zName;
96428        if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
96429          addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
96430                       isOuter, &p->pWhere);
96431        }
96432      }
96433    }
96434
96435    /* Disallow both ON and USING clauses in the same join
96436    */
96437    if( pRight->pOn && pRight->pUsing ){
96438      sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
96439        "clauses in the same join");
96440      return 1;
96441    }
96442
96443    /* Add the ON clause to the end of the WHERE clause, connected by
96444    ** an AND operator.
96445    */
96446    if( pRight->pOn ){
96447      if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
96448      p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
96449      pRight->pOn = 0;
96450    }
96451
96452    /* Create extra terms on the WHERE clause for each column named
96453    ** in the USING clause.  Example: If the two tables to be joined are
96454    ** A and B and the USING clause names X, Y, and Z, then add this
96455    ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
96456    ** Report an error if any column mentioned in the USING clause is
96457    ** not contained in both tables to be joined.
96458    */
96459    if( pRight->pUsing ){
96460      IdList *pList = pRight->pUsing;
96461      for(j=0; j<pList->nId; j++){
96462        char *zName;     /* Name of the term in the USING clause */
96463        int iLeft;       /* Table on the left with matching column name */
96464        int iLeftCol;    /* Column number of matching column on the left */
96465        int iRightCol;   /* Column number of matching column on the right */
96466
96467        zName = pList->a[j].zName;
96468        iRightCol = columnIndex(pRightTab, zName);
96469        if( iRightCol<0
96470         || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
96471        ){
96472          sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
96473            "not present in both tables", zName);
96474          return 1;
96475        }
96476        addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
96477                     isOuter, &p->pWhere);
96478      }
96479    }
96480  }
96481  return 0;
96482}
96483
96484/*
96485** Insert code into "v" that will push the record on the top of the
96486** stack into the sorter.
96487*/
96488static void pushOntoSorter(
96489  Parse *pParse,         /* Parser context */
96490  ExprList *pOrderBy,    /* The ORDER BY clause */
96491  Select *pSelect,       /* The whole SELECT statement */
96492  int regData            /* Register holding data to be sorted */
96493){
96494  Vdbe *v = pParse->pVdbe;
96495  int nExpr = pOrderBy->nExpr;
96496  int regBase = sqlite3GetTempRange(pParse, nExpr+2);
96497  int regRecord = sqlite3GetTempReg(pParse);
96498  int op;
96499  sqlite3ExprCacheClear(pParse);
96500  sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
96501  sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
96502  sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
96503  sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
96504  if( pSelect->selFlags & SF_UseSorter ){
96505    op = OP_SorterInsert;
96506  }else{
96507    op = OP_IdxInsert;
96508  }
96509  sqlite3VdbeAddOp2(v, op, pOrderBy->iECursor, regRecord);
96510  sqlite3ReleaseTempReg(pParse, regRecord);
96511  sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
96512  if( pSelect->iLimit ){
96513    int addr1, addr2;
96514    int iLimit;
96515    if( pSelect->iOffset ){
96516      iLimit = pSelect->iOffset+1;
96517    }else{
96518      iLimit = pSelect->iLimit;
96519    }
96520    addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
96521    sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
96522    addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
96523    sqlite3VdbeJumpHere(v, addr1);
96524    sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
96525    sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
96526    sqlite3VdbeJumpHere(v, addr2);
96527  }
96528}
96529
96530/*
96531** Add code to implement the OFFSET
96532*/
96533static void codeOffset(
96534  Vdbe *v,          /* Generate code into this VM */
96535  Select *p,        /* The SELECT statement being coded */
96536  int iContinue     /* Jump here to skip the current record */
96537){
96538  if( p->iOffset && iContinue!=0 ){
96539    int addr;
96540    sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
96541    addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
96542    sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
96543    VdbeComment((v, "skip OFFSET records"));
96544    sqlite3VdbeJumpHere(v, addr);
96545  }
96546}
96547
96548/*
96549** Add code that will check to make sure the N registers starting at iMem
96550** form a distinct entry.  iTab is a sorting index that holds previously
96551** seen combinations of the N values.  A new entry is made in iTab
96552** if the current N values are new.
96553**
96554** A jump to addrRepeat is made and the N+1 values are popped from the
96555** stack if the top N elements are not distinct.
96556*/
96557static void codeDistinct(
96558  Parse *pParse,     /* Parsing and code generating context */
96559  int iTab,          /* A sorting index used to test for distinctness */
96560  int addrRepeat,    /* Jump to here if not distinct */
96561  int N,             /* Number of elements */
96562  int iMem           /* First element */
96563){
96564  Vdbe *v;
96565  int r1;
96566
96567  v = pParse->pVdbe;
96568  r1 = sqlite3GetTempReg(pParse);
96569  sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N);
96570  sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
96571  sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
96572  sqlite3ReleaseTempReg(pParse, r1);
96573}
96574
96575#ifndef SQLITE_OMIT_SUBQUERY
96576/*
96577** Generate an error message when a SELECT is used within a subexpression
96578** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
96579** column.  We do this in a subroutine because the error used to occur
96580** in multiple places.  (The error only occurs in one place now, but we
96581** retain the subroutine to minimize code disruption.)
96582*/
96583static int checkForMultiColumnSelectError(
96584  Parse *pParse,       /* Parse context. */
96585  SelectDest *pDest,   /* Destination of SELECT results */
96586  int nExpr            /* Number of result columns returned by SELECT */
96587){
96588  int eDest = pDest->eDest;
96589  if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
96590    sqlite3ErrorMsg(pParse, "only a single result allowed for "
96591       "a SELECT that is part of an expression");
96592    return 1;
96593  }else{
96594    return 0;
96595  }
96596}
96597#endif
96598
96599/*
96600** An instance of the following object is used to record information about
96601** how to process the DISTINCT keyword, to simplify passing that information
96602** into the selectInnerLoop() routine.
96603*/
96604typedef struct DistinctCtx DistinctCtx;
96605struct DistinctCtx {
96606  u8 isTnct;      /* True if the DISTINCT keyword is present */
96607  u8 eTnctType;   /* One of the WHERE_DISTINCT_* operators */
96608  int tabTnct;    /* Ephemeral table used for DISTINCT processing */
96609  int addrTnct;   /* Address of OP_OpenEphemeral opcode for tabTnct */
96610};
96611
96612/*
96613** This routine generates the code for the inside of the inner loop
96614** of a SELECT.
96615**
96616** If srcTab and nColumn are both zero, then the pEList expressions
96617** are evaluated in order to get the data for this row.  If nColumn>0
96618** then data is pulled from srcTab and pEList is used only to get the
96619** datatypes for each column.
96620*/
96621static void selectInnerLoop(
96622  Parse *pParse,          /* The parser context */
96623  Select *p,              /* The complete select statement being coded */
96624  ExprList *pEList,       /* List of values being extracted */
96625  int srcTab,             /* Pull data from this table */
96626  int nColumn,            /* Number of columns in the source table */
96627  ExprList *pOrderBy,     /* If not NULL, sort results using this key */
96628  DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
96629  SelectDest *pDest,      /* How to dispose of the results */
96630  int iContinue,          /* Jump here to continue with next row */
96631  int iBreak              /* Jump here to break out of the inner loop */
96632){
96633  Vdbe *v = pParse->pVdbe;
96634  int i;
96635  int hasDistinct;        /* True if the DISTINCT keyword is present */
96636  int regResult;              /* Start of memory holding result set */
96637  int eDest = pDest->eDest;   /* How to dispose of results */
96638  int iParm = pDest->iSDParm; /* First argument to disposal method */
96639  int nResultCol;             /* Number of result columns */
96640
96641  assert( v );
96642  if( NEVER(v==0) ) return;
96643  assert( pEList!=0 );
96644  hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
96645  if( pOrderBy==0 && !hasDistinct ){
96646    codeOffset(v, p, iContinue);
96647  }
96648
96649  /* Pull the requested columns.
96650  */
96651  if( nColumn>0 ){
96652    nResultCol = nColumn;
96653  }else{
96654    nResultCol = pEList->nExpr;
96655  }
96656  if( pDest->iSdst==0 ){
96657    pDest->iSdst = pParse->nMem+1;
96658    pDest->nSdst = nResultCol;
96659    pParse->nMem += nResultCol;
96660  }else{
96661    assert( pDest->nSdst==nResultCol );
96662  }
96663  regResult = pDest->iSdst;
96664  if( nColumn>0 ){
96665    for(i=0; i<nColumn; i++){
96666      sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
96667    }
96668  }else if( eDest!=SRT_Exists ){
96669    /* If the destination is an EXISTS(...) expression, the actual
96670    ** values returned by the SELECT are not required.
96671    */
96672    sqlite3ExprCacheClear(pParse);
96673    sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
96674  }
96675  nColumn = nResultCol;
96676
96677  /* If the DISTINCT keyword was present on the SELECT statement
96678  ** and this row has been seen before, then do not make this row
96679  ** part of the result.
96680  */
96681  if( hasDistinct ){
96682    assert( pEList!=0 );
96683    assert( pEList->nExpr==nColumn );
96684    switch( pDistinct->eTnctType ){
96685      case WHERE_DISTINCT_ORDERED: {
96686        VdbeOp *pOp;            /* No longer required OpenEphemeral instr. */
96687        int iJump;              /* Jump destination */
96688        int regPrev;            /* Previous row content */
96689
96690        /* Allocate space for the previous row */
96691        regPrev = pParse->nMem+1;
96692        pParse->nMem += nColumn;
96693
96694        /* Change the OP_OpenEphemeral coded earlier to an OP_Null
96695        ** sets the MEM_Cleared bit on the first register of the
96696        ** previous value.  This will cause the OP_Ne below to always
96697        ** fail on the first iteration of the loop even if the first
96698        ** row is all NULLs.
96699        */
96700        sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
96701        pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
96702        pOp->opcode = OP_Null;
96703        pOp->p1 = 1;
96704        pOp->p2 = regPrev;
96705
96706        iJump = sqlite3VdbeCurrentAddr(v) + nColumn;
96707        for(i=0; i<nColumn; i++){
96708          CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
96709          if( i<nColumn-1 ){
96710            sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
96711          }else{
96712            sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
96713          }
96714          sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
96715          sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
96716        }
96717        assert( sqlite3VdbeCurrentAddr(v)==iJump );
96718        sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nColumn-1);
96719        break;
96720      }
96721
96722      case WHERE_DISTINCT_UNIQUE: {
96723        sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
96724        break;
96725      }
96726
96727      default: {
96728        assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
96729        codeDistinct(pParse, pDistinct->tabTnct, iContinue, nColumn, regResult);
96730        break;
96731      }
96732    }
96733    if( pOrderBy==0 ){
96734      codeOffset(v, p, iContinue);
96735    }
96736  }
96737
96738  switch( eDest ){
96739    /* In this mode, write each query result to the key of the temporary
96740    ** table iParm.
96741    */
96742#ifndef SQLITE_OMIT_COMPOUND_SELECT
96743    case SRT_Union: {
96744      int r1;
96745      r1 = sqlite3GetTempReg(pParse);
96746      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
96747      sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
96748      sqlite3ReleaseTempReg(pParse, r1);
96749      break;
96750    }
96751
96752    /* Construct a record from the query result, but instead of
96753    ** saving that record, use it as a key to delete elements from
96754    ** the temporary table iParm.
96755    */
96756    case SRT_Except: {
96757      sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
96758      break;
96759    }
96760#endif
96761
96762    /* Store the result as data using a unique key.
96763    */
96764    case SRT_Table:
96765    case SRT_EphemTab: {
96766      int r1 = sqlite3GetTempReg(pParse);
96767      testcase( eDest==SRT_Table );
96768      testcase( eDest==SRT_EphemTab );
96769      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
96770      if( pOrderBy ){
96771        pushOntoSorter(pParse, pOrderBy, p, r1);
96772      }else{
96773        int r2 = sqlite3GetTempReg(pParse);
96774        sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
96775        sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
96776        sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
96777        sqlite3ReleaseTempReg(pParse, r2);
96778      }
96779      sqlite3ReleaseTempReg(pParse, r1);
96780      break;
96781    }
96782
96783#ifndef SQLITE_OMIT_SUBQUERY
96784    /* If we are creating a set for an "expr IN (SELECT ...)" construct,
96785    ** then there should be a single item on the stack.  Write this
96786    ** item into the set table with bogus data.
96787    */
96788    case SRT_Set: {
96789      assert( nColumn==1 );
96790      pDest->affSdst =
96791                  sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affSdst);
96792      if( pOrderBy ){
96793        /* At first glance you would think we could optimize out the
96794        ** ORDER BY in this case since the order of entries in the set
96795        ** does not matter.  But there might be a LIMIT clause, in which
96796        ** case the order does matter */
96797        pushOntoSorter(pParse, pOrderBy, p, regResult);
96798      }else{
96799        int r1 = sqlite3GetTempReg(pParse);
96800        sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult,1,r1, &pDest->affSdst, 1);
96801        sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
96802        sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
96803        sqlite3ReleaseTempReg(pParse, r1);
96804      }
96805      break;
96806    }
96807
96808    /* If any row exist in the result set, record that fact and abort.
96809    */
96810    case SRT_Exists: {
96811      sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
96812      /* The LIMIT clause will terminate the loop for us */
96813      break;
96814    }
96815
96816    /* If this is a scalar select that is part of an expression, then
96817    ** store the results in the appropriate memory cell and break out
96818    ** of the scan loop.
96819    */
96820    case SRT_Mem: {
96821      assert( nColumn==1 );
96822      if( pOrderBy ){
96823        pushOntoSorter(pParse, pOrderBy, p, regResult);
96824      }else{
96825        sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
96826        /* The LIMIT clause will jump out of the loop for us */
96827      }
96828      break;
96829    }
96830#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
96831
96832    /* Send the data to the callback function or to a subroutine.  In the
96833    ** case of a subroutine, the subroutine itself is responsible for
96834    ** popping the data from the stack.
96835    */
96836    case SRT_Coroutine:
96837    case SRT_Output: {
96838      testcase( eDest==SRT_Coroutine );
96839      testcase( eDest==SRT_Output );
96840      if( pOrderBy ){
96841        int r1 = sqlite3GetTempReg(pParse);
96842        sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
96843        pushOntoSorter(pParse, pOrderBy, p, r1);
96844        sqlite3ReleaseTempReg(pParse, r1);
96845      }else if( eDest==SRT_Coroutine ){
96846        sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
96847      }else{
96848        sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
96849        sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
96850      }
96851      break;
96852    }
96853
96854#if !defined(SQLITE_OMIT_TRIGGER)
96855    /* Discard the results.  This is used for SELECT statements inside
96856    ** the body of a TRIGGER.  The purpose of such selects is to call
96857    ** user-defined functions that have side effects.  We do not care
96858    ** about the actual results of the select.
96859    */
96860    default: {
96861      assert( eDest==SRT_Discard );
96862      break;
96863    }
96864#endif
96865  }
96866
96867  /* Jump to the end of the loop if the LIMIT is reached.  Except, if
96868  ** there is a sorter, in which case the sorter has already limited
96869  ** the output for us.
96870  */
96871  if( pOrderBy==0 && p->iLimit ){
96872    sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
96873  }
96874}
96875
96876/*
96877** Given an expression list, generate a KeyInfo structure that records
96878** the collating sequence for each expression in that expression list.
96879**
96880** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
96881** KeyInfo structure is appropriate for initializing a virtual index to
96882** implement that clause.  If the ExprList is the result set of a SELECT
96883** then the KeyInfo structure is appropriate for initializing a virtual
96884** index to implement a DISTINCT test.
96885**
96886** Space to hold the KeyInfo structure is obtain from malloc.  The calling
96887** function is responsible for seeing that this structure is eventually
96888** freed.  Add the KeyInfo structure to the P4 field of an opcode using
96889** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
96890*/
96891static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
96892  sqlite3 *db = pParse->db;
96893  int nExpr;
96894  KeyInfo *pInfo;
96895  struct ExprList_item *pItem;
96896  int i;
96897
96898  nExpr = pList->nExpr;
96899  pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
96900  if( pInfo ){
96901    pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
96902    pInfo->nField = (u16)nExpr;
96903    pInfo->enc = ENC(db);
96904    pInfo->db = db;
96905    for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
96906      CollSeq *pColl;
96907      pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
96908      if( !pColl ){
96909        pColl = db->pDfltColl;
96910      }
96911      pInfo->aColl[i] = pColl;
96912      pInfo->aSortOrder[i] = pItem->sortOrder;
96913    }
96914  }
96915  return pInfo;
96916}
96917
96918#ifndef SQLITE_OMIT_COMPOUND_SELECT
96919/*
96920** Name of the connection operator, used for error messages.
96921*/
96922static const char *selectOpName(int id){
96923  char *z;
96924  switch( id ){
96925    case TK_ALL:       z = "UNION ALL";   break;
96926    case TK_INTERSECT: z = "INTERSECT";   break;
96927    case TK_EXCEPT:    z = "EXCEPT";      break;
96928    default:           z = "UNION";       break;
96929  }
96930  return z;
96931}
96932#endif /* SQLITE_OMIT_COMPOUND_SELECT */
96933
96934#ifndef SQLITE_OMIT_EXPLAIN
96935/*
96936** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
96937** is a no-op. Otherwise, it adds a single row of output to the EQP result,
96938** where the caption is of the form:
96939**
96940**   "USE TEMP B-TREE FOR xxx"
96941**
96942** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
96943** is determined by the zUsage argument.
96944*/
96945static void explainTempTable(Parse *pParse, const char *zUsage){
96946  if( pParse->explain==2 ){
96947    Vdbe *v = pParse->pVdbe;
96948    char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
96949    sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
96950  }
96951}
96952
96953/*
96954** Assign expression b to lvalue a. A second, no-op, version of this macro
96955** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
96956** in sqlite3Select() to assign values to structure member variables that
96957** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
96958** code with #ifndef directives.
96959*/
96960# define explainSetInteger(a, b) a = b
96961
96962#else
96963/* No-op versions of the explainXXX() functions and macros. */
96964# define explainTempTable(y,z)
96965# define explainSetInteger(y,z)
96966#endif
96967
96968#if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
96969/*
96970** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
96971** is a no-op. Otherwise, it adds a single row of output to the EQP result,
96972** where the caption is of one of the two forms:
96973**
96974**   "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
96975**   "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
96976**
96977** where iSub1 and iSub2 are the integers passed as the corresponding
96978** function parameters, and op is the text representation of the parameter
96979** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
96980** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
96981** false, or the second form if it is true.
96982*/
96983static void explainComposite(
96984  Parse *pParse,                  /* Parse context */
96985  int op,                         /* One of TK_UNION, TK_EXCEPT etc. */
96986  int iSub1,                      /* Subquery id 1 */
96987  int iSub2,                      /* Subquery id 2 */
96988  int bUseTmp                     /* True if a temp table was used */
96989){
96990  assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
96991  if( pParse->explain==2 ){
96992    Vdbe *v = pParse->pVdbe;
96993    char *zMsg = sqlite3MPrintf(
96994        pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
96995        bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
96996    );
96997    sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
96998  }
96999}
97000#else
97001/* No-op versions of the explainXXX() functions and macros. */
97002# define explainComposite(v,w,x,y,z)
97003#endif
97004
97005/*
97006** If the inner loop was generated using a non-null pOrderBy argument,
97007** then the results were placed in a sorter.  After the loop is terminated
97008** we need to run the sorter and output the results.  The following
97009** routine generates the code needed to do that.
97010*/
97011static void generateSortTail(
97012  Parse *pParse,    /* Parsing context */
97013  Select *p,        /* The SELECT statement */
97014  Vdbe *v,          /* Generate code into this VDBE */
97015  int nColumn,      /* Number of columns of data */
97016  SelectDest *pDest /* Write the sorted results here */
97017){
97018  int addrBreak = sqlite3VdbeMakeLabel(v);     /* Jump here to exit loop */
97019  int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
97020  int addr;
97021  int iTab;
97022  int pseudoTab = 0;
97023  ExprList *pOrderBy = p->pOrderBy;
97024
97025  int eDest = pDest->eDest;
97026  int iParm = pDest->iSDParm;
97027
97028  int regRow;
97029  int regRowid;
97030
97031  iTab = pOrderBy->iECursor;
97032  regRow = sqlite3GetTempReg(pParse);
97033  if( eDest==SRT_Output || eDest==SRT_Coroutine ){
97034    pseudoTab = pParse->nTab++;
97035    sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
97036    regRowid = 0;
97037  }else{
97038    regRowid = sqlite3GetTempReg(pParse);
97039  }
97040  if( p->selFlags & SF_UseSorter ){
97041    int regSortOut = ++pParse->nMem;
97042    int ptab2 = pParse->nTab++;
97043    sqlite3VdbeAddOp3(v, OP_OpenPseudo, ptab2, regSortOut, pOrderBy->nExpr+2);
97044    addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
97045    codeOffset(v, p, addrContinue);
97046    sqlite3VdbeAddOp2(v, OP_SorterData, iTab, regSortOut);
97047    sqlite3VdbeAddOp3(v, OP_Column, ptab2, pOrderBy->nExpr+1, regRow);
97048    sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
97049  }else{
97050    addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
97051    codeOffset(v, p, addrContinue);
97052    sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr+1, regRow);
97053  }
97054  switch( eDest ){
97055    case SRT_Table:
97056    case SRT_EphemTab: {
97057      testcase( eDest==SRT_Table );
97058      testcase( eDest==SRT_EphemTab );
97059      sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
97060      sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
97061      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
97062      break;
97063    }
97064#ifndef SQLITE_OMIT_SUBQUERY
97065    case SRT_Set: {
97066      assert( nColumn==1 );
97067      sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid,
97068                        &pDest->affSdst, 1);
97069      sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
97070      sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
97071      break;
97072    }
97073    case SRT_Mem: {
97074      assert( nColumn==1 );
97075      sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
97076      /* The LIMIT clause will terminate the loop for us */
97077      break;
97078    }
97079#endif
97080    default: {
97081      int i;
97082      assert( eDest==SRT_Output || eDest==SRT_Coroutine );
97083      testcase( eDest==SRT_Output );
97084      testcase( eDest==SRT_Coroutine );
97085      for(i=0; i<nColumn; i++){
97086        assert( regRow!=pDest->iSdst+i );
97087        sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iSdst+i);
97088        if( i==0 ){
97089          sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
97090        }
97091      }
97092      if( eDest==SRT_Output ){
97093        sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
97094        sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
97095      }else{
97096        sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
97097      }
97098      break;
97099    }
97100  }
97101  sqlite3ReleaseTempReg(pParse, regRow);
97102  sqlite3ReleaseTempReg(pParse, regRowid);
97103
97104  /* The bottom of the loop
97105  */
97106  sqlite3VdbeResolveLabel(v, addrContinue);
97107  if( p->selFlags & SF_UseSorter ){
97108    sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr);
97109  }else{
97110    sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
97111  }
97112  sqlite3VdbeResolveLabel(v, addrBreak);
97113  if( eDest==SRT_Output || eDest==SRT_Coroutine ){
97114    sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
97115  }
97116}
97117
97118/*
97119** Return a pointer to a string containing the 'declaration type' of the
97120** expression pExpr. The string may be treated as static by the caller.
97121**
97122** The declaration type is the exact datatype definition extracted from the
97123** original CREATE TABLE statement if the expression is a column. The
97124** declaration type for a ROWID field is INTEGER. Exactly when an expression
97125** is considered a column can be complex in the presence of subqueries. The
97126** result-set expression in all of the following SELECT statements is
97127** considered a column by this function.
97128**
97129**   SELECT col FROM tbl;
97130**   SELECT (SELECT col FROM tbl;
97131**   SELECT (SELECT col FROM tbl);
97132**   SELECT abc FROM (SELECT col AS abc FROM tbl);
97133**
97134** The declaration type for any expression other than a column is NULL.
97135*/
97136static const char *columnType(
97137  NameContext *pNC,
97138  Expr *pExpr,
97139  const char **pzOriginDb,
97140  const char **pzOriginTab,
97141  const char **pzOriginCol
97142){
97143  char const *zType = 0;
97144  char const *zOriginDb = 0;
97145  char const *zOriginTab = 0;
97146  char const *zOriginCol = 0;
97147  int j;
97148  if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
97149
97150  switch( pExpr->op ){
97151    case TK_AGG_COLUMN:
97152    case TK_COLUMN: {
97153      /* The expression is a column. Locate the table the column is being
97154      ** extracted from in NameContext.pSrcList. This table may be real
97155      ** database table or a subquery.
97156      */
97157      Table *pTab = 0;            /* Table structure column is extracted from */
97158      Select *pS = 0;             /* Select the column is extracted from */
97159      int iCol = pExpr->iColumn;  /* Index of column in pTab */
97160      testcase( pExpr->op==TK_AGG_COLUMN );
97161      testcase( pExpr->op==TK_COLUMN );
97162      while( pNC && !pTab ){
97163        SrcList *pTabList = pNC->pSrcList;
97164        for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
97165        if( j<pTabList->nSrc ){
97166          pTab = pTabList->a[j].pTab;
97167          pS = pTabList->a[j].pSelect;
97168        }else{
97169          pNC = pNC->pNext;
97170        }
97171      }
97172
97173      if( pTab==0 ){
97174        /* At one time, code such as "SELECT new.x" within a trigger would
97175        ** cause this condition to run.  Since then, we have restructured how
97176        ** trigger code is generated and so this condition is no longer
97177        ** possible. However, it can still be true for statements like
97178        ** the following:
97179        **
97180        **   CREATE TABLE t1(col INTEGER);
97181        **   SELECT (SELECT t1.col) FROM FROM t1;
97182        **
97183        ** when columnType() is called on the expression "t1.col" in the
97184        ** sub-select. In this case, set the column type to NULL, even
97185        ** though it should really be "INTEGER".
97186        **
97187        ** This is not a problem, as the column type of "t1.col" is never
97188        ** used. When columnType() is called on the expression
97189        ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
97190        ** branch below.  */
97191        break;
97192      }
97193
97194      assert( pTab && pExpr->pTab==pTab );
97195      if( pS ){
97196        /* The "table" is actually a sub-select or a view in the FROM clause
97197        ** of the SELECT statement. Return the declaration type and origin
97198        ** data for the result-set column of the sub-select.
97199        */
97200        if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
97201          /* If iCol is less than zero, then the expression requests the
97202          ** rowid of the sub-select or view. This expression is legal (see
97203          ** test case misc2.2.2) - it always evaluates to NULL.
97204          */
97205          NameContext sNC;
97206          Expr *p = pS->pEList->a[iCol].pExpr;
97207          sNC.pSrcList = pS->pSrc;
97208          sNC.pNext = pNC;
97209          sNC.pParse = pNC->pParse;
97210          zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
97211        }
97212      }else if( ALWAYS(pTab->pSchema) ){
97213        /* A real table */
97214        assert( !pS );
97215        if( iCol<0 ) iCol = pTab->iPKey;
97216        assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
97217        if( iCol<0 ){
97218          zType = "INTEGER";
97219          zOriginCol = "rowid";
97220        }else{
97221          zType = pTab->aCol[iCol].zType;
97222          zOriginCol = pTab->aCol[iCol].zName;
97223        }
97224        zOriginTab = pTab->zName;
97225        if( pNC->pParse ){
97226          int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
97227          zOriginDb = pNC->pParse->db->aDb[iDb].zName;
97228        }
97229      }
97230      break;
97231    }
97232#ifndef SQLITE_OMIT_SUBQUERY
97233    case TK_SELECT: {
97234      /* The expression is a sub-select. Return the declaration type and
97235      ** origin info for the single column in the result set of the SELECT
97236      ** statement.
97237      */
97238      NameContext sNC;
97239      Select *pS = pExpr->x.pSelect;
97240      Expr *p = pS->pEList->a[0].pExpr;
97241      assert( ExprHasProperty(pExpr, EP_xIsSelect) );
97242      sNC.pSrcList = pS->pSrc;
97243      sNC.pNext = pNC;
97244      sNC.pParse = pNC->pParse;
97245      zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
97246      break;
97247    }
97248#endif
97249  }
97250
97251  if( pzOriginDb ){
97252    assert( pzOriginTab && pzOriginCol );
97253    *pzOriginDb = zOriginDb;
97254    *pzOriginTab = zOriginTab;
97255    *pzOriginCol = zOriginCol;
97256  }
97257  return zType;
97258}
97259
97260/*
97261** Generate code that will tell the VDBE the declaration types of columns
97262** in the result set.
97263*/
97264static void generateColumnTypes(
97265  Parse *pParse,      /* Parser context */
97266  SrcList *pTabList,  /* List of tables */
97267  ExprList *pEList    /* Expressions defining the result set */
97268){
97269#ifndef SQLITE_OMIT_DECLTYPE
97270  Vdbe *v = pParse->pVdbe;
97271  int i;
97272  NameContext sNC;
97273  sNC.pSrcList = pTabList;
97274  sNC.pParse = pParse;
97275  for(i=0; i<pEList->nExpr; i++){
97276    Expr *p = pEList->a[i].pExpr;
97277    const char *zType;
97278#ifdef SQLITE_ENABLE_COLUMN_METADATA
97279    const char *zOrigDb = 0;
97280    const char *zOrigTab = 0;
97281    const char *zOrigCol = 0;
97282    zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
97283
97284    /* The vdbe must make its own copy of the column-type and other
97285    ** column specific strings, in case the schema is reset before this
97286    ** virtual machine is deleted.
97287    */
97288    sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
97289    sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
97290    sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
97291#else
97292    zType = columnType(&sNC, p, 0, 0, 0);
97293#endif
97294    sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
97295  }
97296#endif /* SQLITE_OMIT_DECLTYPE */
97297}
97298
97299/*
97300** Generate code that will tell the VDBE the names of columns
97301** in the result set.  This information is used to provide the
97302** azCol[] values in the callback.
97303*/
97304static void generateColumnNames(
97305  Parse *pParse,      /* Parser context */
97306  SrcList *pTabList,  /* List of tables */
97307  ExprList *pEList    /* Expressions defining the result set */
97308){
97309  Vdbe *v = pParse->pVdbe;
97310  int i, j;
97311  sqlite3 *db = pParse->db;
97312  int fullNames, shortNames;
97313
97314#ifndef SQLITE_OMIT_EXPLAIN
97315  /* If this is an EXPLAIN, skip this step */
97316  if( pParse->explain ){
97317    return;
97318  }
97319#endif
97320
97321  if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
97322  pParse->colNamesSet = 1;
97323  fullNames = (db->flags & SQLITE_FullColNames)!=0;
97324  shortNames = (db->flags & SQLITE_ShortColNames)!=0;
97325  sqlite3VdbeSetNumCols(v, pEList->nExpr);
97326  for(i=0; i<pEList->nExpr; i++){
97327    Expr *p;
97328    p = pEList->a[i].pExpr;
97329    if( NEVER(p==0) ) continue;
97330    if( pEList->a[i].zName ){
97331      char *zName = pEList->a[i].zName;
97332      sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
97333    }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
97334      Table *pTab;
97335      char *zCol;
97336      int iCol = p->iColumn;
97337      for(j=0; ALWAYS(j<pTabList->nSrc); j++){
97338        if( pTabList->a[j].iCursor==p->iTable ) break;
97339      }
97340      assert( j<pTabList->nSrc );
97341      pTab = pTabList->a[j].pTab;
97342      if( iCol<0 ) iCol = pTab->iPKey;
97343      assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
97344      if( iCol<0 ){
97345        zCol = "rowid";
97346      }else{
97347        zCol = pTab->aCol[iCol].zName;
97348      }
97349      if( !shortNames && !fullNames ){
97350        sqlite3VdbeSetColName(v, i, COLNAME_NAME,
97351            sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
97352      }else if( fullNames ){
97353        char *zName = 0;
97354        zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
97355        sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
97356      }else{
97357        sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
97358      }
97359    }else{
97360      sqlite3VdbeSetColName(v, i, COLNAME_NAME,
97361          sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
97362    }
97363  }
97364  generateColumnTypes(pParse, pTabList, pEList);
97365}
97366
97367/*
97368** Given a an expression list (which is really the list of expressions
97369** that form the result set of a SELECT statement) compute appropriate
97370** column names for a table that would hold the expression list.
97371**
97372** All column names will be unique.
97373**
97374** Only the column names are computed.  Column.zType, Column.zColl,
97375** and other fields of Column are zeroed.
97376**
97377** Return SQLITE_OK on success.  If a memory allocation error occurs,
97378** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
97379*/
97380static int selectColumnsFromExprList(
97381  Parse *pParse,          /* Parsing context */
97382  ExprList *pEList,       /* Expr list from which to derive column names */
97383  i16 *pnCol,             /* Write the number of columns here */
97384  Column **paCol          /* Write the new column list here */
97385){
97386  sqlite3 *db = pParse->db;   /* Database connection */
97387  int i, j;                   /* Loop counters */
97388  int cnt;                    /* Index added to make the name unique */
97389  Column *aCol, *pCol;        /* For looping over result columns */
97390  int nCol;                   /* Number of columns in the result set */
97391  Expr *p;                    /* Expression for a single result column */
97392  char *zName;                /* Column name */
97393  int nName;                  /* Size of name in zName[] */
97394
97395  if( pEList ){
97396    nCol = pEList->nExpr;
97397    aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
97398    testcase( aCol==0 );
97399  }else{
97400    nCol = 0;
97401    aCol = 0;
97402  }
97403  *pnCol = nCol;
97404  *paCol = aCol;
97405
97406  for(i=0, pCol=aCol; i<nCol; i++, pCol++){
97407    /* Get an appropriate name for the column
97408    */
97409    p = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
97410    if( (zName = pEList->a[i].zName)!=0 ){
97411      /* If the column contains an "AS <name>" phrase, use <name> as the name */
97412      zName = sqlite3DbStrDup(db, zName);
97413    }else{
97414      Expr *pColExpr = p;  /* The expression that is the result column name */
97415      Table *pTab;         /* Table associated with this expression */
97416      while( pColExpr->op==TK_DOT ){
97417        pColExpr = pColExpr->pRight;
97418        assert( pColExpr!=0 );
97419      }
97420      if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
97421        /* For columns use the column name name */
97422        int iCol = pColExpr->iColumn;
97423        pTab = pColExpr->pTab;
97424        if( iCol<0 ) iCol = pTab->iPKey;
97425        zName = sqlite3MPrintf(db, "%s",
97426                 iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
97427      }else if( pColExpr->op==TK_ID ){
97428        assert( !ExprHasProperty(pColExpr, EP_IntValue) );
97429        zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
97430      }else{
97431        /* Use the original text of the column expression as its name */
97432        zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
97433      }
97434    }
97435    if( db->mallocFailed ){
97436      sqlite3DbFree(db, zName);
97437      break;
97438    }
97439
97440    /* Make sure the column name is unique.  If the name is not unique,
97441    ** append a integer to the name so that it becomes unique.
97442    */
97443    nName = sqlite3Strlen30(zName);
97444    for(j=cnt=0; j<i; j++){
97445      if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
97446        char *zNewName;
97447        int k;
97448        for(k=nName-1; k>1 && sqlite3Isdigit(zName[k]); k--){}
97449        if( zName[k]==':' ) nName = k;
97450        zName[nName] = 0;
97451        zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
97452        sqlite3DbFree(db, zName);
97453        zName = zNewName;
97454        j = -1;
97455        if( zName==0 ) break;
97456      }
97457    }
97458    pCol->zName = zName;
97459  }
97460  if( db->mallocFailed ){
97461    for(j=0; j<i; j++){
97462      sqlite3DbFree(db, aCol[j].zName);
97463    }
97464    sqlite3DbFree(db, aCol);
97465    *paCol = 0;
97466    *pnCol = 0;
97467    return SQLITE_NOMEM;
97468  }
97469  return SQLITE_OK;
97470}
97471
97472/*
97473** Add type and collation information to a column list based on
97474** a SELECT statement.
97475**
97476** The column list presumably came from selectColumnNamesFromExprList().
97477** The column list has only names, not types or collations.  This
97478** routine goes through and adds the types and collations.
97479**
97480** This routine requires that all identifiers in the SELECT
97481** statement be resolved.
97482*/
97483static void selectAddColumnTypeAndCollation(
97484  Parse *pParse,        /* Parsing contexts */
97485  int nCol,             /* Number of columns */
97486  Column *aCol,         /* List of columns */
97487  Select *pSelect       /* SELECT used to determine types and collations */
97488){
97489  sqlite3 *db = pParse->db;
97490  NameContext sNC;
97491  Column *pCol;
97492  CollSeq *pColl;
97493  int i;
97494  Expr *p;
97495  struct ExprList_item *a;
97496
97497  assert( pSelect!=0 );
97498  assert( (pSelect->selFlags & SF_Resolved)!=0 );
97499  assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
97500  if( db->mallocFailed ) return;
97501  memset(&sNC, 0, sizeof(sNC));
97502  sNC.pSrcList = pSelect->pSrc;
97503  a = pSelect->pEList->a;
97504  for(i=0, pCol=aCol; i<nCol; i++, pCol++){
97505    p = a[i].pExpr;
97506    pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
97507    pCol->affinity = sqlite3ExprAffinity(p);
97508    if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
97509    pColl = sqlite3ExprCollSeq(pParse, p);
97510    if( pColl ){
97511      pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
97512    }
97513  }
97514}
97515
97516/*
97517** Given a SELECT statement, generate a Table structure that describes
97518** the result set of that SELECT.
97519*/
97520SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
97521  Table *pTab;
97522  sqlite3 *db = pParse->db;
97523  int savedFlags;
97524
97525  savedFlags = db->flags;
97526  db->flags &= ~SQLITE_FullColNames;
97527  db->flags |= SQLITE_ShortColNames;
97528  sqlite3SelectPrep(pParse, pSelect, 0);
97529  if( pParse->nErr ) return 0;
97530  while( pSelect->pPrior ) pSelect = pSelect->pPrior;
97531  db->flags = savedFlags;
97532  pTab = sqlite3DbMallocZero(db, sizeof(Table) );
97533  if( pTab==0 ){
97534    return 0;
97535  }
97536  /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
97537  ** is disabled */
97538  assert( db->lookaside.bEnabled==0 );
97539  pTab->nRef = 1;
97540  pTab->zName = 0;
97541  pTab->nRowEst = 1000000;
97542  selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
97543  selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
97544  pTab->iPKey = -1;
97545  if( db->mallocFailed ){
97546    sqlite3DeleteTable(db, pTab);
97547    return 0;
97548  }
97549  return pTab;
97550}
97551
97552/*
97553** Get a VDBE for the given parser context.  Create a new one if necessary.
97554** If an error occurs, return NULL and leave a message in pParse.
97555*/
97556SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
97557  Vdbe *v = pParse->pVdbe;
97558  if( v==0 ){
97559    v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
97560#ifndef SQLITE_OMIT_TRACE
97561    if( v ){
97562      sqlite3VdbeAddOp0(v, OP_Trace);
97563    }
97564#endif
97565  }
97566  return v;
97567}
97568
97569
97570/*
97571** Compute the iLimit and iOffset fields of the SELECT based on the
97572** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
97573** that appear in the original SQL statement after the LIMIT and OFFSET
97574** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset
97575** are the integer memory register numbers for counters used to compute
97576** the limit and offset.  If there is no limit and/or offset, then
97577** iLimit and iOffset are negative.
97578**
97579** This routine changes the values of iLimit and iOffset only if
97580** a limit or offset is defined by pLimit and pOffset.  iLimit and
97581** iOffset should have been preset to appropriate default values
97582** (usually but not always -1) prior to calling this routine.
97583** Only if pLimit!=0 or pOffset!=0 do the limit registers get
97584** redefined.  The UNION ALL operator uses this property to force
97585** the reuse of the same limit and offset registers across multiple
97586** SELECT statements.
97587*/
97588static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
97589  Vdbe *v = 0;
97590  int iLimit = 0;
97591  int iOffset;
97592  int addr1, n;
97593  if( p->iLimit ) return;
97594
97595  /*
97596  ** "LIMIT -1" always shows all rows.  There is some
97597  ** contraversy about what the correct behavior should be.
97598  ** The current implementation interprets "LIMIT 0" to mean
97599  ** no rows.
97600  */
97601  sqlite3ExprCacheClear(pParse);
97602  assert( p->pOffset==0 || p->pLimit!=0 );
97603  if( p->pLimit ){
97604    p->iLimit = iLimit = ++pParse->nMem;
97605    v = sqlite3GetVdbe(pParse);
97606    if( NEVER(v==0) ) return;  /* VDBE should have already been allocated */
97607    if( sqlite3ExprIsInteger(p->pLimit, &n) ){
97608      sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
97609      VdbeComment((v, "LIMIT counter"));
97610      if( n==0 ){
97611        sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
97612      }else{
97613        if( p->nSelectRow > (double)n ) p->nSelectRow = (double)n;
97614      }
97615    }else{
97616      sqlite3ExprCode(pParse, p->pLimit, iLimit);
97617      sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
97618      VdbeComment((v, "LIMIT counter"));
97619      sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
97620    }
97621    if( p->pOffset ){
97622      p->iOffset = iOffset = ++pParse->nMem;
97623      pParse->nMem++;   /* Allocate an extra register for limit+offset */
97624      sqlite3ExprCode(pParse, p->pOffset, iOffset);
97625      sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
97626      VdbeComment((v, "OFFSET counter"));
97627      addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
97628      sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
97629      sqlite3VdbeJumpHere(v, addr1);
97630      sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
97631      VdbeComment((v, "LIMIT+OFFSET"));
97632      addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
97633      sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
97634      sqlite3VdbeJumpHere(v, addr1);
97635    }
97636  }
97637}
97638
97639#ifndef SQLITE_OMIT_COMPOUND_SELECT
97640/*
97641** Return the appropriate collating sequence for the iCol-th column of
97642** the result set for the compound-select statement "p".  Return NULL if
97643** the column has no default collating sequence.
97644**
97645** The collating sequence for the compound select is taken from the
97646** left-most term of the select that has a collating sequence.
97647*/
97648static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
97649  CollSeq *pRet;
97650  if( p->pPrior ){
97651    pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
97652  }else{
97653    pRet = 0;
97654  }
97655  assert( iCol>=0 );
97656  if( pRet==0 && iCol<p->pEList->nExpr ){
97657    pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
97658  }
97659  return pRet;
97660}
97661#endif /* SQLITE_OMIT_COMPOUND_SELECT */
97662
97663/* Forward reference */
97664static int multiSelectOrderBy(
97665  Parse *pParse,        /* Parsing context */
97666  Select *p,            /* The right-most of SELECTs to be coded */
97667  SelectDest *pDest     /* What to do with query results */
97668);
97669
97670
97671#ifndef SQLITE_OMIT_COMPOUND_SELECT
97672/*
97673** This routine is called to process a compound query form from
97674** two or more separate queries using UNION, UNION ALL, EXCEPT, or
97675** INTERSECT
97676**
97677** "p" points to the right-most of the two queries.  the query on the
97678** left is p->pPrior.  The left query could also be a compound query
97679** in which case this routine will be called recursively.
97680**
97681** The results of the total query are to be written into a destination
97682** of type eDest with parameter iParm.
97683**
97684** Example 1:  Consider a three-way compound SQL statement.
97685**
97686**     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
97687**
97688** This statement is parsed up as follows:
97689**
97690**     SELECT c FROM t3
97691**      |
97692**      `----->  SELECT b FROM t2
97693**                |
97694**                `------>  SELECT a FROM t1
97695**
97696** The arrows in the diagram above represent the Select.pPrior pointer.
97697** So if this routine is called with p equal to the t3 query, then
97698** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
97699**
97700** Notice that because of the way SQLite parses compound SELECTs, the
97701** individual selects always group from left to right.
97702*/
97703static int multiSelect(
97704  Parse *pParse,        /* Parsing context */
97705  Select *p,            /* The right-most of SELECTs to be coded */
97706  SelectDest *pDest     /* What to do with query results */
97707){
97708  int rc = SQLITE_OK;   /* Success code from a subroutine */
97709  Select *pPrior;       /* Another SELECT immediately to our left */
97710  Vdbe *v;              /* Generate code to this VDBE */
97711  SelectDest dest;      /* Alternative data destination */
97712  Select *pDelete = 0;  /* Chain of simple selects to delete */
97713  sqlite3 *db;          /* Database connection */
97714#ifndef SQLITE_OMIT_EXPLAIN
97715  int iSub1;            /* EQP id of left-hand query */
97716  int iSub2;            /* EQP id of right-hand query */
97717#endif
97718
97719  /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
97720  ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
97721  */
97722  assert( p && p->pPrior );  /* Calling function guarantees this much */
97723  db = pParse->db;
97724  pPrior = p->pPrior;
97725  assert( pPrior->pRightmost!=pPrior );
97726  assert( pPrior->pRightmost==p->pRightmost );
97727  dest = *pDest;
97728  if( pPrior->pOrderBy ){
97729    sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
97730      selectOpName(p->op));
97731    rc = 1;
97732    goto multi_select_end;
97733  }
97734  if( pPrior->pLimit ){
97735    sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
97736      selectOpName(p->op));
97737    rc = 1;
97738    goto multi_select_end;
97739  }
97740
97741  v = sqlite3GetVdbe(pParse);
97742  assert( v!=0 );  /* The VDBE already created by calling function */
97743
97744  /* Create the destination temporary table if necessary
97745  */
97746  if( dest.eDest==SRT_EphemTab ){
97747    assert( p->pEList );
97748    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
97749    sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
97750    dest.eDest = SRT_Table;
97751  }
97752
97753  /* Make sure all SELECTs in the statement have the same number of elements
97754  ** in their result sets.
97755  */
97756  assert( p->pEList && pPrior->pEList );
97757  if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
97758    if( p->selFlags & SF_Values ){
97759      sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
97760    }else{
97761      sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
97762        " do not have the same number of result columns", selectOpName(p->op));
97763    }
97764    rc = 1;
97765    goto multi_select_end;
97766  }
97767
97768  /* Compound SELECTs that have an ORDER BY clause are handled separately.
97769  */
97770  if( p->pOrderBy ){
97771    return multiSelectOrderBy(pParse, p, pDest);
97772  }
97773
97774  /* Generate code for the left and right SELECT statements.
97775  */
97776  switch( p->op ){
97777    case TK_ALL: {
97778      int addr = 0;
97779      int nLimit;
97780      assert( !pPrior->pLimit );
97781      pPrior->iLimit = p->iLimit;
97782      pPrior->iOffset = p->iOffset;
97783      pPrior->pLimit = p->pLimit;
97784      pPrior->pOffset = p->pOffset;
97785      explainSetInteger(iSub1, pParse->iNextSelectId);
97786      rc = sqlite3Select(pParse, pPrior, &dest);
97787      p->pLimit = 0;
97788      p->pOffset = 0;
97789      if( rc ){
97790        goto multi_select_end;
97791      }
97792      p->pPrior = 0;
97793      p->iLimit = pPrior->iLimit;
97794      p->iOffset = pPrior->iOffset;
97795      if( p->iLimit ){
97796        addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
97797        VdbeComment((v, "Jump ahead if LIMIT reached"));
97798      }
97799      explainSetInteger(iSub2, pParse->iNextSelectId);
97800      rc = sqlite3Select(pParse, p, &dest);
97801      testcase( rc!=SQLITE_OK );
97802      pDelete = p->pPrior;
97803      p->pPrior = pPrior;
97804      p->nSelectRow += pPrior->nSelectRow;
97805      if( pPrior->pLimit
97806       && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
97807       && p->nSelectRow > (double)nLimit
97808      ){
97809        p->nSelectRow = (double)nLimit;
97810      }
97811      if( addr ){
97812        sqlite3VdbeJumpHere(v, addr);
97813      }
97814      break;
97815    }
97816    case TK_EXCEPT:
97817    case TK_UNION: {
97818      int unionTab;    /* Cursor number of the temporary table holding result */
97819      u8 op = 0;       /* One of the SRT_ operations to apply to self */
97820      int priorOp;     /* The SRT_ operation to apply to prior selects */
97821      Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
97822      int addr;
97823      SelectDest uniondest;
97824
97825      testcase( p->op==TK_EXCEPT );
97826      testcase( p->op==TK_UNION );
97827      priorOp = SRT_Union;
97828      if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
97829        /* We can reuse a temporary table generated by a SELECT to our
97830        ** right.
97831        */
97832        assert( p->pRightmost!=p );  /* Can only happen for leftward elements
97833                                     ** of a 3-way or more compound */
97834        assert( p->pLimit==0 );      /* Not allowed on leftward elements */
97835        assert( p->pOffset==0 );     /* Not allowed on leftward elements */
97836        unionTab = dest.iSDParm;
97837      }else{
97838        /* We will need to create our own temporary table to hold the
97839        ** intermediate results.
97840        */
97841        unionTab = pParse->nTab++;
97842        assert( p->pOrderBy==0 );
97843        addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
97844        assert( p->addrOpenEphm[0] == -1 );
97845        p->addrOpenEphm[0] = addr;
97846        p->pRightmost->selFlags |= SF_UsesEphemeral;
97847        assert( p->pEList );
97848      }
97849
97850      /* Code the SELECT statements to our left
97851      */
97852      assert( !pPrior->pOrderBy );
97853      sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
97854      explainSetInteger(iSub1, pParse->iNextSelectId);
97855      rc = sqlite3Select(pParse, pPrior, &uniondest);
97856      if( rc ){
97857        goto multi_select_end;
97858      }
97859
97860      /* Code the current SELECT statement
97861      */
97862      if( p->op==TK_EXCEPT ){
97863        op = SRT_Except;
97864      }else{
97865        assert( p->op==TK_UNION );
97866        op = SRT_Union;
97867      }
97868      p->pPrior = 0;
97869      pLimit = p->pLimit;
97870      p->pLimit = 0;
97871      pOffset = p->pOffset;
97872      p->pOffset = 0;
97873      uniondest.eDest = op;
97874      explainSetInteger(iSub2, pParse->iNextSelectId);
97875      rc = sqlite3Select(pParse, p, &uniondest);
97876      testcase( rc!=SQLITE_OK );
97877      /* Query flattening in sqlite3Select() might refill p->pOrderBy.
97878      ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
97879      sqlite3ExprListDelete(db, p->pOrderBy);
97880      pDelete = p->pPrior;
97881      p->pPrior = pPrior;
97882      p->pOrderBy = 0;
97883      if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
97884      sqlite3ExprDelete(db, p->pLimit);
97885      p->pLimit = pLimit;
97886      p->pOffset = pOffset;
97887      p->iLimit = 0;
97888      p->iOffset = 0;
97889
97890      /* Convert the data in the temporary table into whatever form
97891      ** it is that we currently need.
97892      */
97893      assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
97894      if( dest.eDest!=priorOp ){
97895        int iCont, iBreak, iStart;
97896        assert( p->pEList );
97897        if( dest.eDest==SRT_Output ){
97898          Select *pFirst = p;
97899          while( pFirst->pPrior ) pFirst = pFirst->pPrior;
97900          generateColumnNames(pParse, 0, pFirst->pEList);
97901        }
97902        iBreak = sqlite3VdbeMakeLabel(v);
97903        iCont = sqlite3VdbeMakeLabel(v);
97904        computeLimitRegisters(pParse, p, iBreak);
97905        sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
97906        iStart = sqlite3VdbeCurrentAddr(v);
97907        selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
97908                        0, 0, &dest, iCont, iBreak);
97909        sqlite3VdbeResolveLabel(v, iCont);
97910        sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
97911        sqlite3VdbeResolveLabel(v, iBreak);
97912        sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
97913      }
97914      break;
97915    }
97916    default: assert( p->op==TK_INTERSECT ); {
97917      int tab1, tab2;
97918      int iCont, iBreak, iStart;
97919      Expr *pLimit, *pOffset;
97920      int addr;
97921      SelectDest intersectdest;
97922      int r1;
97923
97924      /* INTERSECT is different from the others since it requires
97925      ** two temporary tables.  Hence it has its own case.  Begin
97926      ** by allocating the tables we will need.
97927      */
97928      tab1 = pParse->nTab++;
97929      tab2 = pParse->nTab++;
97930      assert( p->pOrderBy==0 );
97931
97932      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
97933      assert( p->addrOpenEphm[0] == -1 );
97934      p->addrOpenEphm[0] = addr;
97935      p->pRightmost->selFlags |= SF_UsesEphemeral;
97936      assert( p->pEList );
97937
97938      /* Code the SELECTs to our left into temporary table "tab1".
97939      */
97940      sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
97941      explainSetInteger(iSub1, pParse->iNextSelectId);
97942      rc = sqlite3Select(pParse, pPrior, &intersectdest);
97943      if( rc ){
97944        goto multi_select_end;
97945      }
97946
97947      /* Code the current SELECT into temporary table "tab2"
97948      */
97949      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
97950      assert( p->addrOpenEphm[1] == -1 );
97951      p->addrOpenEphm[1] = addr;
97952      p->pPrior = 0;
97953      pLimit = p->pLimit;
97954      p->pLimit = 0;
97955      pOffset = p->pOffset;
97956      p->pOffset = 0;
97957      intersectdest.iSDParm = tab2;
97958      explainSetInteger(iSub2, pParse->iNextSelectId);
97959      rc = sqlite3Select(pParse, p, &intersectdest);
97960      testcase( rc!=SQLITE_OK );
97961      pDelete = p->pPrior;
97962      p->pPrior = pPrior;
97963      if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
97964      sqlite3ExprDelete(db, p->pLimit);
97965      p->pLimit = pLimit;
97966      p->pOffset = pOffset;
97967
97968      /* Generate code to take the intersection of the two temporary
97969      ** tables.
97970      */
97971      assert( p->pEList );
97972      if( dest.eDest==SRT_Output ){
97973        Select *pFirst = p;
97974        while( pFirst->pPrior ) pFirst = pFirst->pPrior;
97975        generateColumnNames(pParse, 0, pFirst->pEList);
97976      }
97977      iBreak = sqlite3VdbeMakeLabel(v);
97978      iCont = sqlite3VdbeMakeLabel(v);
97979      computeLimitRegisters(pParse, p, iBreak);
97980      sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
97981      r1 = sqlite3GetTempReg(pParse);
97982      iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
97983      sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
97984      sqlite3ReleaseTempReg(pParse, r1);
97985      selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
97986                      0, 0, &dest, iCont, iBreak);
97987      sqlite3VdbeResolveLabel(v, iCont);
97988      sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
97989      sqlite3VdbeResolveLabel(v, iBreak);
97990      sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
97991      sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
97992      break;
97993    }
97994  }
97995
97996  explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
97997
97998  /* Compute collating sequences used by
97999  ** temporary tables needed to implement the compound select.
98000  ** Attach the KeyInfo structure to all temporary tables.
98001  **
98002  ** This section is run by the right-most SELECT statement only.
98003  ** SELECT statements to the left always skip this part.  The right-most
98004  ** SELECT might also skip this part if it has no ORDER BY clause and
98005  ** no temp tables are required.
98006  */
98007  if( p->selFlags & SF_UsesEphemeral ){
98008    int i;                        /* Loop counter */
98009    KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
98010    Select *pLoop;                /* For looping through SELECT statements */
98011    CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
98012    int nCol;                     /* Number of columns in result set */
98013
98014    assert( p->pRightmost==p );
98015    nCol = p->pEList->nExpr;
98016    pKeyInfo = sqlite3DbMallocZero(db,
98017                       sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
98018    if( !pKeyInfo ){
98019      rc = SQLITE_NOMEM;
98020      goto multi_select_end;
98021    }
98022
98023    pKeyInfo->enc = ENC(db);
98024    pKeyInfo->nField = (u16)nCol;
98025
98026    for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
98027      *apColl = multiSelectCollSeq(pParse, p, i);
98028      if( 0==*apColl ){
98029        *apColl = db->pDfltColl;
98030      }
98031    }
98032    pKeyInfo->aSortOrder = (u8*)apColl;
98033
98034    for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
98035      for(i=0; i<2; i++){
98036        int addr = pLoop->addrOpenEphm[i];
98037        if( addr<0 ){
98038          /* If [0] is unused then [1] is also unused.  So we can
98039          ** always safely abort as soon as the first unused slot is found */
98040          assert( pLoop->addrOpenEphm[1]<0 );
98041          break;
98042        }
98043        sqlite3VdbeChangeP2(v, addr, nCol);
98044        sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
98045        pLoop->addrOpenEphm[i] = -1;
98046      }
98047    }
98048    sqlite3DbFree(db, pKeyInfo);
98049  }
98050
98051multi_select_end:
98052  pDest->iSdst = dest.iSdst;
98053  pDest->nSdst = dest.nSdst;
98054  sqlite3SelectDelete(db, pDelete);
98055  return rc;
98056}
98057#endif /* SQLITE_OMIT_COMPOUND_SELECT */
98058
98059/*
98060** Code an output subroutine for a coroutine implementation of a
98061** SELECT statment.
98062**
98063** The data to be output is contained in pIn->iSdst.  There are
98064** pIn->nSdst columns to be output.  pDest is where the output should
98065** be sent.
98066**
98067** regReturn is the number of the register holding the subroutine
98068** return address.
98069**
98070** If regPrev>0 then it is the first register in a vector that
98071** records the previous output.  mem[regPrev] is a flag that is false
98072** if there has been no previous output.  If regPrev>0 then code is
98073** generated to suppress duplicates.  pKeyInfo is used for comparing
98074** keys.
98075**
98076** If the LIMIT found in p->iLimit is reached, jump immediately to
98077** iBreak.
98078*/
98079static int generateOutputSubroutine(
98080  Parse *pParse,          /* Parsing context */
98081  Select *p,              /* The SELECT statement */
98082  SelectDest *pIn,        /* Coroutine supplying data */
98083  SelectDest *pDest,      /* Where to send the data */
98084  int regReturn,          /* The return address register */
98085  int regPrev,            /* Previous result register.  No uniqueness if 0 */
98086  KeyInfo *pKeyInfo,      /* For comparing with previous entry */
98087  int p4type,             /* The p4 type for pKeyInfo */
98088  int iBreak              /* Jump here if we hit the LIMIT */
98089){
98090  Vdbe *v = pParse->pVdbe;
98091  int iContinue;
98092  int addr;
98093
98094  addr = sqlite3VdbeCurrentAddr(v);
98095  iContinue = sqlite3VdbeMakeLabel(v);
98096
98097  /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
98098  */
98099  if( regPrev ){
98100    int j1, j2;
98101    j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
98102    j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
98103                              (char*)pKeyInfo, p4type);
98104    sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
98105    sqlite3VdbeJumpHere(v, j1);
98106    sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
98107    sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
98108  }
98109  if( pParse->db->mallocFailed ) return 0;
98110
98111  /* Suppress the first OFFSET entries if there is an OFFSET clause
98112  */
98113  codeOffset(v, p, iContinue);
98114
98115  switch( pDest->eDest ){
98116    /* Store the result as data using a unique key.
98117    */
98118    case SRT_Table:
98119    case SRT_EphemTab: {
98120      int r1 = sqlite3GetTempReg(pParse);
98121      int r2 = sqlite3GetTempReg(pParse);
98122      testcase( pDest->eDest==SRT_Table );
98123      testcase( pDest->eDest==SRT_EphemTab );
98124      sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
98125      sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
98126      sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
98127      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
98128      sqlite3ReleaseTempReg(pParse, r2);
98129      sqlite3ReleaseTempReg(pParse, r1);
98130      break;
98131    }
98132
98133#ifndef SQLITE_OMIT_SUBQUERY
98134    /* If we are creating a set for an "expr IN (SELECT ...)" construct,
98135    ** then there should be a single item on the stack.  Write this
98136    ** item into the set table with bogus data.
98137    */
98138    case SRT_Set: {
98139      int r1;
98140      assert( pIn->nSdst==1 );
98141      pDest->affSdst =
98142         sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affSdst);
98143      r1 = sqlite3GetTempReg(pParse);
98144      sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, 1, r1, &pDest->affSdst,1);
98145      sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, 1);
98146      sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1);
98147      sqlite3ReleaseTempReg(pParse, r1);
98148      break;
98149    }
98150
98151#if 0  /* Never occurs on an ORDER BY query */
98152    /* If any row exist in the result set, record that fact and abort.
98153    */
98154    case SRT_Exists: {
98155      sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iSDParm);
98156      /* The LIMIT clause will terminate the loop for us */
98157      break;
98158    }
98159#endif
98160
98161    /* If this is a scalar select that is part of an expression, then
98162    ** store the results in the appropriate memory cell and break out
98163    ** of the scan loop.
98164    */
98165    case SRT_Mem: {
98166      assert( pIn->nSdst==1 );
98167      sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
98168      /* The LIMIT clause will jump out of the loop for us */
98169      break;
98170    }
98171#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
98172
98173    /* The results are stored in a sequence of registers
98174    ** starting at pDest->iSdst.  Then the co-routine yields.
98175    */
98176    case SRT_Coroutine: {
98177      if( pDest->iSdst==0 ){
98178        pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
98179        pDest->nSdst = pIn->nSdst;
98180      }
98181      sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pDest->nSdst);
98182      sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
98183      break;
98184    }
98185
98186    /* If none of the above, then the result destination must be
98187    ** SRT_Output.  This routine is never called with any other
98188    ** destination other than the ones handled above or SRT_Output.
98189    **
98190    ** For SRT_Output, results are stored in a sequence of registers.
98191    ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
98192    ** return the next row of result.
98193    */
98194    default: {
98195      assert( pDest->eDest==SRT_Output );
98196      sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
98197      sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
98198      break;
98199    }
98200  }
98201
98202  /* Jump to the end of the loop if the LIMIT is reached.
98203  */
98204  if( p->iLimit ){
98205    sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
98206  }
98207
98208  /* Generate the subroutine return
98209  */
98210  sqlite3VdbeResolveLabel(v, iContinue);
98211  sqlite3VdbeAddOp1(v, OP_Return, regReturn);
98212
98213  return addr;
98214}
98215
98216/*
98217** Alternative compound select code generator for cases when there
98218** is an ORDER BY clause.
98219**
98220** We assume a query of the following form:
98221**
98222**      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
98223**
98224** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
98225** is to code both <selectA> and <selectB> with the ORDER BY clause as
98226** co-routines.  Then run the co-routines in parallel and merge the results
98227** into the output.  In addition to the two coroutines (called selectA and
98228** selectB) there are 7 subroutines:
98229**
98230**    outA:    Move the output of the selectA coroutine into the output
98231**             of the compound query.
98232**
98233**    outB:    Move the output of the selectB coroutine into the output
98234**             of the compound query.  (Only generated for UNION and
98235**             UNION ALL.  EXCEPT and INSERTSECT never output a row that
98236**             appears only in B.)
98237**
98238**    AltB:    Called when there is data from both coroutines and A<B.
98239**
98240**    AeqB:    Called when there is data from both coroutines and A==B.
98241**
98242**    AgtB:    Called when there is data from both coroutines and A>B.
98243**
98244**    EofA:    Called when data is exhausted from selectA.
98245**
98246**    EofB:    Called when data is exhausted from selectB.
98247**
98248** The implementation of the latter five subroutines depend on which
98249** <operator> is used:
98250**
98251**
98252**             UNION ALL         UNION            EXCEPT          INTERSECT
98253**          -------------  -----------------  --------------  -----------------
98254**   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
98255**
98256**   AeqB:   outA, nextA         nextA             nextA         outA, nextA
98257**
98258**   AgtB:   outB, nextB      outB, nextB          nextB            nextB
98259**
98260**   EofA:   outB, nextB      outB, nextB          halt             halt
98261**
98262**   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
98263**
98264** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
98265** causes an immediate jump to EofA and an EOF on B following nextB causes
98266** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
98267** following nextX causes a jump to the end of the select processing.
98268**
98269** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
98270** within the output subroutine.  The regPrev register set holds the previously
98271** output value.  A comparison is made against this value and the output
98272** is skipped if the next results would be the same as the previous.
98273**
98274** The implementation plan is to implement the two coroutines and seven
98275** subroutines first, then put the control logic at the bottom.  Like this:
98276**
98277**          goto Init
98278**     coA: coroutine for left query (A)
98279**     coB: coroutine for right query (B)
98280**    outA: output one row of A
98281**    outB: output one row of B (UNION and UNION ALL only)
98282**    EofA: ...
98283**    EofB: ...
98284**    AltB: ...
98285**    AeqB: ...
98286**    AgtB: ...
98287**    Init: initialize coroutine registers
98288**          yield coA
98289**          if eof(A) goto EofA
98290**          yield coB
98291**          if eof(B) goto EofB
98292**    Cmpr: Compare A, B
98293**          Jump AltB, AeqB, AgtB
98294**     End: ...
98295**
98296** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
98297** actually called using Gosub and they do not Return.  EofA and EofB loop
98298** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
98299** and AgtB jump to either L2 or to one of EofA or EofB.
98300*/
98301#ifndef SQLITE_OMIT_COMPOUND_SELECT
98302static int multiSelectOrderBy(
98303  Parse *pParse,        /* Parsing context */
98304  Select *p,            /* The right-most of SELECTs to be coded */
98305  SelectDest *pDest     /* What to do with query results */
98306){
98307  int i, j;             /* Loop counters */
98308  Select *pPrior;       /* Another SELECT immediately to our left */
98309  Vdbe *v;              /* Generate code to this VDBE */
98310  SelectDest destA;     /* Destination for coroutine A */
98311  SelectDest destB;     /* Destination for coroutine B */
98312  int regAddrA;         /* Address register for select-A coroutine */
98313  int regEofA;          /* Flag to indicate when select-A is complete */
98314  int regAddrB;         /* Address register for select-B coroutine */
98315  int regEofB;          /* Flag to indicate when select-B is complete */
98316  int addrSelectA;      /* Address of the select-A coroutine */
98317  int addrSelectB;      /* Address of the select-B coroutine */
98318  int regOutA;          /* Address register for the output-A subroutine */
98319  int regOutB;          /* Address register for the output-B subroutine */
98320  int addrOutA;         /* Address of the output-A subroutine */
98321  int addrOutB = 0;     /* Address of the output-B subroutine */
98322  int addrEofA;         /* Address of the select-A-exhausted subroutine */
98323  int addrEofB;         /* Address of the select-B-exhausted subroutine */
98324  int addrAltB;         /* Address of the A<B subroutine */
98325  int addrAeqB;         /* Address of the A==B subroutine */
98326  int addrAgtB;         /* Address of the A>B subroutine */
98327  int regLimitA;        /* Limit register for select-A */
98328  int regLimitB;        /* Limit register for select-A */
98329  int regPrev;          /* A range of registers to hold previous output */
98330  int savedLimit;       /* Saved value of p->iLimit */
98331  int savedOffset;      /* Saved value of p->iOffset */
98332  int labelCmpr;        /* Label for the start of the merge algorithm */
98333  int labelEnd;         /* Label for the end of the overall SELECT stmt */
98334  int j1;               /* Jump instructions that get retargetted */
98335  int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
98336  KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
98337  KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
98338  sqlite3 *db;          /* Database connection */
98339  ExprList *pOrderBy;   /* The ORDER BY clause */
98340  int nOrderBy;         /* Number of terms in the ORDER BY clause */
98341  int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
98342#ifndef SQLITE_OMIT_EXPLAIN
98343  int iSub1;            /* EQP id of left-hand query */
98344  int iSub2;            /* EQP id of right-hand query */
98345#endif
98346
98347  assert( p->pOrderBy!=0 );
98348  assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
98349  db = pParse->db;
98350  v = pParse->pVdbe;
98351  assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
98352  labelEnd = sqlite3VdbeMakeLabel(v);
98353  labelCmpr = sqlite3VdbeMakeLabel(v);
98354
98355
98356  /* Patch up the ORDER BY clause
98357  */
98358  op = p->op;
98359  pPrior = p->pPrior;
98360  assert( pPrior->pOrderBy==0 );
98361  pOrderBy = p->pOrderBy;
98362  assert( pOrderBy );
98363  nOrderBy = pOrderBy->nExpr;
98364
98365  /* For operators other than UNION ALL we have to make sure that
98366  ** the ORDER BY clause covers every term of the result set.  Add
98367  ** terms to the ORDER BY clause as necessary.
98368  */
98369  if( op!=TK_ALL ){
98370    for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
98371      struct ExprList_item *pItem;
98372      for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
98373        assert( pItem->iOrderByCol>0 );
98374        if( pItem->iOrderByCol==i ) break;
98375      }
98376      if( j==nOrderBy ){
98377        Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
98378        if( pNew==0 ) return SQLITE_NOMEM;
98379        pNew->flags |= EP_IntValue;
98380        pNew->u.iValue = i;
98381        pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
98382        if( pOrderBy ) pOrderBy->a[nOrderBy++].iOrderByCol = (u16)i;
98383      }
98384    }
98385  }
98386
98387  /* Compute the comparison permutation and keyinfo that is used with
98388  ** the permutation used to determine if the next
98389  ** row of results comes from selectA or selectB.  Also add explicit
98390  ** collations to the ORDER BY clause terms so that when the subqueries
98391  ** to the right and the left are evaluated, they use the correct
98392  ** collation.
98393  */
98394  aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
98395  if( aPermute ){
98396    struct ExprList_item *pItem;
98397    for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
98398      assert( pItem->iOrderByCol>0  && pItem->iOrderByCol<=p->pEList->nExpr );
98399      aPermute[i] = pItem->iOrderByCol - 1;
98400    }
98401    pKeyMerge =
98402      sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
98403    if( pKeyMerge ){
98404      pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
98405      pKeyMerge->nField = (u16)nOrderBy;
98406      pKeyMerge->enc = ENC(db);
98407      for(i=0; i<nOrderBy; i++){
98408        CollSeq *pColl;
98409        Expr *pTerm = pOrderBy->a[i].pExpr;
98410        if( pTerm->flags & EP_Collate ){
98411          pColl = sqlite3ExprCollSeq(pParse, pTerm);
98412        }else{
98413          pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
98414          if( pColl==0 ) pColl = db->pDfltColl;
98415          pOrderBy->a[i].pExpr =
98416             sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
98417        }
98418        pKeyMerge->aColl[i] = pColl;
98419        pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
98420      }
98421    }
98422  }else{
98423    pKeyMerge = 0;
98424  }
98425
98426  /* Reattach the ORDER BY clause to the query.
98427  */
98428  p->pOrderBy = pOrderBy;
98429  pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
98430
98431  /* Allocate a range of temporary registers and the KeyInfo needed
98432  ** for the logic that removes duplicate result rows when the
98433  ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
98434  */
98435  if( op==TK_ALL ){
98436    regPrev = 0;
98437  }else{
98438    int nExpr = p->pEList->nExpr;
98439    assert( nOrderBy>=nExpr || db->mallocFailed );
98440    regPrev = pParse->nMem+1;
98441    pParse->nMem += nExpr+1;
98442    sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
98443    pKeyDup = sqlite3DbMallocZero(db,
98444                  sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
98445    if( pKeyDup ){
98446      pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
98447      pKeyDup->nField = (u16)nExpr;
98448      pKeyDup->enc = ENC(db);
98449      for(i=0; i<nExpr; i++){
98450        pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
98451        pKeyDup->aSortOrder[i] = 0;
98452      }
98453    }
98454  }
98455
98456  /* Separate the left and the right query from one another
98457  */
98458  p->pPrior = 0;
98459  sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
98460  if( pPrior->pPrior==0 ){
98461    sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
98462  }
98463
98464  /* Compute the limit registers */
98465  computeLimitRegisters(pParse, p, labelEnd);
98466  if( p->iLimit && op==TK_ALL ){
98467    regLimitA = ++pParse->nMem;
98468    regLimitB = ++pParse->nMem;
98469    sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
98470                                  regLimitA);
98471    sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
98472  }else{
98473    regLimitA = regLimitB = 0;
98474  }
98475  sqlite3ExprDelete(db, p->pLimit);
98476  p->pLimit = 0;
98477  sqlite3ExprDelete(db, p->pOffset);
98478  p->pOffset = 0;
98479
98480  regAddrA = ++pParse->nMem;
98481  regEofA = ++pParse->nMem;
98482  regAddrB = ++pParse->nMem;
98483  regEofB = ++pParse->nMem;
98484  regOutA = ++pParse->nMem;
98485  regOutB = ++pParse->nMem;
98486  sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
98487  sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
98488
98489  /* Jump past the various subroutines and coroutines to the main
98490  ** merge loop
98491  */
98492  j1 = sqlite3VdbeAddOp0(v, OP_Goto);
98493  addrSelectA = sqlite3VdbeCurrentAddr(v);
98494
98495
98496  /* Generate a coroutine to evaluate the SELECT statement to the
98497  ** left of the compound operator - the "A" select.
98498  */
98499  VdbeNoopComment((v, "Begin coroutine for left SELECT"));
98500  pPrior->iLimit = regLimitA;
98501  explainSetInteger(iSub1, pParse->iNextSelectId);
98502  sqlite3Select(pParse, pPrior, &destA);
98503  sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
98504  sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
98505  VdbeNoopComment((v, "End coroutine for left SELECT"));
98506
98507  /* Generate a coroutine to evaluate the SELECT statement on
98508  ** the right - the "B" select
98509  */
98510  addrSelectB = sqlite3VdbeCurrentAddr(v);
98511  VdbeNoopComment((v, "Begin coroutine for right SELECT"));
98512  savedLimit = p->iLimit;
98513  savedOffset = p->iOffset;
98514  p->iLimit = regLimitB;
98515  p->iOffset = 0;
98516  explainSetInteger(iSub2, pParse->iNextSelectId);
98517  sqlite3Select(pParse, p, &destB);
98518  p->iLimit = savedLimit;
98519  p->iOffset = savedOffset;
98520  sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
98521  sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
98522  VdbeNoopComment((v, "End coroutine for right SELECT"));
98523
98524  /* Generate a subroutine that outputs the current row of the A
98525  ** select as the next output row of the compound select.
98526  */
98527  VdbeNoopComment((v, "Output routine for A"));
98528  addrOutA = generateOutputSubroutine(pParse,
98529                 p, &destA, pDest, regOutA,
98530                 regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
98531
98532  /* Generate a subroutine that outputs the current row of the B
98533  ** select as the next output row of the compound select.
98534  */
98535  if( op==TK_ALL || op==TK_UNION ){
98536    VdbeNoopComment((v, "Output routine for B"));
98537    addrOutB = generateOutputSubroutine(pParse,
98538                 p, &destB, pDest, regOutB,
98539                 regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
98540  }
98541
98542  /* Generate a subroutine to run when the results from select A
98543  ** are exhausted and only data in select B remains.
98544  */
98545  VdbeNoopComment((v, "eof-A subroutine"));
98546  if( op==TK_EXCEPT || op==TK_INTERSECT ){
98547    addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
98548  }else{
98549    addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
98550    sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
98551    sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
98552    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
98553    p->nSelectRow += pPrior->nSelectRow;
98554  }
98555
98556  /* Generate a subroutine to run when the results from select B
98557  ** are exhausted and only data in select A remains.
98558  */
98559  if( op==TK_INTERSECT ){
98560    addrEofB = addrEofA;
98561    if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
98562  }else{
98563    VdbeNoopComment((v, "eof-B subroutine"));
98564    addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
98565    sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
98566    sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
98567    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
98568  }
98569
98570  /* Generate code to handle the case of A<B
98571  */
98572  VdbeNoopComment((v, "A-lt-B subroutine"));
98573  addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
98574  sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
98575  sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
98576  sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
98577
98578  /* Generate code to handle the case of A==B
98579  */
98580  if( op==TK_ALL ){
98581    addrAeqB = addrAltB;
98582  }else if( op==TK_INTERSECT ){
98583    addrAeqB = addrAltB;
98584    addrAltB++;
98585  }else{
98586    VdbeNoopComment((v, "A-eq-B subroutine"));
98587    addrAeqB =
98588    sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
98589    sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
98590    sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
98591  }
98592
98593  /* Generate code to handle the case of A>B
98594  */
98595  VdbeNoopComment((v, "A-gt-B subroutine"));
98596  addrAgtB = sqlite3VdbeCurrentAddr(v);
98597  if( op==TK_ALL || op==TK_UNION ){
98598    sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
98599  }
98600  sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
98601  sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
98602  sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
98603
98604  /* This code runs once to initialize everything.
98605  */
98606  sqlite3VdbeJumpHere(v, j1);
98607  sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
98608  sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
98609  sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
98610  sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
98611  sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
98612  sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
98613
98614  /* Implement the main merge loop
98615  */
98616  sqlite3VdbeResolveLabel(v, labelCmpr);
98617  sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
98618  sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
98619                         (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
98620  sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
98621  sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
98622
98623  /* Jump to the this point in order to terminate the query.
98624  */
98625  sqlite3VdbeResolveLabel(v, labelEnd);
98626
98627  /* Set the number of output columns
98628  */
98629  if( pDest->eDest==SRT_Output ){
98630    Select *pFirst = pPrior;
98631    while( pFirst->pPrior ) pFirst = pFirst->pPrior;
98632    generateColumnNames(pParse, 0, pFirst->pEList);
98633  }
98634
98635  /* Reassembly the compound query so that it will be freed correctly
98636  ** by the calling function */
98637  if( p->pPrior ){
98638    sqlite3SelectDelete(db, p->pPrior);
98639  }
98640  p->pPrior = pPrior;
98641
98642  /*** TBD:  Insert subroutine calls to close cursors on incomplete
98643  **** subqueries ****/
98644  explainComposite(pParse, p->op, iSub1, iSub2, 0);
98645  return SQLITE_OK;
98646}
98647#endif
98648
98649#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
98650/* Forward Declarations */
98651static void substExprList(sqlite3*, ExprList*, int, ExprList*);
98652static void substSelect(sqlite3*, Select *, int, ExprList *);
98653
98654/*
98655** Scan through the expression pExpr.  Replace every reference to
98656** a column in table number iTable with a copy of the iColumn-th
98657** entry in pEList.  (But leave references to the ROWID column
98658** unchanged.)
98659**
98660** This routine is part of the flattening procedure.  A subquery
98661** whose result set is defined by pEList appears as entry in the
98662** FROM clause of a SELECT such that the VDBE cursor assigned to that
98663** FORM clause entry is iTable.  This routine make the necessary
98664** changes to pExpr so that it refers directly to the source table
98665** of the subquery rather the result set of the subquery.
98666*/
98667static Expr *substExpr(
98668  sqlite3 *db,        /* Report malloc errors to this connection */
98669  Expr *pExpr,        /* Expr in which substitution occurs */
98670  int iTable,         /* Table to be substituted */
98671  ExprList *pEList    /* Substitute expressions */
98672){
98673  if( pExpr==0 ) return 0;
98674  if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
98675    if( pExpr->iColumn<0 ){
98676      pExpr->op = TK_NULL;
98677    }else{
98678      Expr *pNew;
98679      assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
98680      assert( pExpr->pLeft==0 && pExpr->pRight==0 );
98681      pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
98682      sqlite3ExprDelete(db, pExpr);
98683      pExpr = pNew;
98684    }
98685  }else{
98686    pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
98687    pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
98688    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
98689      substSelect(db, pExpr->x.pSelect, iTable, pEList);
98690    }else{
98691      substExprList(db, pExpr->x.pList, iTable, pEList);
98692    }
98693  }
98694  return pExpr;
98695}
98696static void substExprList(
98697  sqlite3 *db,         /* Report malloc errors here */
98698  ExprList *pList,     /* List to scan and in which to make substitutes */
98699  int iTable,          /* Table to be substituted */
98700  ExprList *pEList     /* Substitute values */
98701){
98702  int i;
98703  if( pList==0 ) return;
98704  for(i=0; i<pList->nExpr; i++){
98705    pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
98706  }
98707}
98708static void substSelect(
98709  sqlite3 *db,         /* Report malloc errors here */
98710  Select *p,           /* SELECT statement in which to make substitutions */
98711  int iTable,          /* Table to be replaced */
98712  ExprList *pEList     /* Substitute values */
98713){
98714  SrcList *pSrc;
98715  struct SrcList_item *pItem;
98716  int i;
98717  if( !p ) return;
98718  substExprList(db, p->pEList, iTable, pEList);
98719  substExprList(db, p->pGroupBy, iTable, pEList);
98720  substExprList(db, p->pOrderBy, iTable, pEList);
98721  p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
98722  p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
98723  substSelect(db, p->pPrior, iTable, pEList);
98724  pSrc = p->pSrc;
98725  assert( pSrc );  /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
98726  if( ALWAYS(pSrc) ){
98727    for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
98728      substSelect(db, pItem->pSelect, iTable, pEList);
98729    }
98730  }
98731}
98732#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
98733
98734#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
98735/*
98736** This routine attempts to flatten subqueries as a performance optimization.
98737** This routine returns 1 if it makes changes and 0 if no flattening occurs.
98738**
98739** To understand the concept of flattening, consider the following
98740** query:
98741**
98742**     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
98743**
98744** The default way of implementing this query is to execute the
98745** subquery first and store the results in a temporary table, then
98746** run the outer query on that temporary table.  This requires two
98747** passes over the data.  Furthermore, because the temporary table
98748** has no indices, the WHERE clause on the outer query cannot be
98749** optimized.
98750**
98751** This routine attempts to rewrite queries such as the above into
98752** a single flat select, like this:
98753**
98754**     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
98755**
98756** The code generated for this simpification gives the same result
98757** but only has to scan the data once.  And because indices might
98758** exist on the table t1, a complete scan of the data might be
98759** avoided.
98760**
98761** Flattening is only attempted if all of the following are true:
98762**
98763**   (1)  The subquery and the outer query do not both use aggregates.
98764**
98765**   (2)  The subquery is not an aggregate or the outer query is not a join.
98766**
98767**   (3)  The subquery is not the right operand of a left outer join
98768**        (Originally ticket #306.  Strengthened by ticket #3300)
98769**
98770**   (4)  The subquery is not DISTINCT.
98771**
98772**  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT
98773**        sub-queries that were excluded from this optimization. Restriction
98774**        (4) has since been expanded to exclude all DISTINCT subqueries.
98775**
98776**   (6)  The subquery does not use aggregates or the outer query is not
98777**        DISTINCT.
98778**
98779**   (7)  The subquery has a FROM clause.  TODO:  For subqueries without
98780**        A FROM clause, consider adding a FROM close with the special
98781**        table sqlite_once that consists of a single row containing a
98782**        single NULL.
98783**
98784**   (8)  The subquery does not use LIMIT or the outer query is not a join.
98785**
98786**   (9)  The subquery does not use LIMIT or the outer query does not use
98787**        aggregates.
98788**
98789**  (10)  The subquery does not use aggregates or the outer query does not
98790**        use LIMIT.
98791**
98792**  (11)  The subquery and the outer query do not both have ORDER BY clauses.
98793**
98794**  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
98795**        a separate restriction deriving from ticket #350.
98796**
98797**  (13)  The subquery and outer query do not both use LIMIT.
98798**
98799**  (14)  The subquery does not use OFFSET.
98800**
98801**  (15)  The outer query is not part of a compound select or the
98802**        subquery does not have a LIMIT clause.
98803**        (See ticket #2339 and ticket [02a8e81d44]).
98804**
98805**  (16)  The outer query is not an aggregate or the subquery does
98806**        not contain ORDER BY.  (Ticket #2942)  This used to not matter
98807**        until we introduced the group_concat() function.
98808**
98809**  (17)  The sub-query is not a compound select, or it is a UNION ALL
98810**        compound clause made up entirely of non-aggregate queries, and
98811**        the parent query:
98812**
98813**          * is not itself part of a compound select,
98814**          * is not an aggregate or DISTINCT query, and
98815**          * is not a join
98816**
98817**        The parent and sub-query may contain WHERE clauses. Subject to
98818**        rules (11), (13) and (14), they may also contain ORDER BY,
98819**        LIMIT and OFFSET clauses.  The subquery cannot use any compound
98820**        operator other than UNION ALL because all the other compound
98821**        operators have an implied DISTINCT which is disallowed by
98822**        restriction (4).
98823**
98824**        Also, each component of the sub-query must return the same number
98825**        of result columns. This is actually a requirement for any compound
98826**        SELECT statement, but all the code here does is make sure that no
98827**        such (illegal) sub-query is flattened. The caller will detect the
98828**        syntax error and return a detailed message.
98829**
98830**  (18)  If the sub-query is a compound select, then all terms of the
98831**        ORDER by clause of the parent must be simple references to
98832**        columns of the sub-query.
98833**
98834**  (19)  The subquery does not use LIMIT or the outer query does not
98835**        have a WHERE clause.
98836**
98837**  (20)  If the sub-query is a compound select, then it must not use
98838**        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
98839**        somewhat by saying that the terms of the ORDER BY clause must
98840**        appear as unmodified result columns in the outer query.  But we
98841**        have other optimizations in mind to deal with that case.
98842**
98843**  (21)  The subquery does not use LIMIT or the outer query is not
98844**        DISTINCT.  (See ticket [752e1646fc]).
98845**
98846** In this routine, the "p" parameter is a pointer to the outer query.
98847** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
98848** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
98849**
98850** If flattening is not attempted, this routine is a no-op and returns 0.
98851** If flattening is attempted this routine returns 1.
98852**
98853** All of the expression analysis must occur on both the outer query and
98854** the subquery before this routine runs.
98855*/
98856static int flattenSubquery(
98857  Parse *pParse,       /* Parsing context */
98858  Select *p,           /* The parent or outer SELECT statement */
98859  int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
98860  int isAgg,           /* True if outer SELECT uses aggregate functions */
98861  int subqueryIsAgg    /* True if the subquery uses aggregate functions */
98862){
98863  const char *zSavedAuthContext = pParse->zAuthContext;
98864  Select *pParent;
98865  Select *pSub;       /* The inner query or "subquery" */
98866  Select *pSub1;      /* Pointer to the rightmost select in sub-query */
98867  SrcList *pSrc;      /* The FROM clause of the outer query */
98868  SrcList *pSubSrc;   /* The FROM clause of the subquery */
98869  ExprList *pList;    /* The result set of the outer query */
98870  int iParent;        /* VDBE cursor number of the pSub result set temp table */
98871  int i;              /* Loop counter */
98872  Expr *pWhere;                    /* The WHERE clause */
98873  struct SrcList_item *pSubitem;   /* The subquery */
98874  sqlite3 *db = pParse->db;
98875
98876  /* Check to see if flattening is permitted.  Return 0 if not.
98877  */
98878  assert( p!=0 );
98879  assert( p->pPrior==0 );  /* Unable to flatten compound queries */
98880  if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
98881  pSrc = p->pSrc;
98882  assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
98883  pSubitem = &pSrc->a[iFrom];
98884  iParent = pSubitem->iCursor;
98885  pSub = pSubitem->pSelect;
98886  assert( pSub!=0 );
98887  if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
98888  if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
98889  pSubSrc = pSub->pSrc;
98890  assert( pSubSrc );
98891  /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
98892  ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
98893  ** because they could be computed at compile-time.  But when LIMIT and OFFSET
98894  ** became arbitrary expressions, we were forced to add restrictions (13)
98895  ** and (14). */
98896  if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
98897  if( pSub->pOffset ) return 0;                          /* Restriction (14) */
98898  if( p->pRightmost && pSub->pLimit ){
98899    return 0;                                            /* Restriction (15) */
98900  }
98901  if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
98902  if( pSub->selFlags & SF_Distinct ) return 0;           /* Restriction (5)  */
98903  if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
98904     return 0;         /* Restrictions (8)(9) */
98905  }
98906  if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
98907     return 0;         /* Restriction (6)  */
98908  }
98909  if( p->pOrderBy && pSub->pOrderBy ){
98910     return 0;                                           /* Restriction (11) */
98911  }
98912  if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
98913  if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
98914  if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
98915     return 0;         /* Restriction (21) */
98916  }
98917
98918  /* OBSOLETE COMMENT 1:
98919  ** Restriction 3:  If the subquery is a join, make sure the subquery is
98920  ** not used as the right operand of an outer join.  Examples of why this
98921  ** is not allowed:
98922  **
98923  **         t1 LEFT OUTER JOIN (t2 JOIN t3)
98924  **
98925  ** If we flatten the above, we would get
98926  **
98927  **         (t1 LEFT OUTER JOIN t2) JOIN t3
98928  **
98929  ** which is not at all the same thing.
98930  **
98931  ** OBSOLETE COMMENT 2:
98932  ** Restriction 12:  If the subquery is the right operand of a left outer
98933  ** join, make sure the subquery has no WHERE clause.
98934  ** An examples of why this is not allowed:
98935  **
98936  **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
98937  **
98938  ** If we flatten the above, we would get
98939  **
98940  **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
98941  **
98942  ** But the t2.x>0 test will always fail on a NULL row of t2, which
98943  ** effectively converts the OUTER JOIN into an INNER JOIN.
98944  **
98945  ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
98946  ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
98947  ** is fraught with danger.  Best to avoid the whole thing.  If the
98948  ** subquery is the right term of a LEFT JOIN, then do not flatten.
98949  */
98950  if( (pSubitem->jointype & JT_OUTER)!=0 ){
98951    return 0;
98952  }
98953
98954  /* Restriction 17: If the sub-query is a compound SELECT, then it must
98955  ** use only the UNION ALL operator. And none of the simple select queries
98956  ** that make up the compound SELECT are allowed to be aggregate or distinct
98957  ** queries.
98958  */
98959  if( pSub->pPrior ){
98960    if( pSub->pOrderBy ){
98961      return 0;  /* Restriction 20 */
98962    }
98963    if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
98964      return 0;
98965    }
98966    for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
98967      testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
98968      testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
98969      assert( pSub->pSrc!=0 );
98970      if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
98971       || (pSub1->pPrior && pSub1->op!=TK_ALL)
98972       || pSub1->pSrc->nSrc<1
98973       || pSub->pEList->nExpr!=pSub1->pEList->nExpr
98974      ){
98975        return 0;
98976      }
98977      testcase( pSub1->pSrc->nSrc>1 );
98978    }
98979
98980    /* Restriction 18. */
98981    if( p->pOrderBy ){
98982      int ii;
98983      for(ii=0; ii<p->pOrderBy->nExpr; ii++){
98984        if( p->pOrderBy->a[ii].iOrderByCol==0 ) return 0;
98985      }
98986    }
98987  }
98988
98989  /***** If we reach this point, flattening is permitted. *****/
98990
98991  /* Authorize the subquery */
98992  pParse->zAuthContext = pSubitem->zName;
98993  TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
98994  testcase( i==SQLITE_DENY );
98995  pParse->zAuthContext = zSavedAuthContext;
98996
98997  /* If the sub-query is a compound SELECT statement, then (by restrictions
98998  ** 17 and 18 above) it must be a UNION ALL and the parent query must
98999  ** be of the form:
99000  **
99001  **     SELECT <expr-list> FROM (<sub-query>) <where-clause>
99002  **
99003  ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
99004  ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
99005  ** OFFSET clauses and joins them to the left-hand-side of the original
99006  ** using UNION ALL operators. In this case N is the number of simple
99007  ** select statements in the compound sub-query.
99008  **
99009  ** Example:
99010  **
99011  **     SELECT a+1 FROM (
99012  **        SELECT x FROM tab
99013  **        UNION ALL
99014  **        SELECT y FROM tab
99015  **        UNION ALL
99016  **        SELECT abs(z*2) FROM tab2
99017  **     ) WHERE a!=5 ORDER BY 1
99018  **
99019  ** Transformed into:
99020  **
99021  **     SELECT x+1 FROM tab WHERE x+1!=5
99022  **     UNION ALL
99023  **     SELECT y+1 FROM tab WHERE y+1!=5
99024  **     UNION ALL
99025  **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
99026  **     ORDER BY 1
99027  **
99028  ** We call this the "compound-subquery flattening".
99029  */
99030  for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
99031    Select *pNew;
99032    ExprList *pOrderBy = p->pOrderBy;
99033    Expr *pLimit = p->pLimit;
99034    Expr *pOffset = p->pOffset;
99035    Select *pPrior = p->pPrior;
99036    p->pOrderBy = 0;
99037    p->pSrc = 0;
99038    p->pPrior = 0;
99039    p->pLimit = 0;
99040    p->pOffset = 0;
99041    pNew = sqlite3SelectDup(db, p, 0);
99042    p->pOffset = pOffset;
99043    p->pLimit = pLimit;
99044    p->pOrderBy = pOrderBy;
99045    p->pSrc = pSrc;
99046    p->op = TK_ALL;
99047    p->pRightmost = 0;
99048    if( pNew==0 ){
99049      pNew = pPrior;
99050    }else{
99051      pNew->pPrior = pPrior;
99052      pNew->pRightmost = 0;
99053    }
99054    p->pPrior = pNew;
99055    if( db->mallocFailed ) return 1;
99056  }
99057
99058  /* Begin flattening the iFrom-th entry of the FROM clause
99059  ** in the outer query.
99060  */
99061  pSub = pSub1 = pSubitem->pSelect;
99062
99063  /* Delete the transient table structure associated with the
99064  ** subquery
99065  */
99066  sqlite3DbFree(db, pSubitem->zDatabase);
99067  sqlite3DbFree(db, pSubitem->zName);
99068  sqlite3DbFree(db, pSubitem->zAlias);
99069  pSubitem->zDatabase = 0;
99070  pSubitem->zName = 0;
99071  pSubitem->zAlias = 0;
99072  pSubitem->pSelect = 0;
99073
99074  /* Defer deleting the Table object associated with the
99075  ** subquery until code generation is
99076  ** complete, since there may still exist Expr.pTab entries that
99077  ** refer to the subquery even after flattening.  Ticket #3346.
99078  **
99079  ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
99080  */
99081  if( ALWAYS(pSubitem->pTab!=0) ){
99082    Table *pTabToDel = pSubitem->pTab;
99083    if( pTabToDel->nRef==1 ){
99084      Parse *pToplevel = sqlite3ParseToplevel(pParse);
99085      pTabToDel->pNextZombie = pToplevel->pZombieTab;
99086      pToplevel->pZombieTab = pTabToDel;
99087    }else{
99088      pTabToDel->nRef--;
99089    }
99090    pSubitem->pTab = 0;
99091  }
99092
99093  /* The following loop runs once for each term in a compound-subquery
99094  ** flattening (as described above).  If we are doing a different kind
99095  ** of flattening - a flattening other than a compound-subquery flattening -
99096  ** then this loop only runs once.
99097  **
99098  ** This loop moves all of the FROM elements of the subquery into the
99099  ** the FROM clause of the outer query.  Before doing this, remember
99100  ** the cursor number for the original outer query FROM element in
99101  ** iParent.  The iParent cursor will never be used.  Subsequent code
99102  ** will scan expressions looking for iParent references and replace
99103  ** those references with expressions that resolve to the subquery FROM
99104  ** elements we are now copying in.
99105  */
99106  for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
99107    int nSubSrc;
99108    u8 jointype = 0;
99109    pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
99110    nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
99111    pSrc = pParent->pSrc;     /* FROM clause of the outer query */
99112
99113    if( pSrc ){
99114      assert( pParent==p );  /* First time through the loop */
99115      jointype = pSubitem->jointype;
99116    }else{
99117      assert( pParent!=p );  /* 2nd and subsequent times through the loop */
99118      pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
99119      if( pSrc==0 ){
99120        assert( db->mallocFailed );
99121        break;
99122      }
99123    }
99124
99125    /* The subquery uses a single slot of the FROM clause of the outer
99126    ** query.  If the subquery has more than one element in its FROM clause,
99127    ** then expand the outer query to make space for it to hold all elements
99128    ** of the subquery.
99129    **
99130    ** Example:
99131    **
99132    **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
99133    **
99134    ** The outer query has 3 slots in its FROM clause.  One slot of the
99135    ** outer query (the middle slot) is used by the subquery.  The next
99136    ** block of code will expand the out query to 4 slots.  The middle
99137    ** slot is expanded to two slots in order to make space for the
99138    ** two elements in the FROM clause of the subquery.
99139    */
99140    if( nSubSrc>1 ){
99141      pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
99142      if( db->mallocFailed ){
99143        break;
99144      }
99145    }
99146
99147    /* Transfer the FROM clause terms from the subquery into the
99148    ** outer query.
99149    */
99150    for(i=0; i<nSubSrc; i++){
99151      sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
99152      pSrc->a[i+iFrom] = pSubSrc->a[i];
99153      memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
99154    }
99155    pSrc->a[iFrom].jointype = jointype;
99156
99157    /* Now begin substituting subquery result set expressions for
99158    ** references to the iParent in the outer query.
99159    **
99160    ** Example:
99161    **
99162    **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
99163    **   \                     \_____________ subquery __________/          /
99164    **    \_____________________ outer query ______________________________/
99165    **
99166    ** We look at every expression in the outer query and every place we see
99167    ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
99168    */
99169    pList = pParent->pEList;
99170    for(i=0; i<pList->nExpr; i++){
99171      if( pList->a[i].zName==0 ){
99172        char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan);
99173        sqlite3Dequote(zName);
99174        pList->a[i].zName = zName;
99175      }
99176    }
99177    substExprList(db, pParent->pEList, iParent, pSub->pEList);
99178    if( isAgg ){
99179      substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
99180      pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
99181    }
99182    if( pSub->pOrderBy ){
99183      assert( pParent->pOrderBy==0 );
99184      pParent->pOrderBy = pSub->pOrderBy;
99185      pSub->pOrderBy = 0;
99186    }else if( pParent->pOrderBy ){
99187      substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
99188    }
99189    if( pSub->pWhere ){
99190      pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
99191    }else{
99192      pWhere = 0;
99193    }
99194    if( subqueryIsAgg ){
99195      assert( pParent->pHaving==0 );
99196      pParent->pHaving = pParent->pWhere;
99197      pParent->pWhere = pWhere;
99198      pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
99199      pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
99200                                  sqlite3ExprDup(db, pSub->pHaving, 0));
99201      assert( pParent->pGroupBy==0 );
99202      pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
99203    }else{
99204      pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
99205      pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
99206    }
99207
99208    /* The flattened query is distinct if either the inner or the
99209    ** outer query is distinct.
99210    */
99211    pParent->selFlags |= pSub->selFlags & SF_Distinct;
99212
99213    /*
99214    ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
99215    **
99216    ** One is tempted to try to add a and b to combine the limits.  But this
99217    ** does not work if either limit is negative.
99218    */
99219    if( pSub->pLimit ){
99220      pParent->pLimit = pSub->pLimit;
99221      pSub->pLimit = 0;
99222    }
99223  }
99224
99225  /* Finially, delete what is left of the subquery and return
99226  ** success.
99227  */
99228  sqlite3SelectDelete(db, pSub1);
99229
99230  return 1;
99231}
99232#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
99233
99234/*
99235** Based on the contents of the AggInfo structure indicated by the first
99236** argument, this function checks if the following are true:
99237**
99238**    * the query contains just a single aggregate function,
99239**    * the aggregate function is either min() or max(), and
99240**    * the argument to the aggregate function is a column value.
99241**
99242** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX
99243** is returned as appropriate. Also, *ppMinMax is set to point to the
99244** list of arguments passed to the aggregate before returning.
99245**
99246** Or, if the conditions above are not met, *ppMinMax is set to 0 and
99247** WHERE_ORDERBY_NORMAL is returned.
99248*/
99249static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){
99250  int eRet = WHERE_ORDERBY_NORMAL;          /* Return value */
99251
99252  *ppMinMax = 0;
99253  if( pAggInfo->nFunc==1 ){
99254    Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */
99255    ExprList *pEList = pExpr->x.pList;      /* Arguments to agg function */
99256
99257    assert( pExpr->op==TK_AGG_FUNCTION );
99258    if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){
99259      const char *zFunc = pExpr->u.zToken;
99260      if( sqlite3StrICmp(zFunc, "min")==0 ){
99261        eRet = WHERE_ORDERBY_MIN;
99262        *ppMinMax = pEList;
99263      }else if( sqlite3StrICmp(zFunc, "max")==0 ){
99264        eRet = WHERE_ORDERBY_MAX;
99265        *ppMinMax = pEList;
99266      }
99267    }
99268  }
99269
99270  assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 );
99271  return eRet;
99272}
99273
99274/*
99275** The select statement passed as the first argument is an aggregate query.
99276** The second argment is the associated aggregate-info object. This
99277** function tests if the SELECT is of the form:
99278**
99279**   SELECT count(*) FROM <tbl>
99280**
99281** where table is a database table, not a sub-select or view. If the query
99282** does match this pattern, then a pointer to the Table object representing
99283** <tbl> is returned. Otherwise, 0 is returned.
99284*/
99285static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
99286  Table *pTab;
99287  Expr *pExpr;
99288
99289  assert( !p->pGroupBy );
99290
99291  if( p->pWhere || p->pEList->nExpr!=1
99292   || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
99293  ){
99294    return 0;
99295  }
99296  pTab = p->pSrc->a[0].pTab;
99297  pExpr = p->pEList->a[0].pExpr;
99298  assert( pTab && !pTab->pSelect && pExpr );
99299
99300  if( IsVirtual(pTab) ) return 0;
99301  if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
99302  if( NEVER(pAggInfo->nFunc==0) ) return 0;
99303  if( (pAggInfo->aFunc[0].pFunc->flags&SQLITE_FUNC_COUNT)==0 ) return 0;
99304  if( pExpr->flags&EP_Distinct ) return 0;
99305
99306  return pTab;
99307}
99308
99309/*
99310** If the source-list item passed as an argument was augmented with an
99311** INDEXED BY clause, then try to locate the specified index. If there
99312** was such a clause and the named index cannot be found, return
99313** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
99314** pFrom->pIndex and return SQLITE_OK.
99315*/
99316SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
99317  if( pFrom->pTab && pFrom->zIndex ){
99318    Table *pTab = pFrom->pTab;
99319    char *zIndex = pFrom->zIndex;
99320    Index *pIdx;
99321    for(pIdx=pTab->pIndex;
99322        pIdx && sqlite3StrICmp(pIdx->zName, zIndex);
99323        pIdx=pIdx->pNext
99324    );
99325    if( !pIdx ){
99326      sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
99327      pParse->checkSchema = 1;
99328      return SQLITE_ERROR;
99329    }
99330    pFrom->pIndex = pIdx;
99331  }
99332  return SQLITE_OK;
99333}
99334/*
99335** Detect compound SELECT statements that use an ORDER BY clause with
99336** an alternative collating sequence.
99337**
99338**    SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
99339**
99340** These are rewritten as a subquery:
99341**
99342**    SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
99343**     ORDER BY ... COLLATE ...
99344**
99345** This transformation is necessary because the multiSelectOrderBy() routine
99346** above that generates the code for a compound SELECT with an ORDER BY clause
99347** uses a merge algorithm that requires the same collating sequence on the
99348** result columns as on the ORDER BY clause.  See ticket
99349** http://www.sqlite.org/src/info/6709574d2a
99350**
99351** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
99352** The UNION ALL operator works fine with multiSelectOrderBy() even when
99353** there are COLLATE terms in the ORDER BY.
99354*/
99355static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
99356  int i;
99357  Select *pNew;
99358  Select *pX;
99359  sqlite3 *db;
99360  struct ExprList_item *a;
99361  SrcList *pNewSrc;
99362  Parse *pParse;
99363  Token dummy;
99364
99365  if( p->pPrior==0 ) return WRC_Continue;
99366  if( p->pOrderBy==0 ) return WRC_Continue;
99367  for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
99368  if( pX==0 ) return WRC_Continue;
99369  a = p->pOrderBy->a;
99370  for(i=p->pOrderBy->nExpr-1; i>=0; i--){
99371    if( a[i].pExpr->flags & EP_Collate ) break;
99372  }
99373  if( i<0 ) return WRC_Continue;
99374
99375  /* If we reach this point, that means the transformation is required. */
99376
99377  pParse = pWalker->pParse;
99378  db = pParse->db;
99379  pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
99380  if( pNew==0 ) return WRC_Abort;
99381  memset(&dummy, 0, sizeof(dummy));
99382  pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
99383  if( pNewSrc==0 ) return WRC_Abort;
99384  *pNew = *p;
99385  p->pSrc = pNewSrc;
99386  p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ALL, 0));
99387  p->op = TK_SELECT;
99388  p->pWhere = 0;
99389  pNew->pGroupBy = 0;
99390  pNew->pHaving = 0;
99391  pNew->pOrderBy = 0;
99392  p->pPrior = 0;
99393  pNew->pLimit = 0;
99394  pNew->pOffset = 0;
99395  return WRC_Continue;
99396}
99397
99398/*
99399** This routine is a Walker callback for "expanding" a SELECT statement.
99400** "Expanding" means to do the following:
99401**
99402**    (1)  Make sure VDBE cursor numbers have been assigned to every
99403**         element of the FROM clause.
99404**
99405**    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that
99406**         defines FROM clause.  When views appear in the FROM clause,
99407**         fill pTabList->a[].pSelect with a copy of the SELECT statement
99408**         that implements the view.  A copy is made of the view's SELECT
99409**         statement so that we can freely modify or delete that statement
99410**         without worrying about messing up the presistent representation
99411**         of the view.
99412**
99413**    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
99414**         on joins and the ON and USING clause of joins.
99415**
99416**    (4)  Scan the list of columns in the result set (pEList) looking
99417**         for instances of the "*" operator or the TABLE.* operator.
99418**         If found, expand each "*" to be every column in every table
99419**         and TABLE.* to be every column in TABLE.
99420**
99421*/
99422static int selectExpander(Walker *pWalker, Select *p){
99423  Parse *pParse = pWalker->pParse;
99424  int i, j, k;
99425  SrcList *pTabList;
99426  ExprList *pEList;
99427  struct SrcList_item *pFrom;
99428  sqlite3 *db = pParse->db;
99429  Expr *pE, *pRight, *pExpr;
99430  u16 selFlags = p->selFlags;
99431
99432  p->selFlags |= SF_Expanded;
99433  if( db->mallocFailed  ){
99434    return WRC_Abort;
99435  }
99436  if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){
99437    return WRC_Prune;
99438  }
99439  pTabList = p->pSrc;
99440  pEList = p->pEList;
99441
99442  /* Make sure cursor numbers have been assigned to all entries in
99443  ** the FROM clause of the SELECT statement.
99444  */
99445  sqlite3SrcListAssignCursors(pParse, pTabList);
99446
99447  /* Look up every table named in the FROM clause of the select.  If
99448  ** an entry of the FROM clause is a subquery instead of a table or view,
99449  ** then create a transient table structure to describe the subquery.
99450  */
99451  for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
99452    Table *pTab;
99453    if( pFrom->pTab!=0 ){
99454      /* This statement has already been prepared.  There is no need
99455      ** to go further. */
99456      assert( i==0 );
99457      return WRC_Prune;
99458    }
99459    if( pFrom->zName==0 ){
99460#ifndef SQLITE_OMIT_SUBQUERY
99461      Select *pSel = pFrom->pSelect;
99462      /* A sub-query in the FROM clause of a SELECT */
99463      assert( pSel!=0 );
99464      assert( pFrom->pTab==0 );
99465      sqlite3WalkSelect(pWalker, pSel);
99466      pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
99467      if( pTab==0 ) return WRC_Abort;
99468      pTab->nRef = 1;
99469      pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
99470      while( pSel->pPrior ){ pSel = pSel->pPrior; }
99471      selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
99472      pTab->iPKey = -1;
99473      pTab->nRowEst = 1000000;
99474      pTab->tabFlags |= TF_Ephemeral;
99475#endif
99476    }else{
99477      /* An ordinary table or view name in the FROM clause */
99478      assert( pFrom->pTab==0 );
99479      pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
99480      if( pTab==0 ) return WRC_Abort;
99481      if( pTab->nRef==0xffff ){
99482        sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
99483           pTab->zName);
99484        pFrom->pTab = 0;
99485        return WRC_Abort;
99486      }
99487      pTab->nRef++;
99488#if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
99489      if( pTab->pSelect || IsVirtual(pTab) ){
99490        /* We reach here if the named table is a really a view */
99491        if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
99492        assert( pFrom->pSelect==0 );
99493        pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
99494        sqlite3WalkSelect(pWalker, pFrom->pSelect);
99495      }
99496#endif
99497    }
99498
99499    /* Locate the index named by the INDEXED BY clause, if any. */
99500    if( sqlite3IndexedByLookup(pParse, pFrom) ){
99501      return WRC_Abort;
99502    }
99503  }
99504
99505  /* Process NATURAL keywords, and ON and USING clauses of joins.
99506  */
99507  if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
99508    return WRC_Abort;
99509  }
99510
99511  /* For every "*" that occurs in the column list, insert the names of
99512  ** all columns in all tables.  And for every TABLE.* insert the names
99513  ** of all columns in TABLE.  The parser inserted a special expression
99514  ** with the TK_ALL operator for each "*" that it found in the column list.
99515  ** The following code just has to locate the TK_ALL expressions and expand
99516  ** each one to the list of all columns in all tables.
99517  **
99518  ** The first loop just checks to see if there are any "*" operators
99519  ** that need expanding.
99520  */
99521  for(k=0; k<pEList->nExpr; k++){
99522    pE = pEList->a[k].pExpr;
99523    if( pE->op==TK_ALL ) break;
99524    assert( pE->op!=TK_DOT || pE->pRight!=0 );
99525    assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
99526    if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
99527  }
99528  if( k<pEList->nExpr ){
99529    /*
99530    ** If we get here it means the result set contains one or more "*"
99531    ** operators that need to be expanded.  Loop through each expression
99532    ** in the result set and expand them one by one.
99533    */
99534    struct ExprList_item *a = pEList->a;
99535    ExprList *pNew = 0;
99536    int flags = pParse->db->flags;
99537    int longNames = (flags & SQLITE_FullColNames)!=0
99538                      && (flags & SQLITE_ShortColNames)==0;
99539
99540    /* When processing FROM-clause subqueries, it is always the case
99541    ** that full_column_names=OFF and short_column_names=ON.  The
99542    ** sqlite3ResultSetOfSelect() routine makes it so. */
99543    assert( (p->selFlags & SF_NestedFrom)==0
99544          || ((flags & SQLITE_FullColNames)==0 &&
99545              (flags & SQLITE_ShortColNames)!=0) );
99546
99547    for(k=0; k<pEList->nExpr; k++){
99548      pE = a[k].pExpr;
99549      pRight = pE->pRight;
99550      assert( pE->op!=TK_DOT || pRight!=0 );
99551      if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pRight->op!=TK_ALL) ){
99552        /* This particular expression does not need to be expanded.
99553        */
99554        pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
99555        if( pNew ){
99556          pNew->a[pNew->nExpr-1].zName = a[k].zName;
99557          pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
99558          a[k].zName = 0;
99559          a[k].zSpan = 0;
99560        }
99561        a[k].pExpr = 0;
99562      }else{
99563        /* This expression is a "*" or a "TABLE.*" and needs to be
99564        ** expanded. */
99565        int tableSeen = 0;      /* Set to 1 when TABLE matches */
99566        char *zTName = 0;       /* text of name of TABLE */
99567        if( pE->op==TK_DOT ){
99568          assert( pE->pLeft!=0 );
99569          assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
99570          zTName = pE->pLeft->u.zToken;
99571        }
99572        for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
99573          Table *pTab = pFrom->pTab;
99574          Select *pSub = pFrom->pSelect;
99575          char *zTabName = pFrom->zAlias;
99576          const char *zSchemaName = 0;
99577          int iDb;
99578          if( zTabName==0 ){
99579            zTabName = pTab->zName;
99580          }
99581          if( db->mallocFailed ) break;
99582          if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
99583            pSub = 0;
99584            if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
99585              continue;
99586            }
99587            iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
99588            zSchemaName = iDb>=0 ? db->aDb[iDb].zName : "*";
99589          }
99590          for(j=0; j<pTab->nCol; j++){
99591            char *zName = pTab->aCol[j].zName;
99592            char *zColname;  /* The computed column name */
99593            char *zToFree;   /* Malloced string that needs to be freed */
99594            Token sColname;  /* Computed column name as a token */
99595
99596            assert( zName );
99597            if( zTName && pSub
99598             && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
99599            ){
99600              continue;
99601            }
99602
99603            /* If a column is marked as 'hidden' (currently only possible
99604            ** for virtual tables), do not include it in the expanded
99605            ** result-set list.
99606            */
99607            if( IsHiddenColumn(&pTab->aCol[j]) ){
99608              assert(IsVirtual(pTab));
99609              continue;
99610            }
99611            tableSeen = 1;
99612
99613            if( i>0 && zTName==0 ){
99614              if( (pFrom->jointype & JT_NATURAL)!=0
99615                && tableAndColumnIndex(pTabList, i, zName, 0, 0)
99616              ){
99617                /* In a NATURAL join, omit the join columns from the
99618                ** table to the right of the join */
99619                continue;
99620              }
99621              if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
99622                /* In a join with a USING clause, omit columns in the
99623                ** using clause from the table on the right. */
99624                continue;
99625              }
99626            }
99627            pRight = sqlite3Expr(db, TK_ID, zName);
99628            zColname = zName;
99629            zToFree = 0;
99630            if( longNames || pTabList->nSrc>1 ){
99631              Expr *pLeft;
99632              pLeft = sqlite3Expr(db, TK_ID, zTabName);
99633              pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
99634              if( zSchemaName ){
99635                pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
99636                pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr, 0);
99637              }
99638              if( longNames ){
99639                zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
99640                zToFree = zColname;
99641              }
99642            }else{
99643              pExpr = pRight;
99644            }
99645            pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
99646            sColname.z = zColname;
99647            sColname.n = sqlite3Strlen30(zColname);
99648            sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
99649            if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
99650              struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
99651              if( pSub ){
99652                pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
99653                testcase( pX->zSpan==0 );
99654              }else{
99655                pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
99656                                           zSchemaName, zTabName, zColname);
99657                testcase( pX->zSpan==0 );
99658              }
99659              pX->bSpanIsTab = 1;
99660            }
99661            sqlite3DbFree(db, zToFree);
99662          }
99663        }
99664        if( !tableSeen ){
99665          if( zTName ){
99666            sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
99667          }else{
99668            sqlite3ErrorMsg(pParse, "no tables specified");
99669          }
99670        }
99671      }
99672    }
99673    sqlite3ExprListDelete(db, pEList);
99674    p->pEList = pNew;
99675  }
99676#if SQLITE_MAX_COLUMN
99677  if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
99678    sqlite3ErrorMsg(pParse, "too many columns in result set");
99679  }
99680#endif
99681  return WRC_Continue;
99682}
99683
99684/*
99685** No-op routine for the parse-tree walker.
99686**
99687** When this routine is the Walker.xExprCallback then expression trees
99688** are walked without any actions being taken at each node.  Presumably,
99689** when this routine is used for Walker.xExprCallback then
99690** Walker.xSelectCallback is set to do something useful for every
99691** subquery in the parser tree.
99692*/
99693static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
99694  UNUSED_PARAMETER2(NotUsed, NotUsed2);
99695  return WRC_Continue;
99696}
99697
99698/*
99699** This routine "expands" a SELECT statement and all of its subqueries.
99700** For additional information on what it means to "expand" a SELECT
99701** statement, see the comment on the selectExpand worker callback above.
99702**
99703** Expanding a SELECT statement is the first step in processing a
99704** SELECT statement.  The SELECT statement must be expanded before
99705** name resolution is performed.
99706**
99707** If anything goes wrong, an error message is written into pParse.
99708** The calling function can detect the problem by looking at pParse->nErr
99709** and/or pParse->db->mallocFailed.
99710*/
99711static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
99712  Walker w;
99713  memset(&w, 0, sizeof(w));
99714  w.xSelectCallback = convertCompoundSelectToSubquery;
99715  w.xExprCallback = exprWalkNoop;
99716  w.pParse = pParse;
99717  sqlite3WalkSelect(&w, pSelect);
99718  w.xSelectCallback = selectExpander;
99719  sqlite3WalkSelect(&w, pSelect);
99720}
99721
99722
99723#ifndef SQLITE_OMIT_SUBQUERY
99724/*
99725** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
99726** interface.
99727**
99728** For each FROM-clause subquery, add Column.zType and Column.zColl
99729** information to the Table structure that represents the result set
99730** of that subquery.
99731**
99732** The Table structure that represents the result set was constructed
99733** by selectExpander() but the type and collation information was omitted
99734** at that point because identifiers had not yet been resolved.  This
99735** routine is called after identifier resolution.
99736*/
99737static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
99738  Parse *pParse;
99739  int i;
99740  SrcList *pTabList;
99741  struct SrcList_item *pFrom;
99742
99743  assert( p->selFlags & SF_Resolved );
99744  if( (p->selFlags & SF_HasTypeInfo)==0 ){
99745    p->selFlags |= SF_HasTypeInfo;
99746    pParse = pWalker->pParse;
99747    pTabList = p->pSrc;
99748    for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
99749      Table *pTab = pFrom->pTab;
99750      if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
99751        /* A sub-query in the FROM clause of a SELECT */
99752        Select *pSel = pFrom->pSelect;
99753        assert( pSel );
99754        while( pSel->pPrior ) pSel = pSel->pPrior;
99755        selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
99756      }
99757    }
99758  }
99759  return WRC_Continue;
99760}
99761#endif
99762
99763
99764/*
99765** This routine adds datatype and collating sequence information to
99766** the Table structures of all FROM-clause subqueries in a
99767** SELECT statement.
99768**
99769** Use this routine after name resolution.
99770*/
99771static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
99772#ifndef SQLITE_OMIT_SUBQUERY
99773  Walker w;
99774  memset(&w, 0, sizeof(w));
99775  w.xSelectCallback = selectAddSubqueryTypeInfo;
99776  w.xExprCallback = exprWalkNoop;
99777  w.pParse = pParse;
99778  w.bSelectDepthFirst = 1;
99779  sqlite3WalkSelect(&w, pSelect);
99780#endif
99781}
99782
99783
99784/*
99785** This routine sets up a SELECT statement for processing.  The
99786** following is accomplished:
99787**
99788**     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
99789**     *  Ephemeral Table objects are created for all FROM-clause subqueries.
99790**     *  ON and USING clauses are shifted into WHERE statements
99791**     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
99792**     *  Identifiers in expression are matched to tables.
99793**
99794** This routine acts recursively on all subqueries within the SELECT.
99795*/
99796SQLITE_PRIVATE void sqlite3SelectPrep(
99797  Parse *pParse,         /* The parser context */
99798  Select *p,             /* The SELECT statement being coded. */
99799  NameContext *pOuterNC  /* Name context for container */
99800){
99801  sqlite3 *db;
99802  if( NEVER(p==0) ) return;
99803  db = pParse->db;
99804  if( db->mallocFailed ) return;
99805  if( p->selFlags & SF_HasTypeInfo ) return;
99806  sqlite3SelectExpand(pParse, p);
99807  if( pParse->nErr || db->mallocFailed ) return;
99808  sqlite3ResolveSelectNames(pParse, p, pOuterNC);
99809  if( pParse->nErr || db->mallocFailed ) return;
99810  sqlite3SelectAddTypeInfo(pParse, p);
99811}
99812
99813/*
99814** Reset the aggregate accumulator.
99815**
99816** The aggregate accumulator is a set of memory cells that hold
99817** intermediate results while calculating an aggregate.  This
99818** routine generates code that stores NULLs in all of those memory
99819** cells.
99820*/
99821static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
99822  Vdbe *v = pParse->pVdbe;
99823  int i;
99824  struct AggInfo_func *pFunc;
99825  if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
99826    return;
99827  }
99828  for(i=0; i<pAggInfo->nColumn; i++){
99829    sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
99830  }
99831  for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
99832    sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
99833    if( pFunc->iDistinct>=0 ){
99834      Expr *pE = pFunc->pExpr;
99835      assert( !ExprHasProperty(pE, EP_xIsSelect) );
99836      if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
99837        sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
99838           "argument");
99839        pFunc->iDistinct = -1;
99840      }else{
99841        KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList);
99842        sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
99843                          (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
99844      }
99845    }
99846  }
99847}
99848
99849/*
99850** Invoke the OP_AggFinalize opcode for every aggregate function
99851** in the AggInfo structure.
99852*/
99853static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
99854  Vdbe *v = pParse->pVdbe;
99855  int i;
99856  struct AggInfo_func *pF;
99857  for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
99858    ExprList *pList = pF->pExpr->x.pList;
99859    assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
99860    sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
99861                      (void*)pF->pFunc, P4_FUNCDEF);
99862  }
99863}
99864
99865/*
99866** Update the accumulator memory cells for an aggregate based on
99867** the current cursor position.
99868*/
99869static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
99870  Vdbe *v = pParse->pVdbe;
99871  int i;
99872  int regHit = 0;
99873  int addrHitTest = 0;
99874  struct AggInfo_func *pF;
99875  struct AggInfo_col *pC;
99876
99877  pAggInfo->directMode = 1;
99878  sqlite3ExprCacheClear(pParse);
99879  for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
99880    int nArg;
99881    int addrNext = 0;
99882    int regAgg;
99883    ExprList *pList = pF->pExpr->x.pList;
99884    assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
99885    if( pList ){
99886      nArg = pList->nExpr;
99887      regAgg = sqlite3GetTempRange(pParse, nArg);
99888      sqlite3ExprCodeExprList(pParse, pList, regAgg, 1);
99889    }else{
99890      nArg = 0;
99891      regAgg = 0;
99892    }
99893    if( pF->iDistinct>=0 ){
99894      addrNext = sqlite3VdbeMakeLabel(v);
99895      assert( nArg==1 );
99896      codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
99897    }
99898    if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
99899      CollSeq *pColl = 0;
99900      struct ExprList_item *pItem;
99901      int j;
99902      assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
99903      for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
99904        pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
99905      }
99906      if( !pColl ){
99907        pColl = pParse->db->pDfltColl;
99908      }
99909      if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
99910      sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
99911    }
99912    sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
99913                      (void*)pF->pFunc, P4_FUNCDEF);
99914    sqlite3VdbeChangeP5(v, (u8)nArg);
99915    sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
99916    sqlite3ReleaseTempRange(pParse, regAgg, nArg);
99917    if( addrNext ){
99918      sqlite3VdbeResolveLabel(v, addrNext);
99919      sqlite3ExprCacheClear(pParse);
99920    }
99921  }
99922
99923  /* Before populating the accumulator registers, clear the column cache.
99924  ** Otherwise, if any of the required column values are already present
99925  ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
99926  ** to pC->iMem. But by the time the value is used, the original register
99927  ** may have been used, invalidating the underlying buffer holding the
99928  ** text or blob value. See ticket [883034dcb5].
99929  **
99930  ** Another solution would be to change the OP_SCopy used to copy cached
99931  ** values to an OP_Copy.
99932  */
99933  if( regHit ){
99934    addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit);
99935  }
99936  sqlite3ExprCacheClear(pParse);
99937  for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
99938    sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
99939  }
99940  pAggInfo->directMode = 0;
99941  sqlite3ExprCacheClear(pParse);
99942  if( addrHitTest ){
99943    sqlite3VdbeJumpHere(v, addrHitTest);
99944  }
99945}
99946
99947/*
99948** Add a single OP_Explain instruction to the VDBE to explain a simple
99949** count(*) query ("SELECT count(*) FROM pTab").
99950*/
99951#ifndef SQLITE_OMIT_EXPLAIN
99952static void explainSimpleCount(
99953  Parse *pParse,                  /* Parse context */
99954  Table *pTab,                    /* Table being queried */
99955  Index *pIdx                     /* Index used to optimize scan, or NULL */
99956){
99957  if( pParse->explain==2 ){
99958    char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s %s%s(~%d rows)",
99959        pTab->zName,
99960        pIdx ? "USING COVERING INDEX " : "",
99961        pIdx ? pIdx->zName : "",
99962        pTab->nRowEst
99963    );
99964    sqlite3VdbeAddOp4(
99965        pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
99966    );
99967  }
99968}
99969#else
99970# define explainSimpleCount(a,b,c)
99971#endif
99972
99973/*
99974** Generate code for the SELECT statement given in the p argument.
99975**
99976** The results are distributed in various ways depending on the
99977** contents of the SelectDest structure pointed to by argument pDest
99978** as follows:
99979**
99980**     pDest->eDest    Result
99981**     ------------    -------------------------------------------
99982**     SRT_Output      Generate a row of output (using the OP_ResultRow
99983**                     opcode) for each row in the result set.
99984**
99985**     SRT_Mem         Only valid if the result is a single column.
99986**                     Store the first column of the first result row
99987**                     in register pDest->iSDParm then abandon the rest
99988**                     of the query.  This destination implies "LIMIT 1".
99989**
99990**     SRT_Set         The result must be a single column.  Store each
99991**                     row of result as the key in table pDest->iSDParm.
99992**                     Apply the affinity pDest->affSdst before storing
99993**                     results.  Used to implement "IN (SELECT ...)".
99994**
99995**     SRT_Union       Store results as a key in a temporary table
99996**                     identified by pDest->iSDParm.
99997**
99998**     SRT_Except      Remove results from the temporary table pDest->iSDParm.
99999**
100000**     SRT_Table       Store results in temporary table pDest->iSDParm.
100001**                     This is like SRT_EphemTab except that the table
100002**                     is assumed to already be open.
100003**
100004**     SRT_EphemTab    Create an temporary table pDest->iSDParm and store
100005**                     the result there. The cursor is left open after
100006**                     returning.  This is like SRT_Table except that
100007**                     this destination uses OP_OpenEphemeral to create
100008**                     the table first.
100009**
100010**     SRT_Coroutine   Generate a co-routine that returns a new row of
100011**                     results each time it is invoked.  The entry point
100012**                     of the co-routine is stored in register pDest->iSDParm.
100013**
100014**     SRT_Exists      Store a 1 in memory cell pDest->iSDParm if the result
100015**                     set is not empty.
100016**
100017**     SRT_Discard     Throw the results away.  This is used by SELECT
100018**                     statements within triggers whose only purpose is
100019**                     the side-effects of functions.
100020**
100021** This routine returns the number of errors.  If any errors are
100022** encountered, then an appropriate error message is left in
100023** pParse->zErrMsg.
100024**
100025** This routine does NOT free the Select structure passed in.  The
100026** calling function needs to do that.
100027*/
100028SQLITE_PRIVATE int sqlite3Select(
100029  Parse *pParse,         /* The parser context */
100030  Select *p,             /* The SELECT statement being coded. */
100031  SelectDest *pDest      /* What to do with the query results */
100032){
100033  int i, j;              /* Loop counters */
100034  WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
100035  Vdbe *v;               /* The virtual machine under construction */
100036  int isAgg;             /* True for select lists like "count(*)" */
100037  ExprList *pEList;      /* List of columns to extract. */
100038  SrcList *pTabList;     /* List of tables to select from */
100039  Expr *pWhere;          /* The WHERE clause.  May be NULL */
100040  ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
100041  ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
100042  Expr *pHaving;         /* The HAVING clause.  May be NULL */
100043  int rc = 1;            /* Value to return from this function */
100044  int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
100045  DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
100046  AggInfo sAggInfo;      /* Information used by aggregate queries */
100047  int iEnd;              /* Address of the end of the query */
100048  sqlite3 *db;           /* The database connection */
100049
100050#ifndef SQLITE_OMIT_EXPLAIN
100051  int iRestoreSelectId = pParse->iSelectId;
100052  pParse->iSelectId = pParse->iNextSelectId++;
100053#endif
100054
100055  db = pParse->db;
100056  if( p==0 || db->mallocFailed || pParse->nErr ){
100057    return 1;
100058  }
100059  if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
100060  memset(&sAggInfo, 0, sizeof(sAggInfo));
100061
100062  if( IgnorableOrderby(pDest) ){
100063    assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
100064           pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
100065    /* If ORDER BY makes no difference in the output then neither does
100066    ** DISTINCT so it can be removed too. */
100067    sqlite3ExprListDelete(db, p->pOrderBy);
100068    p->pOrderBy = 0;
100069    p->selFlags &= ~SF_Distinct;
100070  }
100071  sqlite3SelectPrep(pParse, p, 0);
100072  pOrderBy = p->pOrderBy;
100073  pTabList = p->pSrc;
100074  pEList = p->pEList;
100075  if( pParse->nErr || db->mallocFailed ){
100076    goto select_end;
100077  }
100078  isAgg = (p->selFlags & SF_Aggregate)!=0;
100079  assert( pEList!=0 );
100080
100081  /* Begin generating code.
100082  */
100083  v = sqlite3GetVdbe(pParse);
100084  if( v==0 ) goto select_end;
100085
100086  /* If writing to memory or generating a set
100087  ** only a single column may be output.
100088  */
100089#ifndef SQLITE_OMIT_SUBQUERY
100090  if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
100091    goto select_end;
100092  }
100093#endif
100094
100095  /* Generate code for all sub-queries in the FROM clause
100096  */
100097#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
100098  for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
100099    struct SrcList_item *pItem = &pTabList->a[i];
100100    SelectDest dest;
100101    Select *pSub = pItem->pSelect;
100102    int isAggSub;
100103
100104    if( pSub==0 ) continue;
100105
100106    /* Sometimes the code for a subquery will be generated more than
100107    ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
100108    ** for example.  In that case, do not regenerate the code to manifest
100109    ** a view or the co-routine to implement a view.  The first instance
100110    ** is sufficient, though the subroutine to manifest the view does need
100111    ** to be invoked again. */
100112    if( pItem->addrFillSub ){
100113      if( pItem->viaCoroutine==0 ){
100114        sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
100115      }
100116      continue;
100117    }
100118
100119    /* Increment Parse.nHeight by the height of the largest expression
100120    ** tree refered to by this, the parent select. The child select
100121    ** may contain expression trees of at most
100122    ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
100123    ** more conservative than necessary, but much easier than enforcing
100124    ** an exact limit.
100125    */
100126    pParse->nHeight += sqlite3SelectExprHeight(p);
100127
100128    isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
100129    if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
100130      /* This subquery can be absorbed into its parent. */
100131      if( isAggSub ){
100132        isAgg = 1;
100133        p->selFlags |= SF_Aggregate;
100134      }
100135      i = -1;
100136    }else if( pTabList->nSrc==1 && (p->selFlags & SF_Materialize)==0
100137      && OptimizationEnabled(db, SQLITE_SubqCoroutine)
100138    ){
100139      /* Implement a co-routine that will return a single row of the result
100140      ** set on each invocation.
100141      */
100142      int addrTop;
100143      int addrEof;
100144      pItem->regReturn = ++pParse->nMem;
100145      addrEof = ++pParse->nMem;
100146      /* Before coding the OP_Goto to jump to the start of the main routine,
100147      ** ensure that the jump to the verify-schema routine has already
100148      ** been coded. Otherwise, the verify-schema would likely be coded as
100149      ** part of the co-routine. If the main routine then accessed the
100150      ** database before invoking the co-routine for the first time (for
100151      ** example to initialize a LIMIT register from a sub-select), it would
100152      ** be doing so without having verified the schema version and obtained
100153      ** the required db locks. See ticket d6b36be38.  */
100154      sqlite3CodeVerifySchema(pParse, -1);
100155      sqlite3VdbeAddOp0(v, OP_Goto);
100156      addrTop = sqlite3VdbeAddOp1(v, OP_OpenPseudo, pItem->iCursor);
100157      sqlite3VdbeChangeP5(v, 1);
100158      VdbeComment((v, "coroutine for %s", pItem->pTab->zName));
100159      pItem->addrFillSub = addrTop;
100160      sqlite3VdbeAddOp2(v, OP_Integer, 0, addrEof);
100161      sqlite3VdbeChangeP5(v, 1);
100162      sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
100163      explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
100164      sqlite3Select(pParse, pSub, &dest);
100165      pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
100166      pItem->viaCoroutine = 1;
100167      sqlite3VdbeChangeP2(v, addrTop, dest.iSdst);
100168      sqlite3VdbeChangeP3(v, addrTop, dest.nSdst);
100169      sqlite3VdbeAddOp2(v, OP_Integer, 1, addrEof);
100170      sqlite3VdbeAddOp1(v, OP_Yield, pItem->regReturn);
100171      VdbeComment((v, "end %s", pItem->pTab->zName));
100172      sqlite3VdbeJumpHere(v, addrTop-1);
100173      sqlite3ClearTempRegCache(pParse);
100174    }else{
100175      /* Generate a subroutine that will fill an ephemeral table with
100176      ** the content of this subquery.  pItem->addrFillSub will point
100177      ** to the address of the generated subroutine.  pItem->regReturn
100178      ** is a register allocated to hold the subroutine return address
100179      */
100180      int topAddr;
100181      int onceAddr = 0;
100182      int retAddr;
100183      assert( pItem->addrFillSub==0 );
100184      pItem->regReturn = ++pParse->nMem;
100185      topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
100186      pItem->addrFillSub = topAddr+1;
100187      VdbeNoopComment((v, "materialize %s", pItem->pTab->zName));
100188      if( pItem->isCorrelated==0 ){
100189        /* If the subquery is not correlated and if we are not inside of
100190        ** a trigger, then we only need to compute the value of the subquery
100191        ** once. */
100192        onceAddr = sqlite3CodeOnce(pParse);
100193      }
100194      sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
100195      explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
100196      sqlite3Select(pParse, pSub, &dest);
100197      pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
100198      if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
100199      retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
100200      VdbeComment((v, "end %s", pItem->pTab->zName));
100201      sqlite3VdbeChangeP1(v, topAddr, retAddr);
100202      sqlite3ClearTempRegCache(pParse);
100203    }
100204    if( /*pParse->nErr ||*/ db->mallocFailed ){
100205      goto select_end;
100206    }
100207    pParse->nHeight -= sqlite3SelectExprHeight(p);
100208    pTabList = p->pSrc;
100209    if( !IgnorableOrderby(pDest) ){
100210      pOrderBy = p->pOrderBy;
100211    }
100212  }
100213  pEList = p->pEList;
100214#endif
100215  pWhere = p->pWhere;
100216  pGroupBy = p->pGroupBy;
100217  pHaving = p->pHaving;
100218  sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
100219
100220#ifndef SQLITE_OMIT_COMPOUND_SELECT
100221  /* If there is are a sequence of queries, do the earlier ones first.
100222  */
100223  if( p->pPrior ){
100224    if( p->pRightmost==0 ){
100225      Select *pLoop, *pRight = 0;
100226      int cnt = 0;
100227      int mxSelect;
100228      for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
100229        pLoop->pRightmost = p;
100230        pLoop->pNext = pRight;
100231        pRight = pLoop;
100232      }
100233      mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
100234      if( mxSelect && cnt>mxSelect ){
100235        sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
100236        goto select_end;
100237      }
100238    }
100239    rc = multiSelect(pParse, p, pDest);
100240    explainSetInteger(pParse->iSelectId, iRestoreSelectId);
100241    return rc;
100242  }
100243#endif
100244
100245  /* If there is both a GROUP BY and an ORDER BY clause and they are
100246  ** identical, then disable the ORDER BY clause since the GROUP BY
100247  ** will cause elements to come out in the correct order.  This is
100248  ** an optimization - the correct answer should result regardless.
100249  ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER
100250  ** to disable this optimization for testing purposes.
100251  */
100252  if( sqlite3ExprListCompare(p->pGroupBy, pOrderBy)==0
100253         && OptimizationEnabled(db, SQLITE_GroupByOrder) ){
100254    pOrderBy = 0;
100255  }
100256
100257  /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
100258  ** if the select-list is the same as the ORDER BY list, then this query
100259  ** can be rewritten as a GROUP BY. In other words, this:
100260  **
100261  **     SELECT DISTINCT xyz FROM ... ORDER BY xyz
100262  **
100263  ** is transformed to:
100264  **
100265  **     SELECT xyz FROM ... GROUP BY xyz
100266  **
100267  ** The second form is preferred as a single index (or temp-table) may be
100268  ** used for both the ORDER BY and DISTINCT processing. As originally
100269  ** written the query must use a temp-table for at least one of the ORDER
100270  ** BY and DISTINCT, and an index or separate temp-table for the other.
100271  */
100272  if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
100273   && sqlite3ExprListCompare(pOrderBy, p->pEList)==0
100274  ){
100275    p->selFlags &= ~SF_Distinct;
100276    p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
100277    pGroupBy = p->pGroupBy;
100278    pOrderBy = 0;
100279    /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
100280    ** the sDistinct.isTnct is still set.  Hence, isTnct represents the
100281    ** original setting of the SF_Distinct flag, not the current setting */
100282    assert( sDistinct.isTnct );
100283  }
100284
100285  /* If there is an ORDER BY clause, then this sorting
100286  ** index might end up being unused if the data can be
100287  ** extracted in pre-sorted order.  If that is the case, then the
100288  ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
100289  ** we figure out that the sorting index is not needed.  The addrSortIndex
100290  ** variable is used to facilitate that change.
100291  */
100292  if( pOrderBy ){
100293    KeyInfo *pKeyInfo;
100294    pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
100295    pOrderBy->iECursor = pParse->nTab++;
100296    p->addrOpenEphm[2] = addrSortIndex =
100297      sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
100298                           pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
100299                           (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
100300  }else{
100301    addrSortIndex = -1;
100302  }
100303
100304  /* If the output is destined for a temporary table, open that table.
100305  */
100306  if( pDest->eDest==SRT_EphemTab ){
100307    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
100308  }
100309
100310  /* Set the limiter.
100311  */
100312  iEnd = sqlite3VdbeMakeLabel(v);
100313  p->nSelectRow = (double)LARGEST_INT64;
100314  computeLimitRegisters(pParse, p, iEnd);
100315  if( p->iLimit==0 && addrSortIndex>=0 ){
100316    sqlite3VdbeGetOp(v, addrSortIndex)->opcode = OP_SorterOpen;
100317    p->selFlags |= SF_UseSorter;
100318  }
100319
100320  /* Open a virtual index to use for the distinct set.
100321  */
100322  if( p->selFlags & SF_Distinct ){
100323    sDistinct.tabTnct = pParse->nTab++;
100324    sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
100325                                sDistinct.tabTnct, 0, 0,
100326                                (char*)keyInfoFromExprList(pParse, p->pEList),
100327                                P4_KEYINFO_HANDOFF);
100328    sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
100329    sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
100330  }else{
100331    sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
100332  }
100333
100334  if( !isAgg && pGroupBy==0 ){
100335    /* No aggregate functions and no GROUP BY clause */
100336    ExprList *pDist = (sDistinct.isTnct ? p->pEList : 0);
100337
100338    /* Begin the database scan. */
100339    pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pOrderBy, pDist, 0,0);
100340    if( pWInfo==0 ) goto select_end;
100341    if( pWInfo->nRowOut < p->nSelectRow ) p->nSelectRow = pWInfo->nRowOut;
100342    if( pWInfo->eDistinct ) sDistinct.eTnctType = pWInfo->eDistinct;
100343    if( pOrderBy && pWInfo->nOBSat==pOrderBy->nExpr ) pOrderBy = 0;
100344
100345    /* If sorting index that was created by a prior OP_OpenEphemeral
100346    ** instruction ended up not being needed, then change the OP_OpenEphemeral
100347    ** into an OP_Noop.
100348    */
100349    if( addrSortIndex>=0 && pOrderBy==0 ){
100350      sqlite3VdbeChangeToNoop(v, addrSortIndex);
100351      p->addrOpenEphm[2] = -1;
100352    }
100353
100354    /* Use the standard inner loop. */
100355    selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, &sDistinct, pDest,
100356                    pWInfo->iContinue, pWInfo->iBreak);
100357
100358    /* End the database scan loop.
100359    */
100360    sqlite3WhereEnd(pWInfo);
100361  }else{
100362    /* This case when there exist aggregate functions or a GROUP BY clause
100363    ** or both */
100364    NameContext sNC;    /* Name context for processing aggregate information */
100365    int iAMem;          /* First Mem address for storing current GROUP BY */
100366    int iBMem;          /* First Mem address for previous GROUP BY */
100367    int iUseFlag;       /* Mem address holding flag indicating that at least
100368                        ** one row of the input to the aggregator has been
100369                        ** processed */
100370    int iAbortFlag;     /* Mem address which causes query abort if positive */
100371    int groupBySort;    /* Rows come from source in GROUP BY order */
100372    int addrEnd;        /* End of processing for this SELECT */
100373    int sortPTab = 0;   /* Pseudotable used to decode sorting results */
100374    int sortOut = 0;    /* Output register from the sorter */
100375
100376    /* Remove any and all aliases between the result set and the
100377    ** GROUP BY clause.
100378    */
100379    if( pGroupBy ){
100380      int k;                        /* Loop counter */
100381      struct ExprList_item *pItem;  /* For looping over expression in a list */
100382
100383      for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
100384        pItem->iAlias = 0;
100385      }
100386      for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
100387        pItem->iAlias = 0;
100388      }
100389      if( p->nSelectRow>(double)100 ) p->nSelectRow = (double)100;
100390    }else{
100391      p->nSelectRow = (double)1;
100392    }
100393
100394
100395    /* Create a label to jump to when we want to abort the query */
100396    addrEnd = sqlite3VdbeMakeLabel(v);
100397
100398    /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
100399    ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
100400    ** SELECT statement.
100401    */
100402    memset(&sNC, 0, sizeof(sNC));
100403    sNC.pParse = pParse;
100404    sNC.pSrcList = pTabList;
100405    sNC.pAggInfo = &sAggInfo;
100406    sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
100407    sAggInfo.pGroupBy = pGroupBy;
100408    sqlite3ExprAnalyzeAggList(&sNC, pEList);
100409    sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
100410    if( pHaving ){
100411      sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
100412    }
100413    sAggInfo.nAccumulator = sAggInfo.nColumn;
100414    for(i=0; i<sAggInfo.nFunc; i++){
100415      assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
100416      sNC.ncFlags |= NC_InAggFunc;
100417      sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
100418      sNC.ncFlags &= ~NC_InAggFunc;
100419    }
100420    if( db->mallocFailed ) goto select_end;
100421
100422    /* Processing for aggregates with GROUP BY is very different and
100423    ** much more complex than aggregates without a GROUP BY.
100424    */
100425    if( pGroupBy ){
100426      KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
100427      int j1;             /* A-vs-B comparision jump */
100428      int addrOutputRow;  /* Start of subroutine that outputs a result row */
100429      int regOutputRow;   /* Return address register for output subroutine */
100430      int addrSetAbort;   /* Set the abort flag and return */
100431      int addrTopOfLoop;  /* Top of the input loop */
100432      int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
100433      int addrReset;      /* Subroutine for resetting the accumulator */
100434      int regReset;       /* Return address register for reset subroutine */
100435
100436      /* If there is a GROUP BY clause we might need a sorting index to
100437      ** implement it.  Allocate that sorting index now.  If it turns out
100438      ** that we do not need it after all, the OP_SorterOpen instruction
100439      ** will be converted into a Noop.
100440      */
100441      sAggInfo.sortingIdx = pParse->nTab++;
100442      pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
100443      addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
100444          sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
100445          0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
100446
100447      /* Initialize memory locations used by GROUP BY aggregate processing
100448      */
100449      iUseFlag = ++pParse->nMem;
100450      iAbortFlag = ++pParse->nMem;
100451      regOutputRow = ++pParse->nMem;
100452      addrOutputRow = sqlite3VdbeMakeLabel(v);
100453      regReset = ++pParse->nMem;
100454      addrReset = sqlite3VdbeMakeLabel(v);
100455      iAMem = pParse->nMem + 1;
100456      pParse->nMem += pGroupBy->nExpr;
100457      iBMem = pParse->nMem + 1;
100458      pParse->nMem += pGroupBy->nExpr;
100459      sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
100460      VdbeComment((v, "clear abort flag"));
100461      sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
100462      VdbeComment((v, "indicate accumulator empty"));
100463      sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
100464
100465      /* Begin a loop that will extract all source rows in GROUP BY order.
100466      ** This might involve two separate loops with an OP_Sort in between, or
100467      ** it might be a single loop that uses an index to extract information
100468      ** in the right order to begin with.
100469      */
100470      sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
100471      pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0, 0, 0);
100472      if( pWInfo==0 ) goto select_end;
100473      if( pWInfo->nOBSat==pGroupBy->nExpr ){
100474        /* The optimizer is able to deliver rows in group by order so
100475        ** we do not have to sort.  The OP_OpenEphemeral table will be
100476        ** cancelled later because we still need to use the pKeyInfo
100477        */
100478        groupBySort = 0;
100479      }else{
100480        /* Rows are coming out in undetermined order.  We have to push
100481        ** each row into a sorting index, terminate the first loop,
100482        ** then loop over the sorting index in order to get the output
100483        ** in sorted order
100484        */
100485        int regBase;
100486        int regRecord;
100487        int nCol;
100488        int nGroupBy;
100489
100490        explainTempTable(pParse,
100491            (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
100492                    "DISTINCT" : "GROUP BY");
100493
100494        groupBySort = 1;
100495        nGroupBy = pGroupBy->nExpr;
100496        nCol = nGroupBy + 1;
100497        j = nGroupBy+1;
100498        for(i=0; i<sAggInfo.nColumn; i++){
100499          if( sAggInfo.aCol[i].iSorterColumn>=j ){
100500            nCol++;
100501            j++;
100502          }
100503        }
100504        regBase = sqlite3GetTempRange(pParse, nCol);
100505        sqlite3ExprCacheClear(pParse);
100506        sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
100507        sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
100508        j = nGroupBy+1;
100509        for(i=0; i<sAggInfo.nColumn; i++){
100510          struct AggInfo_col *pCol = &sAggInfo.aCol[i];
100511          if( pCol->iSorterColumn>=j ){
100512            int r1 = j + regBase;
100513            int r2;
100514
100515            r2 = sqlite3ExprCodeGetColumn(pParse,
100516                               pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);
100517            if( r1!=r2 ){
100518              sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
100519            }
100520            j++;
100521          }
100522        }
100523        regRecord = sqlite3GetTempReg(pParse);
100524        sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
100525        sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
100526        sqlite3ReleaseTempReg(pParse, regRecord);
100527        sqlite3ReleaseTempRange(pParse, regBase, nCol);
100528        sqlite3WhereEnd(pWInfo);
100529        sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
100530        sortOut = sqlite3GetTempReg(pParse);
100531        sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
100532        sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
100533        VdbeComment((v, "GROUP BY sort"));
100534        sAggInfo.useSortingIdx = 1;
100535        sqlite3ExprCacheClear(pParse);
100536      }
100537
100538      /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
100539      ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
100540      ** Then compare the current GROUP BY terms against the GROUP BY terms
100541      ** from the previous row currently stored in a0, a1, a2...
100542      */
100543      addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
100544      sqlite3ExprCacheClear(pParse);
100545      if( groupBySort ){
100546        sqlite3VdbeAddOp2(v, OP_SorterData, sAggInfo.sortingIdx, sortOut);
100547      }
100548      for(j=0; j<pGroupBy->nExpr; j++){
100549        if( groupBySort ){
100550          sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
100551          if( j==0 ) sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
100552        }else{
100553          sAggInfo.directMode = 1;
100554          sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
100555        }
100556      }
100557      sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
100558                          (char*)pKeyInfo, P4_KEYINFO);
100559      j1 = sqlite3VdbeCurrentAddr(v);
100560      sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
100561
100562      /* Generate code that runs whenever the GROUP BY changes.
100563      ** Changes in the GROUP BY are detected by the previous code
100564      ** block.  If there were no changes, this block is skipped.
100565      **
100566      ** This code copies current group by terms in b0,b1,b2,...
100567      ** over to a0,a1,a2.  It then calls the output subroutine
100568      ** and resets the aggregate accumulator registers in preparation
100569      ** for the next GROUP BY batch.
100570      */
100571      sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
100572      sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
100573      VdbeComment((v, "output one row"));
100574      sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
100575      VdbeComment((v, "check abort flag"));
100576      sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
100577      VdbeComment((v, "reset accumulator"));
100578
100579      /* Update the aggregate accumulators based on the content of
100580      ** the current row
100581      */
100582      sqlite3VdbeJumpHere(v, j1);
100583      updateAccumulator(pParse, &sAggInfo);
100584      sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
100585      VdbeComment((v, "indicate data in accumulator"));
100586
100587      /* End of the loop
100588      */
100589      if( groupBySort ){
100590        sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
100591      }else{
100592        sqlite3WhereEnd(pWInfo);
100593        sqlite3VdbeChangeToNoop(v, addrSortingIdx);
100594      }
100595
100596      /* Output the final row of result
100597      */
100598      sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
100599      VdbeComment((v, "output final row"));
100600
100601      /* Jump over the subroutines
100602      */
100603      sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
100604
100605      /* Generate a subroutine that outputs a single row of the result
100606      ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
100607      ** is less than or equal to zero, the subroutine is a no-op.  If
100608      ** the processing calls for the query to abort, this subroutine
100609      ** increments the iAbortFlag memory location before returning in
100610      ** order to signal the caller to abort.
100611      */
100612      addrSetAbort = sqlite3VdbeCurrentAddr(v);
100613      sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
100614      VdbeComment((v, "set abort flag"));
100615      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
100616      sqlite3VdbeResolveLabel(v, addrOutputRow);
100617      addrOutputRow = sqlite3VdbeCurrentAddr(v);
100618      sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
100619      VdbeComment((v, "Groupby result generator entry point"));
100620      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
100621      finalizeAggFunctions(pParse, &sAggInfo);
100622      sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
100623      selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
100624                      &sDistinct, pDest,
100625                      addrOutputRow+1, addrSetAbort);
100626      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
100627      VdbeComment((v, "end groupby result generator"));
100628
100629      /* Generate a subroutine that will reset the group-by accumulator
100630      */
100631      sqlite3VdbeResolveLabel(v, addrReset);
100632      resetAccumulator(pParse, &sAggInfo);
100633      sqlite3VdbeAddOp1(v, OP_Return, regReset);
100634
100635    } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
100636    else {
100637      ExprList *pDel = 0;
100638#ifndef SQLITE_OMIT_BTREECOUNT
100639      Table *pTab;
100640      if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
100641        /* If isSimpleCount() returns a pointer to a Table structure, then
100642        ** the SQL statement is of the form:
100643        **
100644        **   SELECT count(*) FROM <tbl>
100645        **
100646        ** where the Table structure returned represents table <tbl>.
100647        **
100648        ** This statement is so common that it is optimized specially. The
100649        ** OP_Count instruction is executed either on the intkey table that
100650        ** contains the data for table <tbl> or on one of its indexes. It
100651        ** is better to execute the op on an index, as indexes are almost
100652        ** always spread across less pages than their corresponding tables.
100653        */
100654        const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
100655        const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
100656        Index *pIdx;                         /* Iterator variable */
100657        KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
100658        Index *pBest = 0;                    /* Best index found so far */
100659        int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
100660
100661        sqlite3CodeVerifySchema(pParse, iDb);
100662        sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
100663
100664        /* Search for the index that has the least amount of columns. If
100665        ** there is such an index, and it has less columns than the table
100666        ** does, then we can assume that it consumes less space on disk and
100667        ** will therefore be cheaper to scan to determine the query result.
100668        ** In this case set iRoot to the root page number of the index b-tree
100669        ** and pKeyInfo to the KeyInfo structure required to navigate the
100670        ** index.
100671        **
100672        ** (2011-04-15) Do not do a full scan of an unordered index.
100673        **
100674        ** In practice the KeyInfo structure will not be used. It is only
100675        ** passed to keep OP_OpenRead happy.
100676        */
100677        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
100678          if( pIdx->bUnordered==0 && (!pBest || pIdx->nColumn<pBest->nColumn) ){
100679            pBest = pIdx;
100680          }
100681        }
100682        if( pBest && pBest->nColumn<pTab->nCol ){
100683          iRoot = pBest->tnum;
100684          pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest);
100685        }
100686
100687        /* Open a read-only cursor, execute the OP_Count, close the cursor. */
100688        sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb);
100689        if( pKeyInfo ){
100690          sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF);
100691        }
100692        sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
100693        sqlite3VdbeAddOp1(v, OP_Close, iCsr);
100694        explainSimpleCount(pParse, pTab, pBest);
100695      }else
100696#endif /* SQLITE_OMIT_BTREECOUNT */
100697      {
100698        /* Check if the query is of one of the following forms:
100699        **
100700        **   SELECT min(x) FROM ...
100701        **   SELECT max(x) FROM ...
100702        **
100703        ** If it is, then ask the code in where.c to attempt to sort results
100704        ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
100705        ** If where.c is able to produce results sorted in this order, then
100706        ** add vdbe code to break out of the processing loop after the
100707        ** first iteration (since the first iteration of the loop is
100708        ** guaranteed to operate on the row with the minimum or maximum
100709        ** value of x, the only row required).
100710        **
100711        ** A special flag must be passed to sqlite3WhereBegin() to slightly
100712        ** modify behavior as follows:
100713        **
100714        **   + If the query is a "SELECT min(x)", then the loop coded by
100715        **     where.c should not iterate over any values with a NULL value
100716        **     for x.
100717        **
100718        **   + The optimizer code in where.c (the thing that decides which
100719        **     index or indices to use) should place a different priority on
100720        **     satisfying the 'ORDER BY' clause than it does in other cases.
100721        **     Refer to code and comments in where.c for details.
100722        */
100723        ExprList *pMinMax = 0;
100724        u8 flag = WHERE_ORDERBY_NORMAL;
100725
100726        assert( p->pGroupBy==0 );
100727        assert( flag==0 );
100728        if( p->pHaving==0 ){
100729          flag = minMaxQuery(&sAggInfo, &pMinMax);
100730        }
100731        assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) );
100732
100733        if( flag ){
100734          pMinMax = sqlite3ExprListDup(db, pMinMax, 0);
100735          pDel = pMinMax;
100736          if( pMinMax && !db->mallocFailed ){
100737            pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
100738            pMinMax->a[0].pExpr->op = TK_COLUMN;
100739          }
100740        }
100741
100742        /* This case runs if the aggregate has no GROUP BY clause.  The
100743        ** processing is much simpler since there is only a single row
100744        ** of output.
100745        */
100746        resetAccumulator(pParse, &sAggInfo);
100747        pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0);
100748        if( pWInfo==0 ){
100749          sqlite3ExprListDelete(db, pDel);
100750          goto select_end;
100751        }
100752        updateAccumulator(pParse, &sAggInfo);
100753        assert( pMinMax==0 || pMinMax->nExpr==1 );
100754        if( pWInfo->nOBSat>0 ){
100755          sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
100756          VdbeComment((v, "%s() by index",
100757                (flag==WHERE_ORDERBY_MIN?"min":"max")));
100758        }
100759        sqlite3WhereEnd(pWInfo);
100760        finalizeAggFunctions(pParse, &sAggInfo);
100761      }
100762
100763      pOrderBy = 0;
100764      sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
100765      selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, 0,
100766                      pDest, addrEnd, addrEnd);
100767      sqlite3ExprListDelete(db, pDel);
100768    }
100769    sqlite3VdbeResolveLabel(v, addrEnd);
100770
100771  } /* endif aggregate query */
100772
100773  if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
100774    explainTempTable(pParse, "DISTINCT");
100775  }
100776
100777  /* If there is an ORDER BY clause, then we need to sort the results
100778  ** and send them to the callback one by one.
100779  */
100780  if( pOrderBy ){
100781    explainTempTable(pParse, "ORDER BY");
100782    generateSortTail(pParse, p, v, pEList->nExpr, pDest);
100783  }
100784
100785  /* Jump here to skip this query
100786  */
100787  sqlite3VdbeResolveLabel(v, iEnd);
100788
100789  /* The SELECT was successfully coded.   Set the return code to 0
100790  ** to indicate no errors.
100791  */
100792  rc = 0;
100793
100794  /* Control jumps to here if an error is encountered above, or upon
100795  ** successful coding of the SELECT.
100796  */
100797select_end:
100798  explainSetInteger(pParse->iSelectId, iRestoreSelectId);
100799
100800  /* Identify column names if results of the SELECT are to be output.
100801  */
100802  if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
100803    generateColumnNames(pParse, pTabList, pEList);
100804  }
100805
100806  sqlite3DbFree(db, sAggInfo.aCol);
100807  sqlite3DbFree(db, sAggInfo.aFunc);
100808  return rc;
100809}
100810
100811#if defined(SQLITE_ENABLE_TREE_EXPLAIN)
100812/*
100813** Generate a human-readable description of a the Select object.
100814*/
100815static void explainOneSelect(Vdbe *pVdbe, Select *p){
100816  sqlite3ExplainPrintf(pVdbe, "SELECT ");
100817  if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
100818    if( p->selFlags & SF_Distinct ){
100819      sqlite3ExplainPrintf(pVdbe, "DISTINCT ");
100820    }
100821    if( p->selFlags & SF_Aggregate ){
100822      sqlite3ExplainPrintf(pVdbe, "agg_flag ");
100823    }
100824    sqlite3ExplainNL(pVdbe);
100825    sqlite3ExplainPrintf(pVdbe, "   ");
100826  }
100827  sqlite3ExplainExprList(pVdbe, p->pEList);
100828  sqlite3ExplainNL(pVdbe);
100829  if( p->pSrc && p->pSrc->nSrc ){
100830    int i;
100831    sqlite3ExplainPrintf(pVdbe, "FROM ");
100832    sqlite3ExplainPush(pVdbe);
100833    for(i=0; i<p->pSrc->nSrc; i++){
100834      struct SrcList_item *pItem = &p->pSrc->a[i];
100835      sqlite3ExplainPrintf(pVdbe, "{%d,*} = ", pItem->iCursor);
100836      if( pItem->pSelect ){
100837        sqlite3ExplainSelect(pVdbe, pItem->pSelect);
100838        if( pItem->pTab ){
100839          sqlite3ExplainPrintf(pVdbe, " (tabname=%s)", pItem->pTab->zName);
100840        }
100841      }else if( pItem->zName ){
100842        sqlite3ExplainPrintf(pVdbe, "%s", pItem->zName);
100843      }
100844      if( pItem->zAlias ){
100845        sqlite3ExplainPrintf(pVdbe, " (AS %s)", pItem->zAlias);
100846      }
100847      if( pItem->jointype & JT_LEFT ){
100848        sqlite3ExplainPrintf(pVdbe, " LEFT-JOIN");
100849      }
100850      sqlite3ExplainNL(pVdbe);
100851    }
100852    sqlite3ExplainPop(pVdbe);
100853  }
100854  if( p->pWhere ){
100855    sqlite3ExplainPrintf(pVdbe, "WHERE ");
100856    sqlite3ExplainExpr(pVdbe, p->pWhere);
100857    sqlite3ExplainNL(pVdbe);
100858  }
100859  if( p->pGroupBy ){
100860    sqlite3ExplainPrintf(pVdbe, "GROUPBY ");
100861    sqlite3ExplainExprList(pVdbe, p->pGroupBy);
100862    sqlite3ExplainNL(pVdbe);
100863  }
100864  if( p->pHaving ){
100865    sqlite3ExplainPrintf(pVdbe, "HAVING ");
100866    sqlite3ExplainExpr(pVdbe, p->pHaving);
100867    sqlite3ExplainNL(pVdbe);
100868  }
100869  if( p->pOrderBy ){
100870    sqlite3ExplainPrintf(pVdbe, "ORDERBY ");
100871    sqlite3ExplainExprList(pVdbe, p->pOrderBy);
100872    sqlite3ExplainNL(pVdbe);
100873  }
100874  if( p->pLimit ){
100875    sqlite3ExplainPrintf(pVdbe, "LIMIT ");
100876    sqlite3ExplainExpr(pVdbe, p->pLimit);
100877    sqlite3ExplainNL(pVdbe);
100878  }
100879  if( p->pOffset ){
100880    sqlite3ExplainPrintf(pVdbe, "OFFSET ");
100881    sqlite3ExplainExpr(pVdbe, p->pOffset);
100882    sqlite3ExplainNL(pVdbe);
100883  }
100884}
100885SQLITE_PRIVATE void sqlite3ExplainSelect(Vdbe *pVdbe, Select *p){
100886  if( p==0 ){
100887    sqlite3ExplainPrintf(pVdbe, "(null-select)");
100888    return;
100889  }
100890  while( p->pPrior ){
100891    p->pPrior->pNext = p;
100892    p = p->pPrior;
100893  }
100894  sqlite3ExplainPush(pVdbe);
100895  while( p ){
100896    explainOneSelect(pVdbe, p);
100897    p = p->pNext;
100898    if( p==0 ) break;
100899    sqlite3ExplainNL(pVdbe);
100900    sqlite3ExplainPrintf(pVdbe, "%s\n", selectOpName(p->op));
100901  }
100902  sqlite3ExplainPrintf(pVdbe, "END");
100903  sqlite3ExplainPop(pVdbe);
100904}
100905
100906/* End of the structure debug printing code
100907*****************************************************************************/
100908#endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
100909
100910/************** End of select.c **********************************************/
100911/************** Begin file table.c *******************************************/
100912/*
100913** 2001 September 15
100914**
100915** The author disclaims copyright to this source code.  In place of
100916** a legal notice, here is a blessing:
100917**
100918**    May you do good and not evil.
100919**    May you find forgiveness for yourself and forgive others.
100920**    May you share freely, never taking more than you give.
100921**
100922*************************************************************************
100923** This file contains the sqlite3_get_table() and sqlite3_free_table()
100924** interface routines.  These are just wrappers around the main
100925** interface routine of sqlite3_exec().
100926**
100927** These routines are in a separate files so that they will not be linked
100928** if they are not used.
100929*/
100930/* #include <stdlib.h> */
100931/* #include <string.h> */
100932
100933#ifndef SQLITE_OMIT_GET_TABLE
100934
100935/*
100936** This structure is used to pass data from sqlite3_get_table() through
100937** to the callback function is uses to build the result.
100938*/
100939typedef struct TabResult {
100940  char **azResult;   /* Accumulated output */
100941  char *zErrMsg;     /* Error message text, if an error occurs */
100942  int nAlloc;        /* Slots allocated for azResult[] */
100943  int nRow;          /* Number of rows in the result */
100944  int nColumn;       /* Number of columns in the result */
100945  int nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */
100946  int rc;            /* Return code from sqlite3_exec() */
100947} TabResult;
100948
100949/*
100950** This routine is called once for each row in the result table.  Its job
100951** is to fill in the TabResult structure appropriately, allocating new
100952** memory as necessary.
100953*/
100954static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
100955  TabResult *p = (TabResult*)pArg;  /* Result accumulator */
100956  int need;                         /* Slots needed in p->azResult[] */
100957  int i;                            /* Loop counter */
100958  char *z;                          /* A single column of result */
100959
100960  /* Make sure there is enough space in p->azResult to hold everything
100961  ** we need to remember from this invocation of the callback.
100962  */
100963  if( p->nRow==0 && argv!=0 ){
100964    need = nCol*2;
100965  }else{
100966    need = nCol;
100967  }
100968  if( p->nData + need > p->nAlloc ){
100969    char **azNew;
100970    p->nAlloc = p->nAlloc*2 + need;
100971    azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
100972    if( azNew==0 ) goto malloc_failed;
100973    p->azResult = azNew;
100974  }
100975
100976  /* If this is the first row, then generate an extra row containing
100977  ** the names of all columns.
100978  */
100979  if( p->nRow==0 ){
100980    p->nColumn = nCol;
100981    for(i=0; i<nCol; i++){
100982      z = sqlite3_mprintf("%s", colv[i]);
100983      if( z==0 ) goto malloc_failed;
100984      p->azResult[p->nData++] = z;
100985    }
100986  }else if( p->nColumn!=nCol ){
100987    sqlite3_free(p->zErrMsg);
100988    p->zErrMsg = sqlite3_mprintf(
100989       "sqlite3_get_table() called with two or more incompatible queries"
100990    );
100991    p->rc = SQLITE_ERROR;
100992    return 1;
100993  }
100994
100995  /* Copy over the row data
100996  */
100997  if( argv!=0 ){
100998    for(i=0; i<nCol; i++){
100999      if( argv[i]==0 ){
101000        z = 0;
101001      }else{
101002        int n = sqlite3Strlen30(argv[i])+1;
101003        z = sqlite3_malloc( n );
101004        if( z==0 ) goto malloc_failed;
101005        memcpy(z, argv[i], n);
101006      }
101007      p->azResult[p->nData++] = z;
101008    }
101009    p->nRow++;
101010  }
101011  return 0;
101012
101013malloc_failed:
101014  p->rc = SQLITE_NOMEM;
101015  return 1;
101016}
101017
101018/*
101019** Query the database.  But instead of invoking a callback for each row,
101020** malloc() for space to hold the result and return the entire results
101021** at the conclusion of the call.
101022**
101023** The result that is written to ***pazResult is held in memory obtained
101024** from malloc().  But the caller cannot free this memory directly.
101025** Instead, the entire table should be passed to sqlite3_free_table() when
101026** the calling procedure is finished using it.
101027*/
101028SQLITE_API int sqlite3_get_table(
101029  sqlite3 *db,                /* The database on which the SQL executes */
101030  const char *zSql,           /* The SQL to be executed */
101031  char ***pazResult,          /* Write the result table here */
101032  int *pnRow,                 /* Write the number of rows in the result here */
101033  int *pnColumn,              /* Write the number of columns of result here */
101034  char **pzErrMsg             /* Write error messages here */
101035){
101036  int rc;
101037  TabResult res;
101038
101039  *pazResult = 0;
101040  if( pnColumn ) *pnColumn = 0;
101041  if( pnRow ) *pnRow = 0;
101042  if( pzErrMsg ) *pzErrMsg = 0;
101043  res.zErrMsg = 0;
101044  res.nRow = 0;
101045  res.nColumn = 0;
101046  res.nData = 1;
101047  res.nAlloc = 20;
101048  res.rc = SQLITE_OK;
101049  res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
101050  if( res.azResult==0 ){
101051     db->errCode = SQLITE_NOMEM;
101052     return SQLITE_NOMEM;
101053  }
101054  res.azResult[0] = 0;
101055  rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
101056  assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
101057  res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
101058  if( (rc&0xff)==SQLITE_ABORT ){
101059    sqlite3_free_table(&res.azResult[1]);
101060    if( res.zErrMsg ){
101061      if( pzErrMsg ){
101062        sqlite3_free(*pzErrMsg);
101063        *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
101064      }
101065      sqlite3_free(res.zErrMsg);
101066    }
101067    db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
101068    return res.rc;
101069  }
101070  sqlite3_free(res.zErrMsg);
101071  if( rc!=SQLITE_OK ){
101072    sqlite3_free_table(&res.azResult[1]);
101073    return rc;
101074  }
101075  if( res.nAlloc>res.nData ){
101076    char **azNew;
101077    azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
101078    if( azNew==0 ){
101079      sqlite3_free_table(&res.azResult[1]);
101080      db->errCode = SQLITE_NOMEM;
101081      return SQLITE_NOMEM;
101082    }
101083    res.azResult = azNew;
101084  }
101085  *pazResult = &res.azResult[1];
101086  if( pnColumn ) *pnColumn = res.nColumn;
101087  if( pnRow ) *pnRow = res.nRow;
101088  return rc;
101089}
101090
101091/*
101092** This routine frees the space the sqlite3_get_table() malloced.
101093*/
101094SQLITE_API void sqlite3_free_table(
101095  char **azResult            /* Result returned from from sqlite3_get_table() */
101096){
101097  if( azResult ){
101098    int i, n;
101099    azResult--;
101100    assert( azResult!=0 );
101101    n = SQLITE_PTR_TO_INT(azResult[0]);
101102    for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
101103    sqlite3_free(azResult);
101104  }
101105}
101106
101107#endif /* SQLITE_OMIT_GET_TABLE */
101108
101109/************** End of table.c ***********************************************/
101110/************** Begin file trigger.c *****************************************/
101111/*
101112**
101113** The author disclaims copyright to this source code.  In place of
101114** a legal notice, here is a blessing:
101115**
101116**    May you do good and not evil.
101117**    May you find forgiveness for yourself and forgive others.
101118**    May you share freely, never taking more than you give.
101119**
101120*************************************************************************
101121** This file contains the implementation for TRIGGERs
101122*/
101123
101124#ifndef SQLITE_OMIT_TRIGGER
101125/*
101126** Delete a linked list of TriggerStep structures.
101127*/
101128SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
101129  while( pTriggerStep ){
101130    TriggerStep * pTmp = pTriggerStep;
101131    pTriggerStep = pTriggerStep->pNext;
101132
101133    sqlite3ExprDelete(db, pTmp->pWhere);
101134    sqlite3ExprListDelete(db, pTmp->pExprList);
101135    sqlite3SelectDelete(db, pTmp->pSelect);
101136    sqlite3IdListDelete(db, pTmp->pIdList);
101137
101138    sqlite3DbFree(db, pTmp);
101139  }
101140}
101141
101142/*
101143** Given table pTab, return a list of all the triggers attached to
101144** the table. The list is connected by Trigger.pNext pointers.
101145**
101146** All of the triggers on pTab that are in the same database as pTab
101147** are already attached to pTab->pTrigger.  But there might be additional
101148** triggers on pTab in the TEMP schema.  This routine prepends all
101149** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
101150** and returns the combined list.
101151**
101152** To state it another way:  This routine returns a list of all triggers
101153** that fire off of pTab.  The list will include any TEMP triggers on
101154** pTab as well as the triggers lised in pTab->pTrigger.
101155*/
101156SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
101157  Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
101158  Trigger *pList = 0;                  /* List of triggers to return */
101159
101160  if( pParse->disableTriggers ){
101161    return 0;
101162  }
101163
101164  if( pTmpSchema!=pTab->pSchema ){
101165    HashElem *p;
101166    assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
101167    for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
101168      Trigger *pTrig = (Trigger *)sqliteHashData(p);
101169      if( pTrig->pTabSchema==pTab->pSchema
101170       && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
101171      ){
101172        pTrig->pNext = (pList ? pList : pTab->pTrigger);
101173        pList = pTrig;
101174      }
101175    }
101176  }
101177
101178  return (pList ? pList : pTab->pTrigger);
101179}
101180
101181/*
101182** This is called by the parser when it sees a CREATE TRIGGER statement
101183** up to the point of the BEGIN before the trigger actions.  A Trigger
101184** structure is generated based on the information available and stored
101185** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
101186** sqlite3FinishTrigger() function is called to complete the trigger
101187** construction process.
101188*/
101189SQLITE_PRIVATE void sqlite3BeginTrigger(
101190  Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
101191  Token *pName1,      /* The name of the trigger */
101192  Token *pName2,      /* The name of the trigger */
101193  int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
101194  int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
101195  IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
101196  SrcList *pTableName,/* The name of the table/view the trigger applies to */
101197  Expr *pWhen,        /* WHEN clause */
101198  int isTemp,         /* True if the TEMPORARY keyword is present */
101199  int noErr           /* Suppress errors if the trigger already exists */
101200){
101201  Trigger *pTrigger = 0;  /* The new trigger */
101202  Table *pTab;            /* Table that the trigger fires off of */
101203  char *zName = 0;        /* Name of the trigger */
101204  sqlite3 *db = pParse->db;  /* The database connection */
101205  int iDb;                /* The database to store the trigger in */
101206  Token *pName;           /* The unqualified db name */
101207  DbFixer sFix;           /* State vector for the DB fixer */
101208  int iTabDb;             /* Index of the database holding pTab */
101209
101210  assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
101211  assert( pName2!=0 );
101212  assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
101213  assert( op>0 && op<0xff );
101214  if( isTemp ){
101215    /* If TEMP was specified, then the trigger name may not be qualified. */
101216    if( pName2->n>0 ){
101217      sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
101218      goto trigger_cleanup;
101219    }
101220    iDb = 1;
101221    pName = pName1;
101222  }else{
101223    /* Figure out the db that the trigger will be created in */
101224    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
101225    if( iDb<0 ){
101226      goto trigger_cleanup;
101227    }
101228  }
101229  if( !pTableName || db->mallocFailed ){
101230    goto trigger_cleanup;
101231  }
101232
101233  /* A long-standing parser bug is that this syntax was allowed:
101234  **
101235  **    CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
101236  **                                                 ^^^^^^^^
101237  **
101238  ** To maintain backwards compatibility, ignore the database
101239  ** name on pTableName if we are reparsing our of SQLITE_MASTER.
101240  */
101241  if( db->init.busy && iDb!=1 ){
101242    sqlite3DbFree(db, pTableName->a[0].zDatabase);
101243    pTableName->a[0].zDatabase = 0;
101244  }
101245
101246  /* If the trigger name was unqualified, and the table is a temp table,
101247  ** then set iDb to 1 to create the trigger in the temporary database.
101248  ** If sqlite3SrcListLookup() returns 0, indicating the table does not
101249  ** exist, the error is caught by the block below.
101250  */
101251  pTab = sqlite3SrcListLookup(pParse, pTableName);
101252  if( db->init.busy==0 && pName2->n==0 && pTab
101253        && pTab->pSchema==db->aDb[1].pSchema ){
101254    iDb = 1;
101255  }
101256
101257  /* Ensure the table name matches database name and that the table exists */
101258  if( db->mallocFailed ) goto trigger_cleanup;
101259  assert( pTableName->nSrc==1 );
101260  if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) &&
101261      sqlite3FixSrcList(&sFix, pTableName) ){
101262    goto trigger_cleanup;
101263  }
101264  pTab = sqlite3SrcListLookup(pParse, pTableName);
101265  if( !pTab ){
101266    /* The table does not exist. */
101267    if( db->init.iDb==1 ){
101268      /* Ticket #3810.
101269      ** Normally, whenever a table is dropped, all associated triggers are
101270      ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
101271      ** and the table is dropped by a different database connection, the
101272      ** trigger is not visible to the database connection that does the
101273      ** drop so the trigger cannot be dropped.  This results in an
101274      ** "orphaned trigger" - a trigger whose associated table is missing.
101275      */
101276      db->init.orphanTrigger = 1;
101277    }
101278    goto trigger_cleanup;
101279  }
101280  if( IsVirtual(pTab) ){
101281    sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
101282    goto trigger_cleanup;
101283  }
101284
101285  /* Check that the trigger name is not reserved and that no trigger of the
101286  ** specified name exists */
101287  zName = sqlite3NameFromToken(db, pName);
101288  if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
101289    goto trigger_cleanup;
101290  }
101291  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
101292  if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
101293                      zName, sqlite3Strlen30(zName)) ){
101294    if( !noErr ){
101295      sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
101296    }else{
101297      assert( !db->init.busy );
101298      sqlite3CodeVerifySchema(pParse, iDb);
101299    }
101300    goto trigger_cleanup;
101301  }
101302
101303  /* Do not create a trigger on a system table */
101304  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
101305    sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
101306    pParse->nErr++;
101307    goto trigger_cleanup;
101308  }
101309
101310  /* INSTEAD of triggers are only for views and views only support INSTEAD
101311  ** of triggers.
101312  */
101313  if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
101314    sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
101315        (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
101316    goto trigger_cleanup;
101317  }
101318  if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
101319    sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
101320        " trigger on table: %S", pTableName, 0);
101321    goto trigger_cleanup;
101322  }
101323  iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
101324
101325#ifndef SQLITE_OMIT_AUTHORIZATION
101326  {
101327    int code = SQLITE_CREATE_TRIGGER;
101328    const char *zDb = db->aDb[iTabDb].zName;
101329    const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
101330    if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
101331    if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
101332      goto trigger_cleanup;
101333    }
101334    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
101335      goto trigger_cleanup;
101336    }
101337  }
101338#endif
101339
101340  /* INSTEAD OF triggers can only appear on views and BEFORE triggers
101341  ** cannot appear on views.  So we might as well translate every
101342  ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
101343  ** elsewhere.
101344  */
101345  if (tr_tm == TK_INSTEAD){
101346    tr_tm = TK_BEFORE;
101347  }
101348
101349  /* Build the Trigger object */
101350  pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
101351  if( pTrigger==0 ) goto trigger_cleanup;
101352  pTrigger->zName = zName;
101353  zName = 0;
101354  pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
101355  pTrigger->pSchema = db->aDb[iDb].pSchema;
101356  pTrigger->pTabSchema = pTab->pSchema;
101357  pTrigger->op = (u8)op;
101358  pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
101359  pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
101360  pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
101361  assert( pParse->pNewTrigger==0 );
101362  pParse->pNewTrigger = pTrigger;
101363
101364trigger_cleanup:
101365  sqlite3DbFree(db, zName);
101366  sqlite3SrcListDelete(db, pTableName);
101367  sqlite3IdListDelete(db, pColumns);
101368  sqlite3ExprDelete(db, pWhen);
101369  if( !pParse->pNewTrigger ){
101370    sqlite3DeleteTrigger(db, pTrigger);
101371  }else{
101372    assert( pParse->pNewTrigger==pTrigger );
101373  }
101374}
101375
101376/*
101377** This routine is called after all of the trigger actions have been parsed
101378** in order to complete the process of building the trigger.
101379*/
101380SQLITE_PRIVATE void sqlite3FinishTrigger(
101381  Parse *pParse,          /* Parser context */
101382  TriggerStep *pStepList, /* The triggered program */
101383  Token *pAll             /* Token that describes the complete CREATE TRIGGER */
101384){
101385  Trigger *pTrig = pParse->pNewTrigger;   /* Trigger being finished */
101386  char *zName;                            /* Name of trigger */
101387  sqlite3 *db = pParse->db;               /* The database */
101388  DbFixer sFix;                           /* Fixer object */
101389  int iDb;                                /* Database containing the trigger */
101390  Token nameToken;                        /* Trigger name for error reporting */
101391
101392  pParse->pNewTrigger = 0;
101393  if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
101394  zName = pTrig->zName;
101395  iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
101396  pTrig->step_list = pStepList;
101397  while( pStepList ){
101398    pStepList->pTrig = pTrig;
101399    pStepList = pStepList->pNext;
101400  }
101401  nameToken.z = pTrig->zName;
101402  nameToken.n = sqlite3Strlen30(nameToken.z);
101403  if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken)
101404          && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
101405    goto triggerfinish_cleanup;
101406  }
101407
101408  /* if we are not initializing,
101409  ** build the sqlite_master entry
101410  */
101411  if( !db->init.busy ){
101412    Vdbe *v;
101413    char *z;
101414
101415    /* Make an entry in the sqlite_master table */
101416    v = sqlite3GetVdbe(pParse);
101417    if( v==0 ) goto triggerfinish_cleanup;
101418    sqlite3BeginWriteOperation(pParse, 0, iDb);
101419    z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
101420    sqlite3NestedParse(pParse,
101421       "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
101422       db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
101423       pTrig->table, z);
101424    sqlite3DbFree(db, z);
101425    sqlite3ChangeCookie(pParse, iDb);
101426    sqlite3VdbeAddParseSchemaOp(v, iDb,
101427        sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
101428  }
101429
101430  if( db->init.busy ){
101431    Trigger *pLink = pTrig;
101432    Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
101433    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
101434    pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
101435    if( pTrig ){
101436      db->mallocFailed = 1;
101437    }else if( pLink->pSchema==pLink->pTabSchema ){
101438      Table *pTab;
101439      int n = sqlite3Strlen30(pLink->table);
101440      pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
101441      assert( pTab!=0 );
101442      pLink->pNext = pTab->pTrigger;
101443      pTab->pTrigger = pLink;
101444    }
101445  }
101446
101447triggerfinish_cleanup:
101448  sqlite3DeleteTrigger(db, pTrig);
101449  assert( !pParse->pNewTrigger );
101450  sqlite3DeleteTriggerStep(db, pStepList);
101451}
101452
101453/*
101454** Turn a SELECT statement (that the pSelect parameter points to) into
101455** a trigger step.  Return a pointer to a TriggerStep structure.
101456**
101457** The parser calls this routine when it finds a SELECT statement in
101458** body of a TRIGGER.
101459*/
101460SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
101461  TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
101462  if( pTriggerStep==0 ) {
101463    sqlite3SelectDelete(db, pSelect);
101464    return 0;
101465  }
101466  pTriggerStep->op = TK_SELECT;
101467  pTriggerStep->pSelect = pSelect;
101468  pTriggerStep->orconf = OE_Default;
101469  return pTriggerStep;
101470}
101471
101472/*
101473** Allocate space to hold a new trigger step.  The allocated space
101474** holds both the TriggerStep object and the TriggerStep.target.z string.
101475**
101476** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
101477*/
101478static TriggerStep *triggerStepAllocate(
101479  sqlite3 *db,                /* Database connection */
101480  u8 op,                      /* Trigger opcode */
101481  Token *pName                /* The target name */
101482){
101483  TriggerStep *pTriggerStep;
101484
101485  pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
101486  if( pTriggerStep ){
101487    char *z = (char*)&pTriggerStep[1];
101488    memcpy(z, pName->z, pName->n);
101489    pTriggerStep->target.z = z;
101490    pTriggerStep->target.n = pName->n;
101491    pTriggerStep->op = op;
101492  }
101493  return pTriggerStep;
101494}
101495
101496/*
101497** Build a trigger step out of an INSERT statement.  Return a pointer
101498** to the new trigger step.
101499**
101500** The parser calls this routine when it sees an INSERT inside the
101501** body of a trigger.
101502*/
101503SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
101504  sqlite3 *db,        /* The database connection */
101505  Token *pTableName,  /* Name of the table into which we insert */
101506  IdList *pColumn,    /* List of columns in pTableName to insert into */
101507  ExprList *pEList,   /* The VALUE clause: a list of values to be inserted */
101508  Select *pSelect,    /* A SELECT statement that supplies values */
101509  u8 orconf           /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
101510){
101511  TriggerStep *pTriggerStep;
101512
101513  assert(pEList == 0 || pSelect == 0);
101514  assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
101515
101516  pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
101517  if( pTriggerStep ){
101518    pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
101519    pTriggerStep->pIdList = pColumn;
101520    pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
101521    pTriggerStep->orconf = orconf;
101522  }else{
101523    sqlite3IdListDelete(db, pColumn);
101524  }
101525  sqlite3ExprListDelete(db, pEList);
101526  sqlite3SelectDelete(db, pSelect);
101527
101528  return pTriggerStep;
101529}
101530
101531/*
101532** Construct a trigger step that implements an UPDATE statement and return
101533** a pointer to that trigger step.  The parser calls this routine when it
101534** sees an UPDATE statement inside the body of a CREATE TRIGGER.
101535*/
101536SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
101537  sqlite3 *db,         /* The database connection */
101538  Token *pTableName,   /* Name of the table to be updated */
101539  ExprList *pEList,    /* The SET clause: list of column and new values */
101540  Expr *pWhere,        /* The WHERE clause */
101541  u8 orconf            /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
101542){
101543  TriggerStep *pTriggerStep;
101544
101545  pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
101546  if( pTriggerStep ){
101547    pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
101548    pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
101549    pTriggerStep->orconf = orconf;
101550  }
101551  sqlite3ExprListDelete(db, pEList);
101552  sqlite3ExprDelete(db, pWhere);
101553  return pTriggerStep;
101554}
101555
101556/*
101557** Construct a trigger step that implements a DELETE statement and return
101558** a pointer to that trigger step.  The parser calls this routine when it
101559** sees a DELETE statement inside the body of a CREATE TRIGGER.
101560*/
101561SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
101562  sqlite3 *db,            /* Database connection */
101563  Token *pTableName,      /* The table from which rows are deleted */
101564  Expr *pWhere            /* The WHERE clause */
101565){
101566  TriggerStep *pTriggerStep;
101567
101568  pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
101569  if( pTriggerStep ){
101570    pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
101571    pTriggerStep->orconf = OE_Default;
101572  }
101573  sqlite3ExprDelete(db, pWhere);
101574  return pTriggerStep;
101575}
101576
101577/*
101578** Recursively delete a Trigger structure
101579*/
101580SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
101581  if( pTrigger==0 ) return;
101582  sqlite3DeleteTriggerStep(db, pTrigger->step_list);
101583  sqlite3DbFree(db, pTrigger->zName);
101584  sqlite3DbFree(db, pTrigger->table);
101585  sqlite3ExprDelete(db, pTrigger->pWhen);
101586  sqlite3IdListDelete(db, pTrigger->pColumns);
101587  sqlite3DbFree(db, pTrigger);
101588}
101589
101590/*
101591** This function is called to drop a trigger from the database schema.
101592**
101593** This may be called directly from the parser and therefore identifies
101594** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
101595** same job as this routine except it takes a pointer to the trigger
101596** instead of the trigger name.
101597**/
101598SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
101599  Trigger *pTrigger = 0;
101600  int i;
101601  const char *zDb;
101602  const char *zName;
101603  int nName;
101604  sqlite3 *db = pParse->db;
101605
101606  if( db->mallocFailed ) goto drop_trigger_cleanup;
101607  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
101608    goto drop_trigger_cleanup;
101609  }
101610
101611  assert( pName->nSrc==1 );
101612  zDb = pName->a[0].zDatabase;
101613  zName = pName->a[0].zName;
101614  nName = sqlite3Strlen30(zName);
101615  assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
101616  for(i=OMIT_TEMPDB; i<db->nDb; i++){
101617    int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
101618    if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
101619    assert( sqlite3SchemaMutexHeld(db, j, 0) );
101620    pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
101621    if( pTrigger ) break;
101622  }
101623  if( !pTrigger ){
101624    if( !noErr ){
101625      sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
101626    }else{
101627      sqlite3CodeVerifyNamedSchema(pParse, zDb);
101628    }
101629    pParse->checkSchema = 1;
101630    goto drop_trigger_cleanup;
101631  }
101632  sqlite3DropTriggerPtr(pParse, pTrigger);
101633
101634drop_trigger_cleanup:
101635  sqlite3SrcListDelete(db, pName);
101636}
101637
101638/*
101639** Return a pointer to the Table structure for the table that a trigger
101640** is set on.
101641*/
101642static Table *tableOfTrigger(Trigger *pTrigger){
101643  int n = sqlite3Strlen30(pTrigger->table);
101644  return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
101645}
101646
101647
101648/*
101649** Drop a trigger given a pointer to that trigger.
101650*/
101651SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
101652  Table   *pTable;
101653  Vdbe *v;
101654  sqlite3 *db = pParse->db;
101655  int iDb;
101656
101657  iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
101658  assert( iDb>=0 && iDb<db->nDb );
101659  pTable = tableOfTrigger(pTrigger);
101660  assert( pTable );
101661  assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
101662#ifndef SQLITE_OMIT_AUTHORIZATION
101663  {
101664    int code = SQLITE_DROP_TRIGGER;
101665    const char *zDb = db->aDb[iDb].zName;
101666    const char *zTab = SCHEMA_TABLE(iDb);
101667    if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
101668    if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
101669      sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
101670      return;
101671    }
101672  }
101673#endif
101674
101675  /* Generate code to destroy the database record of the trigger.
101676  */
101677  assert( pTable!=0 );
101678  if( (v = sqlite3GetVdbe(pParse))!=0 ){
101679    int base;
101680    static const VdbeOpList dropTrigger[] = {
101681      { OP_Rewind,     0, ADDR(9),  0},
101682      { OP_String8,    0, 1,        0}, /* 1 */
101683      { OP_Column,     0, 1,        2},
101684      { OP_Ne,         2, ADDR(8),  1},
101685      { OP_String8,    0, 1,        0}, /* 4: "trigger" */
101686      { OP_Column,     0, 0,        2},
101687      { OP_Ne,         2, ADDR(8),  1},
101688      { OP_Delete,     0, 0,        0},
101689      { OP_Next,       0, ADDR(1),  0}, /* 8 */
101690    };
101691
101692    sqlite3BeginWriteOperation(pParse, 0, iDb);
101693    sqlite3OpenMasterTable(pParse, iDb);
101694    base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger);
101695    sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT);
101696    sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
101697    sqlite3ChangeCookie(pParse, iDb);
101698    sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
101699    sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
101700    if( pParse->nMem<3 ){
101701      pParse->nMem = 3;
101702    }
101703  }
101704}
101705
101706/*
101707** Remove a trigger from the hash tables of the sqlite* pointer.
101708*/
101709SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
101710  Trigger *pTrigger;
101711  Hash *pHash;
101712
101713  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
101714  pHash = &(db->aDb[iDb].pSchema->trigHash);
101715  pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
101716  if( ALWAYS(pTrigger) ){
101717    if( pTrigger->pSchema==pTrigger->pTabSchema ){
101718      Table *pTab = tableOfTrigger(pTrigger);
101719      Trigger **pp;
101720      for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
101721      *pp = (*pp)->pNext;
101722    }
101723    sqlite3DeleteTrigger(db, pTrigger);
101724    db->flags |= SQLITE_InternChanges;
101725  }
101726}
101727
101728/*
101729** pEList is the SET clause of an UPDATE statement.  Each entry
101730** in pEList is of the format <id>=<expr>.  If any of the entries
101731** in pEList have an <id> which matches an identifier in pIdList,
101732** then return TRUE.  If pIdList==NULL, then it is considered a
101733** wildcard that matches anything.  Likewise if pEList==NULL then
101734** it matches anything so always return true.  Return false only
101735** if there is no match.
101736*/
101737static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
101738  int e;
101739  if( pIdList==0 || NEVER(pEList==0) ) return 1;
101740  for(e=0; e<pEList->nExpr; e++){
101741    if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
101742  }
101743  return 0;
101744}
101745
101746/*
101747** Return a list of all triggers on table pTab if there exists at least
101748** one trigger that must be fired when an operation of type 'op' is
101749** performed on the table, and, if that operation is an UPDATE, if at
101750** least one of the columns in pChanges is being modified.
101751*/
101752SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
101753  Parse *pParse,          /* Parse context */
101754  Table *pTab,            /* The table the contains the triggers */
101755  int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
101756  ExprList *pChanges,     /* Columns that change in an UPDATE statement */
101757  int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
101758){
101759  int mask = 0;
101760  Trigger *pList = 0;
101761  Trigger *p;
101762
101763  if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
101764    pList = sqlite3TriggerList(pParse, pTab);
101765  }
101766  assert( pList==0 || IsVirtual(pTab)==0 );
101767  for(p=pList; p; p=p->pNext){
101768    if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
101769      mask |= p->tr_tm;
101770    }
101771  }
101772  if( pMask ){
101773    *pMask = mask;
101774  }
101775  return (mask ? pList : 0);
101776}
101777
101778/*
101779** Convert the pStep->target token into a SrcList and return a pointer
101780** to that SrcList.
101781**
101782** This routine adds a specific database name, if needed, to the target when
101783** forming the SrcList.  This prevents a trigger in one database from
101784** referring to a target in another database.  An exception is when the
101785** trigger is in TEMP in which case it can refer to any other database it
101786** wants.
101787*/
101788static SrcList *targetSrcList(
101789  Parse *pParse,       /* The parsing context */
101790  TriggerStep *pStep   /* The trigger containing the target token */
101791){
101792  int iDb;             /* Index of the database to use */
101793  SrcList *pSrc;       /* SrcList to be returned */
101794
101795  pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
101796  if( pSrc ){
101797    assert( pSrc->nSrc>0 );
101798    assert( pSrc->a!=0 );
101799    iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
101800    if( iDb==0 || iDb>=2 ){
101801      sqlite3 *db = pParse->db;
101802      assert( iDb<pParse->db->nDb );
101803      pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
101804    }
101805  }
101806  return pSrc;
101807}
101808
101809/*
101810** Generate VDBE code for the statements inside the body of a single
101811** trigger.
101812*/
101813static int codeTriggerProgram(
101814  Parse *pParse,            /* The parser context */
101815  TriggerStep *pStepList,   /* List of statements inside the trigger body */
101816  int orconf                /* Conflict algorithm. (OE_Abort, etc) */
101817){
101818  TriggerStep *pStep;
101819  Vdbe *v = pParse->pVdbe;
101820  sqlite3 *db = pParse->db;
101821
101822  assert( pParse->pTriggerTab && pParse->pToplevel );
101823  assert( pStepList );
101824  assert( v!=0 );
101825  for(pStep=pStepList; pStep; pStep=pStep->pNext){
101826    /* Figure out the ON CONFLICT policy that will be used for this step
101827    ** of the trigger program. If the statement that caused this trigger
101828    ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
101829    ** the ON CONFLICT policy that was specified as part of the trigger
101830    ** step statement. Example:
101831    **
101832    **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
101833    **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
101834    **   END;
101835    **
101836    **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
101837    **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
101838    */
101839    pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
101840
101841    /* Clear the cookieGoto flag. When coding triggers, the cookieGoto
101842    ** variable is used as a flag to indicate to sqlite3ExprCodeConstants()
101843    ** that it is not safe to refactor constants (this happens after the
101844    ** start of the first loop in the SQL statement is coded - at that
101845    ** point code may be conditionally executed, so it is no longer safe to
101846    ** initialize constant register values).  */
101847    assert( pParse->cookieGoto==0 || pParse->cookieGoto==-1 );
101848    pParse->cookieGoto = 0;
101849
101850    switch( pStep->op ){
101851      case TK_UPDATE: {
101852        sqlite3Update(pParse,
101853          targetSrcList(pParse, pStep),
101854          sqlite3ExprListDup(db, pStep->pExprList, 0),
101855          sqlite3ExprDup(db, pStep->pWhere, 0),
101856          pParse->eOrconf
101857        );
101858        break;
101859      }
101860      case TK_INSERT: {
101861        sqlite3Insert(pParse,
101862          targetSrcList(pParse, pStep),
101863          sqlite3ExprListDup(db, pStep->pExprList, 0),
101864          sqlite3SelectDup(db, pStep->pSelect, 0),
101865          sqlite3IdListDup(db, pStep->pIdList),
101866          pParse->eOrconf
101867        );
101868        break;
101869      }
101870      case TK_DELETE: {
101871        sqlite3DeleteFrom(pParse,
101872          targetSrcList(pParse, pStep),
101873          sqlite3ExprDup(db, pStep->pWhere, 0)
101874        );
101875        break;
101876      }
101877      default: assert( pStep->op==TK_SELECT ); {
101878        SelectDest sDest;
101879        Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
101880        sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
101881        sqlite3Select(pParse, pSelect, &sDest);
101882        sqlite3SelectDelete(db, pSelect);
101883        break;
101884      }
101885    }
101886    if( pStep->op!=TK_SELECT ){
101887      sqlite3VdbeAddOp0(v, OP_ResetCount);
101888    }
101889  }
101890
101891  return 0;
101892}
101893
101894#ifdef SQLITE_DEBUG
101895/*
101896** This function is used to add VdbeComment() annotations to a VDBE
101897** program. It is not used in production code, only for debugging.
101898*/
101899static const char *onErrorText(int onError){
101900  switch( onError ){
101901    case OE_Abort:    return "abort";
101902    case OE_Rollback: return "rollback";
101903    case OE_Fail:     return "fail";
101904    case OE_Replace:  return "replace";
101905    case OE_Ignore:   return "ignore";
101906    case OE_Default:  return "default";
101907  }
101908  return "n/a";
101909}
101910#endif
101911
101912/*
101913** Parse context structure pFrom has just been used to create a sub-vdbe
101914** (trigger program). If an error has occurred, transfer error information
101915** from pFrom to pTo.
101916*/
101917static void transferParseError(Parse *pTo, Parse *pFrom){
101918  assert( pFrom->zErrMsg==0 || pFrom->nErr );
101919  assert( pTo->zErrMsg==0 || pTo->nErr );
101920  if( pTo->nErr==0 ){
101921    pTo->zErrMsg = pFrom->zErrMsg;
101922    pTo->nErr = pFrom->nErr;
101923  }else{
101924    sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
101925  }
101926}
101927
101928/*
101929** Create and populate a new TriggerPrg object with a sub-program
101930** implementing trigger pTrigger with ON CONFLICT policy orconf.
101931*/
101932static TriggerPrg *codeRowTrigger(
101933  Parse *pParse,       /* Current parse context */
101934  Trigger *pTrigger,   /* Trigger to code */
101935  Table *pTab,         /* The table pTrigger is attached to */
101936  int orconf           /* ON CONFLICT policy to code trigger program with */
101937){
101938  Parse *pTop = sqlite3ParseToplevel(pParse);
101939  sqlite3 *db = pParse->db;   /* Database handle */
101940  TriggerPrg *pPrg;           /* Value to return */
101941  Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
101942  Vdbe *v;                    /* Temporary VM */
101943  NameContext sNC;            /* Name context for sub-vdbe */
101944  SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
101945  Parse *pSubParse;           /* Parse context for sub-vdbe */
101946  int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
101947
101948  assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
101949  assert( pTop->pVdbe );
101950
101951  /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
101952  ** are freed if an error occurs, link them into the Parse.pTriggerPrg
101953  ** list of the top-level Parse object sooner rather than later.  */
101954  pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
101955  if( !pPrg ) return 0;
101956  pPrg->pNext = pTop->pTriggerPrg;
101957  pTop->pTriggerPrg = pPrg;
101958  pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
101959  if( !pProgram ) return 0;
101960  sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
101961  pPrg->pTrigger = pTrigger;
101962  pPrg->orconf = orconf;
101963  pPrg->aColmask[0] = 0xffffffff;
101964  pPrg->aColmask[1] = 0xffffffff;
101965
101966  /* Allocate and populate a new Parse context to use for coding the
101967  ** trigger sub-program.  */
101968  pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
101969  if( !pSubParse ) return 0;
101970  memset(&sNC, 0, sizeof(sNC));
101971  sNC.pParse = pSubParse;
101972  pSubParse->db = db;
101973  pSubParse->pTriggerTab = pTab;
101974  pSubParse->pToplevel = pTop;
101975  pSubParse->zAuthContext = pTrigger->zName;
101976  pSubParse->eTriggerOp = pTrigger->op;
101977  pSubParse->nQueryLoop = pParse->nQueryLoop;
101978
101979  v = sqlite3GetVdbe(pSubParse);
101980  if( v ){
101981    VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
101982      pTrigger->zName, onErrorText(orconf),
101983      (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
101984        (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
101985        (pTrigger->op==TK_INSERT ? "INSERT" : ""),
101986        (pTrigger->op==TK_DELETE ? "DELETE" : ""),
101987      pTab->zName
101988    ));
101989#ifndef SQLITE_OMIT_TRACE
101990    sqlite3VdbeChangeP4(v, -1,
101991      sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
101992    );
101993#endif
101994
101995    /* If one was specified, code the WHEN clause. If it evaluates to false
101996    ** (or NULL) the sub-vdbe is immediately halted by jumping to the
101997    ** OP_Halt inserted at the end of the program.  */
101998    if( pTrigger->pWhen ){
101999      pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
102000      if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
102001       && db->mallocFailed==0
102002      ){
102003        iEndTrigger = sqlite3VdbeMakeLabel(v);
102004        sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
102005      }
102006      sqlite3ExprDelete(db, pWhen);
102007    }
102008
102009    /* Code the trigger program into the sub-vdbe. */
102010    codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
102011
102012    /* Insert an OP_Halt at the end of the sub-program. */
102013    if( iEndTrigger ){
102014      sqlite3VdbeResolveLabel(v, iEndTrigger);
102015    }
102016    sqlite3VdbeAddOp0(v, OP_Halt);
102017    VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
102018
102019    transferParseError(pParse, pSubParse);
102020    if( db->mallocFailed==0 ){
102021      pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
102022    }
102023    pProgram->nMem = pSubParse->nMem;
102024    pProgram->nCsr = pSubParse->nTab;
102025    pProgram->nOnce = pSubParse->nOnce;
102026    pProgram->token = (void *)pTrigger;
102027    pPrg->aColmask[0] = pSubParse->oldmask;
102028    pPrg->aColmask[1] = pSubParse->newmask;
102029    sqlite3VdbeDelete(v);
102030  }
102031
102032  assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
102033  assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
102034  sqlite3StackFree(db, pSubParse);
102035
102036  return pPrg;
102037}
102038
102039/*
102040** Return a pointer to a TriggerPrg object containing the sub-program for
102041** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
102042** TriggerPrg object exists, a new object is allocated and populated before
102043** being returned.
102044*/
102045static TriggerPrg *getRowTrigger(
102046  Parse *pParse,       /* Current parse context */
102047  Trigger *pTrigger,   /* Trigger to code */
102048  Table *pTab,         /* The table trigger pTrigger is attached to */
102049  int orconf           /* ON CONFLICT algorithm. */
102050){
102051  Parse *pRoot = sqlite3ParseToplevel(pParse);
102052  TriggerPrg *pPrg;
102053
102054  assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
102055
102056  /* It may be that this trigger has already been coded (or is in the
102057  ** process of being coded). If this is the case, then an entry with
102058  ** a matching TriggerPrg.pTrigger field will be present somewhere
102059  ** in the Parse.pTriggerPrg list. Search for such an entry.  */
102060  for(pPrg=pRoot->pTriggerPrg;
102061      pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
102062      pPrg=pPrg->pNext
102063  );
102064
102065  /* If an existing TriggerPrg could not be located, create a new one. */
102066  if( !pPrg ){
102067    pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
102068  }
102069
102070  return pPrg;
102071}
102072
102073/*
102074** Generate code for the trigger program associated with trigger p on
102075** table pTab. The reg, orconf and ignoreJump parameters passed to this
102076** function are the same as those described in the header function for
102077** sqlite3CodeRowTrigger()
102078*/
102079SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
102080  Parse *pParse,       /* Parse context */
102081  Trigger *p,          /* Trigger to code */
102082  Table *pTab,         /* The table to code triggers from */
102083  int reg,             /* Reg array containing OLD.* and NEW.* values */
102084  int orconf,          /* ON CONFLICT policy */
102085  int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
102086){
102087  Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
102088  TriggerPrg *pPrg;
102089  pPrg = getRowTrigger(pParse, p, pTab, orconf);
102090  assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
102091
102092  /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
102093  ** is a pointer to the sub-vdbe containing the trigger program.  */
102094  if( pPrg ){
102095    int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
102096
102097    sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
102098    sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
102099    VdbeComment(
102100        (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
102101
102102    /* Set the P5 operand of the OP_Program instruction to non-zero if
102103    ** recursive invocation of this trigger program is disallowed. Recursive
102104    ** invocation is disallowed if (a) the sub-program is really a trigger,
102105    ** not a foreign key action, and (b) the flag to enable recursive triggers
102106    ** is clear.  */
102107    sqlite3VdbeChangeP5(v, (u8)bRecursive);
102108  }
102109}
102110
102111/*
102112** This is called to code the required FOR EACH ROW triggers for an operation
102113** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
102114** is given by the op paramater. The tr_tm parameter determines whether the
102115** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
102116** parameter pChanges is passed the list of columns being modified.
102117**
102118** If there are no triggers that fire at the specified time for the specified
102119** operation on pTab, this function is a no-op.
102120**
102121** The reg argument is the address of the first in an array of registers
102122** that contain the values substituted for the new.* and old.* references
102123** in the trigger program. If N is the number of columns in table pTab
102124** (a copy of pTab->nCol), then registers are populated as follows:
102125**
102126**   Register       Contains
102127**   ------------------------------------------------------
102128**   reg+0          OLD.rowid
102129**   reg+1          OLD.* value of left-most column of pTab
102130**   ...            ...
102131**   reg+N          OLD.* value of right-most column of pTab
102132**   reg+N+1        NEW.rowid
102133**   reg+N+2        OLD.* value of left-most column of pTab
102134**   ...            ...
102135**   reg+N+N+1      NEW.* value of right-most column of pTab
102136**
102137** For ON DELETE triggers, the registers containing the NEW.* values will
102138** never be accessed by the trigger program, so they are not allocated or
102139** populated by the caller (there is no data to populate them with anyway).
102140** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
102141** are never accessed, and so are not allocated by the caller. So, for an
102142** ON INSERT trigger, the value passed to this function as parameter reg
102143** is not a readable register, although registers (reg+N) through
102144** (reg+N+N+1) are.
102145**
102146** Parameter orconf is the default conflict resolution algorithm for the
102147** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
102148** is the instruction that control should jump to if a trigger program
102149** raises an IGNORE exception.
102150*/
102151SQLITE_PRIVATE void sqlite3CodeRowTrigger(
102152  Parse *pParse,       /* Parse context */
102153  Trigger *pTrigger,   /* List of triggers on table pTab */
102154  int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
102155  ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
102156  int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
102157  Table *pTab,         /* The table to code triggers from */
102158  int reg,             /* The first in an array of registers (see above) */
102159  int orconf,          /* ON CONFLICT policy */
102160  int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
102161){
102162  Trigger *p;          /* Used to iterate through pTrigger list */
102163
102164  assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
102165  assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
102166  assert( (op==TK_UPDATE)==(pChanges!=0) );
102167
102168  for(p=pTrigger; p; p=p->pNext){
102169
102170    /* Sanity checking:  The schema for the trigger and for the table are
102171    ** always defined.  The trigger must be in the same schema as the table
102172    ** or else it must be a TEMP trigger. */
102173    assert( p->pSchema!=0 );
102174    assert( p->pTabSchema!=0 );
102175    assert( p->pSchema==p->pTabSchema
102176         || p->pSchema==pParse->db->aDb[1].pSchema );
102177
102178    /* Determine whether we should code this trigger */
102179    if( p->op==op
102180     && p->tr_tm==tr_tm
102181     && checkColumnOverlap(p->pColumns, pChanges)
102182    ){
102183      sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
102184    }
102185  }
102186}
102187
102188/*
102189** Triggers may access values stored in the old.* or new.* pseudo-table.
102190** This function returns a 32-bit bitmask indicating which columns of the
102191** old.* or new.* tables actually are used by triggers. This information
102192** may be used by the caller, for example, to avoid having to load the entire
102193** old.* record into memory when executing an UPDATE or DELETE command.
102194**
102195** Bit 0 of the returned mask is set if the left-most column of the
102196** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
102197** the second leftmost column value is required, and so on. If there
102198** are more than 32 columns in the table, and at least one of the columns
102199** with an index greater than 32 may be accessed, 0xffffffff is returned.
102200**
102201** It is not possible to determine if the old.rowid or new.rowid column is
102202** accessed by triggers. The caller must always assume that it is.
102203**
102204** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
102205** applies to the old.* table. If 1, the new.* table.
102206**
102207** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
102208** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
102209** included in the returned mask if the TRIGGER_BEFORE bit is set in the
102210** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
102211** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
102212*/
102213SQLITE_PRIVATE u32 sqlite3TriggerColmask(
102214  Parse *pParse,       /* Parse context */
102215  Trigger *pTrigger,   /* List of triggers on table pTab */
102216  ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
102217  int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */
102218  int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
102219  Table *pTab,         /* The table to code triggers from */
102220  int orconf           /* Default ON CONFLICT policy for trigger steps */
102221){
102222  const int op = pChanges ? TK_UPDATE : TK_DELETE;
102223  u32 mask = 0;
102224  Trigger *p;
102225
102226  assert( isNew==1 || isNew==0 );
102227  for(p=pTrigger; p; p=p->pNext){
102228    if( p->op==op && (tr_tm&p->tr_tm)
102229     && checkColumnOverlap(p->pColumns,pChanges)
102230    ){
102231      TriggerPrg *pPrg;
102232      pPrg = getRowTrigger(pParse, p, pTab, orconf);
102233      if( pPrg ){
102234        mask |= pPrg->aColmask[isNew];
102235      }
102236    }
102237  }
102238
102239  return mask;
102240}
102241
102242#endif /* !defined(SQLITE_OMIT_TRIGGER) */
102243
102244/************** End of trigger.c *********************************************/
102245/************** Begin file update.c ******************************************/
102246/*
102247** 2001 September 15
102248**
102249** The author disclaims copyright to this source code.  In place of
102250** a legal notice, here is a blessing:
102251**
102252**    May you do good and not evil.
102253**    May you find forgiveness for yourself and forgive others.
102254**    May you share freely, never taking more than you give.
102255**
102256*************************************************************************
102257** This file contains C code routines that are called by the parser
102258** to handle UPDATE statements.
102259*/
102260
102261#ifndef SQLITE_OMIT_VIRTUALTABLE
102262/* Forward declaration */
102263static void updateVirtualTable(
102264  Parse *pParse,       /* The parsing context */
102265  SrcList *pSrc,       /* The virtual table to be modified */
102266  Table *pTab,         /* The virtual table */
102267  ExprList *pChanges,  /* The columns to change in the UPDATE statement */
102268  Expr *pRowidExpr,    /* Expression used to recompute the rowid */
102269  int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
102270  Expr *pWhere,        /* WHERE clause of the UPDATE statement */
102271  int onError          /* ON CONFLICT strategy */
102272);
102273#endif /* SQLITE_OMIT_VIRTUALTABLE */
102274
102275/*
102276** The most recently coded instruction was an OP_Column to retrieve the
102277** i-th column of table pTab. This routine sets the P4 parameter of the
102278** OP_Column to the default value, if any.
102279**
102280** The default value of a column is specified by a DEFAULT clause in the
102281** column definition. This was either supplied by the user when the table
102282** was created, or added later to the table definition by an ALTER TABLE
102283** command. If the latter, then the row-records in the table btree on disk
102284** may not contain a value for the column and the default value, taken
102285** from the P4 parameter of the OP_Column instruction, is returned instead.
102286** If the former, then all row-records are guaranteed to include a value
102287** for the column and the P4 value is not required.
102288**
102289** Column definitions created by an ALTER TABLE command may only have
102290** literal default values specified: a number, null or a string. (If a more
102291** complicated default expression value was provided, it is evaluated
102292** when the ALTER TABLE is executed and one of the literal values written
102293** into the sqlite_master table.)
102294**
102295** Therefore, the P4 parameter is only required if the default value for
102296** the column is a literal number, string or null. The sqlite3ValueFromExpr()
102297** function is capable of transforming these types of expressions into
102298** sqlite3_value objects.
102299**
102300** If parameter iReg is not negative, code an OP_RealAffinity instruction
102301** on register iReg. This is used when an equivalent integer value is
102302** stored in place of an 8-byte floating point value in order to save
102303** space.
102304*/
102305SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
102306  assert( pTab!=0 );
102307  if( !pTab->pSelect ){
102308    sqlite3_value *pValue;
102309    u8 enc = ENC(sqlite3VdbeDb(v));
102310    Column *pCol = &pTab->aCol[i];
102311    VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
102312    assert( i<pTab->nCol );
102313    sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
102314                         pCol->affinity, &pValue);
102315    if( pValue ){
102316      sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
102317    }
102318#ifndef SQLITE_OMIT_FLOATING_POINT
102319    if( iReg>=0 && pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
102320      sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
102321    }
102322#endif
102323  }
102324}
102325
102326/*
102327** Process an UPDATE statement.
102328**
102329**   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
102330**          \_______/ \________/     \______/       \________________/
102331*            onError   pTabList      pChanges             pWhere
102332*/
102333SQLITE_PRIVATE void sqlite3Update(
102334  Parse *pParse,         /* The parser context */
102335  SrcList *pTabList,     /* The table in which we should change things */
102336  ExprList *pChanges,    /* Things to be changed */
102337  Expr *pWhere,          /* The WHERE clause.  May be null */
102338  int onError            /* How to handle constraint errors */
102339){
102340  int i, j;              /* Loop counters */
102341  Table *pTab;           /* The table to be updated */
102342  int addr = 0;          /* VDBE instruction address of the start of the loop */
102343  WhereInfo *pWInfo;     /* Information about the WHERE clause */
102344  Vdbe *v;               /* The virtual database engine */
102345  Index *pIdx;           /* For looping over indices */
102346  int nIdx;              /* Number of indices that need updating */
102347  int iCur;              /* VDBE Cursor number of pTab */
102348  sqlite3 *db;           /* The database structure */
102349  int *aRegIdx = 0;      /* One register assigned to each index to be updated */
102350  int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
102351                         ** an expression for the i-th column of the table.
102352                         ** aXRef[i]==-1 if the i-th column is not changed. */
102353  int chngRowid;         /* True if the record number is being changed */
102354  Expr *pRowidExpr = 0;  /* Expression defining the new record number */
102355  int openAll = 0;       /* True if all indices need to be opened */
102356  AuthContext sContext;  /* The authorization context */
102357  NameContext sNC;       /* The name-context to resolve expressions in */
102358  int iDb;               /* Database containing the table being updated */
102359  int okOnePass;         /* True for one-pass algorithm without the FIFO */
102360  int hasFK;             /* True if foreign key processing is required */
102361
102362#ifndef SQLITE_OMIT_TRIGGER
102363  int isView;            /* True when updating a view (INSTEAD OF trigger) */
102364  Trigger *pTrigger;     /* List of triggers on pTab, if required */
102365  int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
102366#endif
102367  int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
102368
102369  /* Register Allocations */
102370  int regRowCount = 0;   /* A count of rows changed */
102371  int regOldRowid;       /* The old rowid */
102372  int regNewRowid;       /* The new rowid */
102373  int regNew;            /* Content of the NEW.* table in triggers */
102374  int regOld = 0;        /* Content of OLD.* table in triggers */
102375  int regRowSet = 0;     /* Rowset of rows to be updated */
102376
102377  memset(&sContext, 0, sizeof(sContext));
102378  db = pParse->db;
102379  if( pParse->nErr || db->mallocFailed ){
102380    goto update_cleanup;
102381  }
102382  assert( pTabList->nSrc==1 );
102383
102384  /* Locate the table which we want to update.
102385  */
102386  pTab = sqlite3SrcListLookup(pParse, pTabList);
102387  if( pTab==0 ) goto update_cleanup;
102388  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
102389
102390  /* Figure out if we have any triggers and if the table being
102391  ** updated is a view.
102392  */
102393#ifndef SQLITE_OMIT_TRIGGER
102394  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
102395  isView = pTab->pSelect!=0;
102396  assert( pTrigger || tmask==0 );
102397#else
102398# define pTrigger 0
102399# define isView 0
102400# define tmask 0
102401#endif
102402#ifdef SQLITE_OMIT_VIEW
102403# undef isView
102404# define isView 0
102405#endif
102406
102407  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
102408    goto update_cleanup;
102409  }
102410  if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
102411    goto update_cleanup;
102412  }
102413  aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
102414  if( aXRef==0 ) goto update_cleanup;
102415  for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
102416
102417  /* Allocate a cursors for the main database table and for all indices.
102418  ** The index cursors might not be used, but if they are used they
102419  ** need to occur right after the database cursor.  So go ahead and
102420  ** allocate enough space, just in case.
102421  */
102422  pTabList->a[0].iCursor = iCur = pParse->nTab++;
102423  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
102424    pParse->nTab++;
102425  }
102426
102427  /* Initialize the name-context */
102428  memset(&sNC, 0, sizeof(sNC));
102429  sNC.pParse = pParse;
102430  sNC.pSrcList = pTabList;
102431
102432  /* Resolve the column names in all the expressions of the
102433  ** of the UPDATE statement.  Also find the column index
102434  ** for each column to be updated in the pChanges array.  For each
102435  ** column to be updated, make sure we have authorization to change
102436  ** that column.
102437  */
102438  chngRowid = 0;
102439  for(i=0; i<pChanges->nExpr; i++){
102440    if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
102441      goto update_cleanup;
102442    }
102443    for(j=0; j<pTab->nCol; j++){
102444      if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
102445        if( j==pTab->iPKey ){
102446          chngRowid = 1;
102447          pRowidExpr = pChanges->a[i].pExpr;
102448        }
102449        aXRef[j] = i;
102450        break;
102451      }
102452    }
102453    if( j>=pTab->nCol ){
102454      if( sqlite3IsRowid(pChanges->a[i].zName) ){
102455        j = -1;
102456        chngRowid = 1;
102457        pRowidExpr = pChanges->a[i].pExpr;
102458      }else{
102459        sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
102460        pParse->checkSchema = 1;
102461        goto update_cleanup;
102462      }
102463    }
102464#ifndef SQLITE_OMIT_AUTHORIZATION
102465    {
102466      int rc;
102467      rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
102468                            j<0 ? "ROWID" : pTab->aCol[j].zName,
102469                            db->aDb[iDb].zName);
102470      if( rc==SQLITE_DENY ){
102471        goto update_cleanup;
102472      }else if( rc==SQLITE_IGNORE ){
102473        aXRef[j] = -1;
102474      }
102475    }
102476#endif
102477  }
102478
102479  hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid);
102480
102481  /* Allocate memory for the array aRegIdx[].  There is one entry in the
102482  ** array for each index associated with table being updated.  Fill in
102483  ** the value with a register number for indices that are to be used
102484  ** and with zero for unused indices.
102485  */
102486  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
102487  if( nIdx>0 ){
102488    aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
102489    if( aRegIdx==0 ) goto update_cleanup;
102490  }
102491  for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
102492    int reg;
102493    if( hasFK || chngRowid ){
102494      reg = ++pParse->nMem;
102495    }else{
102496      reg = 0;
102497      for(i=0; i<pIdx->nColumn; i++){
102498        if( aXRef[pIdx->aiColumn[i]]>=0 ){
102499          reg = ++pParse->nMem;
102500          break;
102501        }
102502      }
102503    }
102504    aRegIdx[j] = reg;
102505  }
102506
102507  /* Begin generating code. */
102508  v = sqlite3GetVdbe(pParse);
102509  if( v==0 ) goto update_cleanup;
102510  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
102511  sqlite3BeginWriteOperation(pParse, 1, iDb);
102512
102513#ifndef SQLITE_OMIT_VIRTUALTABLE
102514  /* Virtual tables must be handled separately */
102515  if( IsVirtual(pTab) ){
102516    updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
102517                       pWhere, onError);
102518    pWhere = 0;
102519    pTabList = 0;
102520    goto update_cleanup;
102521  }
102522#endif
102523
102524  /* Allocate required registers. */
102525  regRowSet = ++pParse->nMem;
102526  regOldRowid = regNewRowid = ++pParse->nMem;
102527  if( pTrigger || hasFK ){
102528    regOld = pParse->nMem + 1;
102529    pParse->nMem += pTab->nCol;
102530  }
102531  if( chngRowid || pTrigger || hasFK ){
102532    regNewRowid = ++pParse->nMem;
102533  }
102534  regNew = pParse->nMem + 1;
102535  pParse->nMem += pTab->nCol;
102536
102537  /* Start the view context. */
102538  if( isView ){
102539    sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
102540  }
102541
102542  /* If we are trying to update a view, realize that view into
102543  ** a ephemeral table.
102544  */
102545#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
102546  if( isView ){
102547    sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
102548  }
102549#endif
102550
102551  /* Resolve the column names in all the expressions in the
102552  ** WHERE clause.
102553  */
102554  if( sqlite3ResolveExprNames(&sNC, pWhere) ){
102555    goto update_cleanup;
102556  }
102557
102558  /* Begin the database scan
102559  */
102560  sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
102561  pWInfo = sqlite3WhereBegin(
102562      pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED, 0
102563  );
102564  if( pWInfo==0 ) goto update_cleanup;
102565  okOnePass = pWInfo->okOnePass;
102566
102567  /* Remember the rowid of every item to be updated.
102568  */
102569  sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
102570  if( !okOnePass ){
102571    sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
102572  }
102573
102574  /* End the database scan loop.
102575  */
102576  sqlite3WhereEnd(pWInfo);
102577
102578  /* Initialize the count of updated rows
102579  */
102580  if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
102581    regRowCount = ++pParse->nMem;
102582    sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
102583  }
102584
102585  if( !isView ){
102586    /*
102587    ** Open every index that needs updating.  Note that if any
102588    ** index could potentially invoke a REPLACE conflict resolution
102589    ** action, then we need to open all indices because we might need
102590    ** to be deleting some records.
102591    */
102592    if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
102593    if( onError==OE_Replace ){
102594      openAll = 1;
102595    }else{
102596      openAll = 0;
102597      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
102598        if( pIdx->onError==OE_Replace ){
102599          openAll = 1;
102600          break;
102601        }
102602      }
102603    }
102604    for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
102605      assert( aRegIdx );
102606      if( openAll || aRegIdx[i]>0 ){
102607        KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
102608        sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
102609                       (char*)pKey, P4_KEYINFO_HANDOFF);
102610        assert( pParse->nTab>iCur+i+1 );
102611      }
102612    }
102613  }
102614
102615  /* Top of the update loop */
102616  if( okOnePass ){
102617    int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
102618    addr = sqlite3VdbeAddOp0(v, OP_Goto);
102619    sqlite3VdbeJumpHere(v, a1);
102620  }else{
102621    addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
102622  }
102623
102624  /* Make cursor iCur point to the record that is being updated. If
102625  ** this record does not exist for some reason (deleted by a trigger,
102626  ** for example, then jump to the next iteration of the RowSet loop.  */
102627  sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
102628
102629  /* If the record number will change, set register regNewRowid to
102630  ** contain the new value. If the record number is not being modified,
102631  ** then regNewRowid is the same register as regOldRowid, which is
102632  ** already populated.  */
102633  assert( chngRowid || pTrigger || hasFK || regOldRowid==regNewRowid );
102634  if( chngRowid ){
102635    sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
102636    sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
102637  }
102638
102639  /* If there are triggers on this table, populate an array of registers
102640  ** with the required old.* column data.  */
102641  if( hasFK || pTrigger ){
102642    u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
102643    oldmask |= sqlite3TriggerColmask(pParse,
102644        pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
102645    );
102646    for(i=0; i<pTab->nCol; i++){
102647      if( aXRef[i]<0 || oldmask==0xffffffff || (i<32 && (oldmask & (1<<i))) ){
102648        sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOld+i);
102649      }else{
102650        sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
102651      }
102652    }
102653    if( chngRowid==0 ){
102654      sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
102655    }
102656  }
102657
102658  /* Populate the array of registers beginning at regNew with the new
102659  ** row data. This array is used to check constaints, create the new
102660  ** table and index records, and as the values for any new.* references
102661  ** made by triggers.
102662  **
102663  ** If there are one or more BEFORE triggers, then do not populate the
102664  ** registers associated with columns that are (a) not modified by
102665  ** this UPDATE statement and (b) not accessed by new.* references. The
102666  ** values for registers not modified by the UPDATE must be reloaded from
102667  ** the database after the BEFORE triggers are fired anyway (as the trigger
102668  ** may have modified them). So not loading those that are not going to
102669  ** be used eliminates some redundant opcodes.
102670  */
102671  newmask = sqlite3TriggerColmask(
102672      pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
102673  );
102674  sqlite3VdbeAddOp3(v, OP_Null, 0, regNew, regNew+pTab->nCol-1);
102675  for(i=0; i<pTab->nCol; i++){
102676    if( i==pTab->iPKey ){
102677      /*sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);*/
102678    }else{
102679      j = aXRef[i];
102680      if( j>=0 ){
102681        sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
102682      }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask&(1<<i)) ){
102683        /* This branch loads the value of a column that will not be changed
102684        ** into a register. This is done if there are no BEFORE triggers, or
102685        ** if there are one or more BEFORE triggers that use this value via
102686        ** a new.* reference in a trigger program.
102687        */
102688        testcase( i==31 );
102689        testcase( i==32 );
102690        sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
102691        sqlite3ColumnDefault(v, pTab, i, regNew+i);
102692      }
102693    }
102694  }
102695
102696  /* Fire any BEFORE UPDATE triggers. This happens before constraints are
102697  ** verified. One could argue that this is wrong.
102698  */
102699  if( tmask&TRIGGER_BEFORE ){
102700    sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab->nCol);
102701    sqlite3TableAffinityStr(v, pTab);
102702    sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
102703        TRIGGER_BEFORE, pTab, regOldRowid, onError, addr);
102704
102705    /* The row-trigger may have deleted the row being updated. In this
102706    ** case, jump to the next row. No updates or AFTER triggers are
102707    ** required. This behavior - what happens when the row being updated
102708    ** is deleted or renamed by a BEFORE trigger - is left undefined in the
102709    ** documentation.
102710    */
102711    sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
102712
102713    /* If it did not delete it, the row-trigger may still have modified
102714    ** some of the columns of the row being updated. Load the values for
102715    ** all columns not modified by the update statement into their
102716    ** registers in case this has happened.
102717    */
102718    for(i=0; i<pTab->nCol; i++){
102719      if( aXRef[i]<0 && i!=pTab->iPKey ){
102720        sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
102721        sqlite3ColumnDefault(v, pTab, i, regNew+i);
102722      }
102723    }
102724  }
102725
102726  if( !isView ){
102727    int j1;                       /* Address of jump instruction */
102728
102729    /* Do constraint checks. */
102730    sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
102731        aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0);
102732
102733    /* Do FK constraint checks. */
102734    if( hasFK ){
102735      sqlite3FkCheck(pParse, pTab, regOldRowid, 0);
102736    }
102737
102738    /* Delete the index entries associated with the current record.  */
102739    j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
102740    sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
102741
102742    /* If changing the record number, delete the old record.  */
102743    if( hasFK || chngRowid ){
102744      sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
102745    }
102746    sqlite3VdbeJumpHere(v, j1);
102747
102748    if( hasFK ){
102749      sqlite3FkCheck(pParse, pTab, 0, regNewRowid);
102750    }
102751
102752    /* Insert the new index entries and the new record. */
102753    sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, 1, 0, 0);
102754
102755    /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
102756    ** handle rows (possibly in other tables) that refer via a foreign key
102757    ** to the row just updated. */
102758    if( hasFK ){
102759      sqlite3FkActions(pParse, pTab, pChanges, regOldRowid);
102760    }
102761  }
102762
102763  /* Increment the row counter
102764  */
102765  if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
102766    sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
102767  }
102768
102769  sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
102770      TRIGGER_AFTER, pTab, regOldRowid, onError, addr);
102771
102772  /* Repeat the above with the next record to be updated, until
102773  ** all record selected by the WHERE clause have been updated.
102774  */
102775  sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
102776  sqlite3VdbeJumpHere(v, addr);
102777
102778  /* Close all tables */
102779  for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
102780    assert( aRegIdx );
102781    if( openAll || aRegIdx[i]>0 ){
102782      sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
102783    }
102784  }
102785  sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
102786
102787  /* Update the sqlite_sequence table by storing the content of the
102788  ** maximum rowid counter values recorded while inserting into
102789  ** autoincrement tables.
102790  */
102791  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
102792    sqlite3AutoincrementEnd(pParse);
102793  }
102794
102795  /*
102796  ** Return the number of rows that were changed. If this routine is
102797  ** generating code because of a call to sqlite3NestedParse(), do not
102798  ** invoke the callback function.
102799  */
102800  if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
102801    sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
102802    sqlite3VdbeSetNumCols(v, 1);
102803    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
102804  }
102805
102806update_cleanup:
102807  sqlite3AuthContextPop(&sContext);
102808  sqlite3DbFree(db, aRegIdx);
102809  sqlite3DbFree(db, aXRef);
102810  sqlite3SrcListDelete(db, pTabList);
102811  sqlite3ExprListDelete(db, pChanges);
102812  sqlite3ExprDelete(db, pWhere);
102813  return;
102814}
102815/* Make sure "isView" and other macros defined above are undefined. Otherwise
102816** thely may interfere with compilation of other functions in this file
102817** (or in another file, if this file becomes part of the amalgamation).  */
102818#ifdef isView
102819 #undef isView
102820#endif
102821#ifdef pTrigger
102822 #undef pTrigger
102823#endif
102824
102825#ifndef SQLITE_OMIT_VIRTUALTABLE
102826/*
102827** Generate code for an UPDATE of a virtual table.
102828**
102829** The strategy is that we create an ephemerial table that contains
102830** for each row to be changed:
102831**
102832**   (A)  The original rowid of that row.
102833**   (B)  The revised rowid for the row. (note1)
102834**   (C)  The content of every column in the row.
102835**
102836** Then we loop over this ephemeral table and for each row in
102837** the ephermeral table call VUpdate.
102838**
102839** When finished, drop the ephemeral table.
102840**
102841** (note1) Actually, if we know in advance that (A) is always the same
102842** as (B) we only store (A), then duplicate (A) when pulling
102843** it out of the ephemeral table before calling VUpdate.
102844*/
102845static void updateVirtualTable(
102846  Parse *pParse,       /* The parsing context */
102847  SrcList *pSrc,       /* The virtual table to be modified */
102848  Table *pTab,         /* The virtual table */
102849  ExprList *pChanges,  /* The columns to change in the UPDATE statement */
102850  Expr *pRowid,        /* Expression used to recompute the rowid */
102851  int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
102852  Expr *pWhere,        /* WHERE clause of the UPDATE statement */
102853  int onError          /* ON CONFLICT strategy */
102854){
102855  Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
102856  ExprList *pEList = 0;     /* The result set of the SELECT statement */
102857  Select *pSelect = 0;      /* The SELECT statement */
102858  Expr *pExpr;              /* Temporary expression */
102859  int ephemTab;             /* Table holding the result of the SELECT */
102860  int i;                    /* Loop counter */
102861  int addr;                 /* Address of top of loop */
102862  int iReg;                 /* First register in set passed to OP_VUpdate */
102863  sqlite3 *db = pParse->db; /* Database connection */
102864  const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
102865  SelectDest dest;
102866
102867  /* Construct the SELECT statement that will find the new values for
102868  ** all updated rows.
102869  */
102870  pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
102871  if( pRowid ){
102872    pEList = sqlite3ExprListAppend(pParse, pEList,
102873                                   sqlite3ExprDup(db, pRowid, 0));
102874  }
102875  assert( pTab->iPKey<0 );
102876  for(i=0; i<pTab->nCol; i++){
102877    if( aXRef[i]>=0 ){
102878      pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
102879    }else{
102880      pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
102881    }
102882    pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
102883  }
102884  pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
102885
102886  /* Create the ephemeral table into which the update results will
102887  ** be stored.
102888  */
102889  assert( v );
102890  ephemTab = pParse->nTab++;
102891  sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
102892  sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
102893
102894  /* fill the ephemeral table
102895  */
102896  sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
102897  sqlite3Select(pParse, pSelect, &dest);
102898
102899  /* Generate code to scan the ephemeral table and call VUpdate. */
102900  iReg = ++pParse->nMem;
102901  pParse->nMem += pTab->nCol+1;
102902  addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
102903  sqlite3VdbeAddOp3(v, OP_Column,  ephemTab, 0, iReg);
102904  sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
102905  for(i=0; i<pTab->nCol; i++){
102906    sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
102907  }
102908  sqlite3VtabMakeWritable(pParse, pTab);
102909  sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
102910  sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
102911  sqlite3MayAbort(pParse);
102912  sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1);
102913  sqlite3VdbeJumpHere(v, addr);
102914  sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
102915
102916  /* Cleanup */
102917  sqlite3SelectDelete(db, pSelect);
102918}
102919#endif /* SQLITE_OMIT_VIRTUALTABLE */
102920
102921/************** End of update.c **********************************************/
102922/************** Begin file vacuum.c ******************************************/
102923/*
102924** 2003 April 6
102925**
102926** The author disclaims copyright to this source code.  In place of
102927** a legal notice, here is a blessing:
102928**
102929**    May you do good and not evil.
102930**    May you find forgiveness for yourself and forgive others.
102931**    May you share freely, never taking more than you give.
102932**
102933*************************************************************************
102934** This file contains code used to implement the VACUUM command.
102935**
102936** Most of the code in this file may be omitted by defining the
102937** SQLITE_OMIT_VACUUM macro.
102938*/
102939
102940#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
102941/*
102942** Finalize a prepared statement.  If there was an error, store the
102943** text of the error message in *pzErrMsg.  Return the result code.
102944*/
102945static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
102946  int rc;
102947  rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
102948  if( rc ){
102949    sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
102950  }
102951  return rc;
102952}
102953
102954/*
102955** Execute zSql on database db. Return an error code.
102956*/
102957static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
102958  sqlite3_stmt *pStmt;
102959  VVA_ONLY( int rc; )
102960  if( !zSql ){
102961    return SQLITE_NOMEM;
102962  }
102963  if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
102964    sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
102965    return sqlite3_errcode(db);
102966  }
102967  VVA_ONLY( rc = ) sqlite3_step(pStmt);
102968  assert( rc!=SQLITE_ROW || (db->flags&SQLITE_CountRows) );
102969  return vacuumFinalize(db, pStmt, pzErrMsg);
102970}
102971
102972/*
102973** Execute zSql on database db. The statement returns exactly
102974** one column. Execute this as SQL on the same database.
102975*/
102976static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
102977  sqlite3_stmt *pStmt;
102978  int rc;
102979
102980  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
102981  if( rc!=SQLITE_OK ) return rc;
102982
102983  while( SQLITE_ROW==sqlite3_step(pStmt) ){
102984    rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
102985    if( rc!=SQLITE_OK ){
102986      vacuumFinalize(db, pStmt, pzErrMsg);
102987      return rc;
102988    }
102989  }
102990
102991  return vacuumFinalize(db, pStmt, pzErrMsg);
102992}
102993
102994/*
102995** The non-standard VACUUM command is used to clean up the database,
102996** collapse free space, etc.  It is modelled after the VACUUM command
102997** in PostgreSQL.
102998**
102999** In version 1.0.x of SQLite, the VACUUM command would call
103000** gdbm_reorganize() on all the database tables.  But beginning
103001** with 2.0.0, SQLite no longer uses GDBM so this command has
103002** become a no-op.
103003*/
103004SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
103005  Vdbe *v = sqlite3GetVdbe(pParse);
103006  if( v ){
103007    sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
103008    sqlite3VdbeUsesBtree(v, 0);
103009  }
103010  return;
103011}
103012
103013/*
103014** This routine implements the OP_Vacuum opcode of the VDBE.
103015*/
103016SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
103017  int rc = SQLITE_OK;     /* Return code from service routines */
103018  Btree *pMain;           /* The database being vacuumed */
103019  Btree *pTemp;           /* The temporary database we vacuum into */
103020  char *zSql = 0;         /* SQL statements */
103021  int saved_flags;        /* Saved value of the db->flags */
103022  int saved_nChange;      /* Saved value of db->nChange */
103023  int saved_nTotalChange; /* Saved value of db->nTotalChange */
103024  void (*saved_xTrace)(void*,const char*);  /* Saved db->xTrace */
103025  Db *pDb = 0;            /* Database to detach at end of vacuum */
103026  int isMemDb;            /* True if vacuuming a :memory: database */
103027  int nRes;               /* Bytes of reserved space at the end of each page */
103028  int nDb;                /* Number of attached databases */
103029
103030  if( !db->autoCommit ){
103031    sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
103032    return SQLITE_ERROR;
103033  }
103034  if( db->activeVdbeCnt>1 ){
103035    sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
103036    return SQLITE_ERROR;
103037  }
103038
103039  /* Save the current value of the database flags so that it can be
103040  ** restored before returning. Then set the writable-schema flag, and
103041  ** disable CHECK and foreign key constraints.  */
103042  saved_flags = db->flags;
103043  saved_nChange = db->nChange;
103044  saved_nTotalChange = db->nTotalChange;
103045  saved_xTrace = db->xTrace;
103046  db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
103047  db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
103048  db->xTrace = 0;
103049
103050  pMain = db->aDb[0].pBt;
103051  isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
103052
103053  /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
103054  ** can be set to 'off' for this file, as it is not recovered if a crash
103055  ** occurs anyway. The integrity of the database is maintained by a
103056  ** (possibly synchronous) transaction opened on the main database before
103057  ** sqlite3BtreeCopyFile() is called.
103058  **
103059  ** An optimisation would be to use a non-journaled pager.
103060  ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
103061  ** that actually made the VACUUM run slower.  Very little journalling
103062  ** actually occurs when doing a vacuum since the vacuum_db is initially
103063  ** empty.  Only the journal header is written.  Apparently it takes more
103064  ** time to parse and run the PRAGMA to turn journalling off than it does
103065  ** to write the journal header file.
103066  */
103067  nDb = db->nDb;
103068  if( sqlite3TempInMemory(db) ){
103069    zSql = "ATTACH ':memory:' AS vacuum_db;";
103070  }else{
103071    zSql = "ATTACH '' AS vacuum_db;";
103072  }
103073  rc = execSql(db, pzErrMsg, zSql);
103074  if( db->nDb>nDb ){
103075    pDb = &db->aDb[db->nDb-1];
103076    assert( strcmp(pDb->zName,"vacuum_db")==0 );
103077  }
103078  if( rc!=SQLITE_OK ) goto end_of_vacuum;
103079  pTemp = db->aDb[db->nDb-1].pBt;
103080
103081  /* The call to execSql() to attach the temp database has left the file
103082  ** locked (as there was more than one active statement when the transaction
103083  ** to read the schema was concluded. Unlock it here so that this doesn't
103084  ** cause problems for the call to BtreeSetPageSize() below.  */
103085  sqlite3BtreeCommit(pTemp);
103086
103087  nRes = sqlite3BtreeGetReserve(pMain);
103088
103089  /* A VACUUM cannot change the pagesize of an encrypted database. */
103090#ifdef SQLITE_HAS_CODEC
103091  if( db->nextPagesize ){
103092    extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
103093    int nKey;
103094    char *zKey;
103095    sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
103096    if( nKey ) db->nextPagesize = 0;
103097  }
103098#endif
103099
103100  rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
103101  if( rc!=SQLITE_OK ) goto end_of_vacuum;
103102
103103  /* Begin a transaction and take an exclusive lock on the main database
103104  ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
103105  ** to ensure that we do not try to change the page-size on a WAL database.
103106  */
103107  rc = execSql(db, pzErrMsg, "BEGIN;");
103108  if( rc!=SQLITE_OK ) goto end_of_vacuum;
103109  rc = sqlite3BtreeBeginTrans(pMain, 2);
103110  if( rc!=SQLITE_OK ) goto end_of_vacuum;
103111
103112  /* Do not attempt to change the page size for a WAL database */
103113  if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
103114                                               ==PAGER_JOURNALMODE_WAL ){
103115    db->nextPagesize = 0;
103116  }
103117
103118  if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
103119   || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
103120   || NEVER(db->mallocFailed)
103121  ){
103122    rc = SQLITE_NOMEM;
103123    goto end_of_vacuum;
103124  }
103125
103126#ifndef SQLITE_OMIT_AUTOVACUUM
103127  sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
103128                                           sqlite3BtreeGetAutoVacuum(pMain));
103129#endif
103130
103131  /* Query the schema of the main database. Create a mirror schema
103132  ** in the temporary database.
103133  */
103134  rc = execExecSql(db, pzErrMsg,
103135      "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
103136      "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
103137      "   AND rootpage>0"
103138  );
103139  if( rc!=SQLITE_OK ) goto end_of_vacuum;
103140  rc = execExecSql(db, pzErrMsg,
103141      "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
103142      "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
103143  if( rc!=SQLITE_OK ) goto end_of_vacuum;
103144  rc = execExecSql(db, pzErrMsg,
103145      "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
103146      "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
103147  if( rc!=SQLITE_OK ) goto end_of_vacuum;
103148
103149  /* Loop through the tables in the main database. For each, do
103150  ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
103151  ** the contents to the temporary database.
103152  */
103153  rc = execExecSql(db, pzErrMsg,
103154      "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
103155      "|| ' SELECT * FROM main.' || quote(name) || ';'"
103156      "FROM main.sqlite_master "
103157      "WHERE type = 'table' AND name!='sqlite_sequence' "
103158      "  AND rootpage>0"
103159  );
103160  if( rc!=SQLITE_OK ) goto end_of_vacuum;
103161
103162  /* Copy over the sequence table
103163  */
103164  rc = execExecSql(db, pzErrMsg,
103165      "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
103166      "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
103167  );
103168  if( rc!=SQLITE_OK ) goto end_of_vacuum;
103169  rc = execExecSql(db, pzErrMsg,
103170      "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
103171      "|| ' SELECT * FROM main.' || quote(name) || ';' "
103172      "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
103173  );
103174  if( rc!=SQLITE_OK ) goto end_of_vacuum;
103175
103176
103177  /* Copy the triggers, views, and virtual tables from the main database
103178  ** over to the temporary database.  None of these objects has any
103179  ** associated storage, so all we have to do is copy their entries
103180  ** from the SQLITE_MASTER table.
103181  */
103182  rc = execSql(db, pzErrMsg,
103183      "INSERT INTO vacuum_db.sqlite_master "
103184      "  SELECT type, name, tbl_name, rootpage, sql"
103185      "    FROM main.sqlite_master"
103186      "   WHERE type='view' OR type='trigger'"
103187      "      OR (type='table' AND rootpage=0)"
103188  );
103189  if( rc ) goto end_of_vacuum;
103190
103191  /* At this point, there is a write transaction open on both the
103192  ** vacuum database and the main database. Assuming no error occurs,
103193  ** both transactions are closed by this block - the main database
103194  ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
103195  ** call to sqlite3BtreeCommit().
103196  */
103197  {
103198    u32 meta;
103199    int i;
103200
103201    /* This array determines which meta meta values are preserved in the
103202    ** vacuum.  Even entries are the meta value number and odd entries
103203    ** are an increment to apply to the meta value after the vacuum.
103204    ** The increment is used to increase the schema cookie so that other
103205    ** connections to the same database will know to reread the schema.
103206    */
103207    static const unsigned char aCopy[] = {
103208       BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
103209       BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
103210       BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
103211       BTREE_USER_VERSION,       0,  /* Preserve the user version */
103212       BTREE_APPLICATION_ID,     0,  /* Preserve the application id */
103213    };
103214
103215    assert( 1==sqlite3BtreeIsInTrans(pTemp) );
103216    assert( 1==sqlite3BtreeIsInTrans(pMain) );
103217
103218    /* Copy Btree meta values */
103219    for(i=0; i<ArraySize(aCopy); i+=2){
103220      /* GetMeta() and UpdateMeta() cannot fail in this context because
103221      ** we already have page 1 loaded into cache and marked dirty. */
103222      sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
103223      rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
103224      if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
103225    }
103226
103227    rc = sqlite3BtreeCopyFile(pMain, pTemp);
103228    if( rc!=SQLITE_OK ) goto end_of_vacuum;
103229    rc = sqlite3BtreeCommit(pTemp);
103230    if( rc!=SQLITE_OK ) goto end_of_vacuum;
103231#ifndef SQLITE_OMIT_AUTOVACUUM
103232    sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
103233#endif
103234  }
103235
103236  assert( rc==SQLITE_OK );
103237  rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
103238
103239end_of_vacuum:
103240  /* Restore the original value of db->flags */
103241  db->flags = saved_flags;
103242  db->nChange = saved_nChange;
103243  db->nTotalChange = saved_nTotalChange;
103244  db->xTrace = saved_xTrace;
103245  sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
103246
103247  /* Currently there is an SQL level transaction open on the vacuum
103248  ** database. No locks are held on any other files (since the main file
103249  ** was committed at the btree level). So it safe to end the transaction
103250  ** by manually setting the autoCommit flag to true and detaching the
103251  ** vacuum database. The vacuum_db journal file is deleted when the pager
103252  ** is closed by the DETACH.
103253  */
103254  db->autoCommit = 1;
103255
103256  if( pDb ){
103257    sqlite3BtreeClose(pDb->pBt);
103258    pDb->pBt = 0;
103259    pDb->pSchema = 0;
103260  }
103261
103262  /* This both clears the schemas and reduces the size of the db->aDb[]
103263  ** array. */
103264  sqlite3ResetAllSchemasOfConnection(db);
103265
103266  return rc;
103267}
103268
103269#endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
103270
103271/************** End of vacuum.c **********************************************/
103272/************** Begin file vtab.c ********************************************/
103273/*
103274** 2006 June 10
103275**
103276** The author disclaims copyright to this source code.  In place of
103277** a legal notice, here is a blessing:
103278**
103279**    May you do good and not evil.
103280**    May you find forgiveness for yourself and forgive others.
103281**    May you share freely, never taking more than you give.
103282**
103283*************************************************************************
103284** This file contains code used to help implement virtual tables.
103285*/
103286#ifndef SQLITE_OMIT_VIRTUALTABLE
103287
103288/*
103289** Before a virtual table xCreate() or xConnect() method is invoked, the
103290** sqlite3.pVtabCtx member variable is set to point to an instance of
103291** this struct allocated on the stack. It is used by the implementation of
103292** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
103293** are invoked only from within xCreate and xConnect methods.
103294*/
103295struct VtabCtx {
103296  VTable *pVTable;    /* The virtual table being constructed */
103297  Table *pTab;        /* The Table object to which the virtual table belongs */
103298};
103299
103300/*
103301** The actual function that does the work of creating a new module.
103302** This function implements the sqlite3_create_module() and
103303** sqlite3_create_module_v2() interfaces.
103304*/
103305static int createModule(
103306  sqlite3 *db,                    /* Database in which module is registered */
103307  const char *zName,              /* Name assigned to this module */
103308  const sqlite3_module *pModule,  /* The definition of the module */
103309  void *pAux,                     /* Context pointer for xCreate/xConnect */
103310  void (*xDestroy)(void *)        /* Module destructor function */
103311){
103312  int rc = SQLITE_OK;
103313  int nName;
103314
103315  sqlite3_mutex_enter(db->mutex);
103316  nName = sqlite3Strlen30(zName);
103317  if( sqlite3HashFind(&db->aModule, zName, nName) ){
103318    rc = SQLITE_MISUSE_BKPT;
103319  }else{
103320    Module *pMod;
103321    pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
103322    if( pMod ){
103323      Module *pDel;
103324      char *zCopy = (char *)(&pMod[1]);
103325      memcpy(zCopy, zName, nName+1);
103326      pMod->zName = zCopy;
103327      pMod->pModule = pModule;
103328      pMod->pAux = pAux;
103329      pMod->xDestroy = xDestroy;
103330      pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,nName,(void*)pMod);
103331      assert( pDel==0 || pDel==pMod );
103332      if( pDel ){
103333        db->mallocFailed = 1;
103334        sqlite3DbFree(db, pDel);
103335      }
103336    }
103337  }
103338  rc = sqlite3ApiExit(db, rc);
103339  if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
103340
103341  sqlite3_mutex_leave(db->mutex);
103342  return rc;
103343}
103344
103345
103346/*
103347** External API function used to create a new virtual-table module.
103348*/
103349SQLITE_API int sqlite3_create_module(
103350  sqlite3 *db,                    /* Database in which module is registered */
103351  const char *zName,              /* Name assigned to this module */
103352  const sqlite3_module *pModule,  /* The definition of the module */
103353  void *pAux                      /* Context pointer for xCreate/xConnect */
103354){
103355  return createModule(db, zName, pModule, pAux, 0);
103356}
103357
103358/*
103359** External API function used to create a new virtual-table module.
103360*/
103361SQLITE_API int sqlite3_create_module_v2(
103362  sqlite3 *db,                    /* Database in which module is registered */
103363  const char *zName,              /* Name assigned to this module */
103364  const sqlite3_module *pModule,  /* The definition of the module */
103365  void *pAux,                     /* Context pointer for xCreate/xConnect */
103366  void (*xDestroy)(void *)        /* Module destructor function */
103367){
103368  return createModule(db, zName, pModule, pAux, xDestroy);
103369}
103370
103371/*
103372** Lock the virtual table so that it cannot be disconnected.
103373** Locks nest.  Every lock should have a corresponding unlock.
103374** If an unlock is omitted, resources leaks will occur.
103375**
103376** If a disconnect is attempted while a virtual table is locked,
103377** the disconnect is deferred until all locks have been removed.
103378*/
103379SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
103380  pVTab->nRef++;
103381}
103382
103383
103384/*
103385** pTab is a pointer to a Table structure representing a virtual-table.
103386** Return a pointer to the VTable object used by connection db to access
103387** this virtual-table, if one has been created, or NULL otherwise.
103388*/
103389SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
103390  VTable *pVtab;
103391  assert( IsVirtual(pTab) );
103392  for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
103393  return pVtab;
103394}
103395
103396/*
103397** Decrement the ref-count on a virtual table object. When the ref-count
103398** reaches zero, call the xDisconnect() method to delete the object.
103399*/
103400SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
103401  sqlite3 *db = pVTab->db;
103402
103403  assert( db );
103404  assert( pVTab->nRef>0 );
103405  assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
103406
103407  pVTab->nRef--;
103408  if( pVTab->nRef==0 ){
103409    sqlite3_vtab *p = pVTab->pVtab;
103410    if( p ){
103411      p->pModule->xDisconnect(p);
103412    }
103413    sqlite3DbFree(db, pVTab);
103414  }
103415}
103416
103417/*
103418** Table p is a virtual table. This function moves all elements in the
103419** p->pVTable list to the sqlite3.pDisconnect lists of their associated
103420** database connections to be disconnected at the next opportunity.
103421** Except, if argument db is not NULL, then the entry associated with
103422** connection db is left in the p->pVTable list.
103423*/
103424static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
103425  VTable *pRet = 0;
103426  VTable *pVTable = p->pVTable;
103427  p->pVTable = 0;
103428
103429  /* Assert that the mutex (if any) associated with the BtShared database
103430  ** that contains table p is held by the caller. See header comments
103431  ** above function sqlite3VtabUnlockList() for an explanation of why
103432  ** this makes it safe to access the sqlite3.pDisconnect list of any
103433  ** database connection that may have an entry in the p->pVTable list.
103434  */
103435  assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
103436
103437  while( pVTable ){
103438    sqlite3 *db2 = pVTable->db;
103439    VTable *pNext = pVTable->pNext;
103440    assert( db2 );
103441    if( db2==db ){
103442      pRet = pVTable;
103443      p->pVTable = pRet;
103444      pRet->pNext = 0;
103445    }else{
103446      pVTable->pNext = db2->pDisconnect;
103447      db2->pDisconnect = pVTable;
103448    }
103449    pVTable = pNext;
103450  }
103451
103452  assert( !db || pRet );
103453  return pRet;
103454}
103455
103456/*
103457** Table *p is a virtual table. This function removes the VTable object
103458** for table *p associated with database connection db from the linked
103459** list in p->pVTab. It also decrements the VTable ref count. This is
103460** used when closing database connection db to free all of its VTable
103461** objects without disturbing the rest of the Schema object (which may
103462** be being used by other shared-cache connections).
103463*/
103464SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
103465  VTable **ppVTab;
103466
103467  assert( IsVirtual(p) );
103468  assert( sqlite3BtreeHoldsAllMutexes(db) );
103469  assert( sqlite3_mutex_held(db->mutex) );
103470
103471  for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
103472    if( (*ppVTab)->db==db  ){
103473      VTable *pVTab = *ppVTab;
103474      *ppVTab = pVTab->pNext;
103475      sqlite3VtabUnlock(pVTab);
103476      break;
103477    }
103478  }
103479}
103480
103481
103482/*
103483** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
103484**
103485** This function may only be called when the mutexes associated with all
103486** shared b-tree databases opened using connection db are held by the
103487** caller. This is done to protect the sqlite3.pDisconnect list. The
103488** sqlite3.pDisconnect list is accessed only as follows:
103489**
103490**   1) By this function. In this case, all BtShared mutexes and the mutex
103491**      associated with the database handle itself must be held.
103492**
103493**   2) By function vtabDisconnectAll(), when it adds a VTable entry to
103494**      the sqlite3.pDisconnect list. In this case either the BtShared mutex
103495**      associated with the database the virtual table is stored in is held
103496**      or, if the virtual table is stored in a non-sharable database, then
103497**      the database handle mutex is held.
103498**
103499** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
103500** by multiple threads. It is thread-safe.
103501*/
103502SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
103503  VTable *p = db->pDisconnect;
103504  db->pDisconnect = 0;
103505
103506  assert( sqlite3BtreeHoldsAllMutexes(db) );
103507  assert( sqlite3_mutex_held(db->mutex) );
103508
103509  if( p ){
103510    sqlite3ExpirePreparedStatements(db);
103511    do {
103512      VTable *pNext = p->pNext;
103513      sqlite3VtabUnlock(p);
103514      p = pNext;
103515    }while( p );
103516  }
103517}
103518
103519/*
103520** Clear any and all virtual-table information from the Table record.
103521** This routine is called, for example, just before deleting the Table
103522** record.
103523**
103524** Since it is a virtual-table, the Table structure contains a pointer
103525** to the head of a linked list of VTable structures. Each VTable
103526** structure is associated with a single sqlite3* user of the schema.
103527** The reference count of the VTable structure associated with database
103528** connection db is decremented immediately (which may lead to the
103529** structure being xDisconnected and free). Any other VTable structures
103530** in the list are moved to the sqlite3.pDisconnect list of the associated
103531** database connection.
103532*/
103533SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
103534  if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
103535  if( p->azModuleArg ){
103536    int i;
103537    for(i=0; i<p->nModuleArg; i++){
103538      if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
103539    }
103540    sqlite3DbFree(db, p->azModuleArg);
103541  }
103542}
103543
103544/*
103545** Add a new module argument to pTable->azModuleArg[].
103546** The string is not copied - the pointer is stored.  The
103547** string will be freed automatically when the table is
103548** deleted.
103549*/
103550static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
103551  int i = pTable->nModuleArg++;
103552  int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
103553  char **azModuleArg;
103554  azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
103555  if( azModuleArg==0 ){
103556    int j;
103557    for(j=0; j<i; j++){
103558      sqlite3DbFree(db, pTable->azModuleArg[j]);
103559    }
103560    sqlite3DbFree(db, zArg);
103561    sqlite3DbFree(db, pTable->azModuleArg);
103562    pTable->nModuleArg = 0;
103563  }else{
103564    azModuleArg[i] = zArg;
103565    azModuleArg[i+1] = 0;
103566  }
103567  pTable->azModuleArg = azModuleArg;
103568}
103569
103570/*
103571** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
103572** statement.  The module name has been parsed, but the optional list
103573** of parameters that follow the module name are still pending.
103574*/
103575SQLITE_PRIVATE void sqlite3VtabBeginParse(
103576  Parse *pParse,        /* Parsing context */
103577  Token *pName1,        /* Name of new table, or database name */
103578  Token *pName2,        /* Name of new table or NULL */
103579  Token *pModuleName,   /* Name of the module for the virtual table */
103580  int ifNotExists       /* No error if the table already exists */
103581){
103582  int iDb;              /* The database the table is being created in */
103583  Table *pTable;        /* The new virtual table */
103584  sqlite3 *db;          /* Database connection */
103585
103586  sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
103587  pTable = pParse->pNewTable;
103588  if( pTable==0 ) return;
103589  assert( 0==pTable->pIndex );
103590
103591  db = pParse->db;
103592  iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
103593  assert( iDb>=0 );
103594
103595  pTable->tabFlags |= TF_Virtual;
103596  pTable->nModuleArg = 0;
103597  addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
103598  addModuleArgument(db, pTable, 0);
103599  addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
103600  pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
103601
103602#ifndef SQLITE_OMIT_AUTHORIZATION
103603  /* Creating a virtual table invokes the authorization callback twice.
103604  ** The first invocation, to obtain permission to INSERT a row into the
103605  ** sqlite_master table, has already been made by sqlite3StartTable().
103606  ** The second call, to obtain permission to create the table, is made now.
103607  */
103608  if( pTable->azModuleArg ){
103609    sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
103610            pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
103611  }
103612#endif
103613}
103614
103615/*
103616** This routine takes the module argument that has been accumulating
103617** in pParse->zArg[] and appends it to the list of arguments on the
103618** virtual table currently under construction in pParse->pTable.
103619*/
103620static void addArgumentToVtab(Parse *pParse){
103621  if( pParse->sArg.z && pParse->pNewTable ){
103622    const char *z = (const char*)pParse->sArg.z;
103623    int n = pParse->sArg.n;
103624    sqlite3 *db = pParse->db;
103625    addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
103626  }
103627}
103628
103629/*
103630** The parser calls this routine after the CREATE VIRTUAL TABLE statement
103631** has been completely parsed.
103632*/
103633SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
103634  Table *pTab = pParse->pNewTable;  /* The table being constructed */
103635  sqlite3 *db = pParse->db;         /* The database connection */
103636
103637  if( pTab==0 ) return;
103638  addArgumentToVtab(pParse);
103639  pParse->sArg.z = 0;
103640  if( pTab->nModuleArg<1 ) return;
103641
103642  /* If the CREATE VIRTUAL TABLE statement is being entered for the
103643  ** first time (in other words if the virtual table is actually being
103644  ** created now instead of just being read out of sqlite_master) then
103645  ** do additional initialization work and store the statement text
103646  ** in the sqlite_master table.
103647  */
103648  if( !db->init.busy ){
103649    char *zStmt;
103650    char *zWhere;
103651    int iDb;
103652    Vdbe *v;
103653
103654    /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
103655    if( pEnd ){
103656      pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
103657    }
103658    zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
103659
103660    /* A slot for the record has already been allocated in the
103661    ** SQLITE_MASTER table.  We just need to update that slot with all
103662    ** the information we've collected.
103663    **
103664    ** The VM register number pParse->regRowid holds the rowid of an
103665    ** entry in the sqlite_master table tht was created for this vtab
103666    ** by sqlite3StartTable().
103667    */
103668    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
103669    sqlite3NestedParse(pParse,
103670      "UPDATE %Q.%s "
103671         "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
103672       "WHERE rowid=#%d",
103673      db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
103674      pTab->zName,
103675      pTab->zName,
103676      zStmt,
103677      pParse->regRowid
103678    );
103679    sqlite3DbFree(db, zStmt);
103680    v = sqlite3GetVdbe(pParse);
103681    sqlite3ChangeCookie(pParse, iDb);
103682
103683    sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
103684    zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
103685    sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
103686    sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0,
103687                         pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
103688  }
103689
103690  /* If we are rereading the sqlite_master table create the in-memory
103691  ** record of the table. The xConnect() method is not called until
103692  ** the first time the virtual table is used in an SQL statement. This
103693  ** allows a schema that contains virtual tables to be loaded before
103694  ** the required virtual table implementations are registered.  */
103695  else {
103696    Table *pOld;
103697    Schema *pSchema = pTab->pSchema;
103698    const char *zName = pTab->zName;
103699    int nName = sqlite3Strlen30(zName);
103700    assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
103701    pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
103702    if( pOld ){
103703      db->mallocFailed = 1;
103704      assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
103705      return;
103706    }
103707    pParse->pNewTable = 0;
103708  }
103709}
103710
103711/*
103712** The parser calls this routine when it sees the first token
103713** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
103714*/
103715SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
103716  addArgumentToVtab(pParse);
103717  pParse->sArg.z = 0;
103718  pParse->sArg.n = 0;
103719}
103720
103721/*
103722** The parser calls this routine for each token after the first token
103723** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
103724*/
103725SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
103726  Token *pArg = &pParse->sArg;
103727  if( pArg->z==0 ){
103728    pArg->z = p->z;
103729    pArg->n = p->n;
103730  }else{
103731    assert(pArg->z < p->z);
103732    pArg->n = (int)(&p->z[p->n] - pArg->z);
103733  }
103734}
103735
103736/*
103737** Invoke a virtual table constructor (either xCreate or xConnect). The
103738** pointer to the function to invoke is passed as the fourth parameter
103739** to this procedure.
103740*/
103741static int vtabCallConstructor(
103742  sqlite3 *db,
103743  Table *pTab,
103744  Module *pMod,
103745  int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
103746  char **pzErr
103747){
103748  VtabCtx sCtx, *pPriorCtx;
103749  VTable *pVTable;
103750  int rc;
103751  const char *const*azArg = (const char *const*)pTab->azModuleArg;
103752  int nArg = pTab->nModuleArg;
103753  char *zErr = 0;
103754  char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
103755  int iDb;
103756
103757  if( !zModuleName ){
103758    return SQLITE_NOMEM;
103759  }
103760
103761  pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
103762  if( !pVTable ){
103763    sqlite3DbFree(db, zModuleName);
103764    return SQLITE_NOMEM;
103765  }
103766  pVTable->db = db;
103767  pVTable->pMod = pMod;
103768
103769  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
103770  pTab->azModuleArg[1] = db->aDb[iDb].zName;
103771
103772  /* Invoke the virtual table constructor */
103773  assert( &db->pVtabCtx );
103774  assert( xConstruct );
103775  sCtx.pTab = pTab;
103776  sCtx.pVTable = pVTable;
103777  pPriorCtx = db->pVtabCtx;
103778  db->pVtabCtx = &sCtx;
103779  rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
103780  db->pVtabCtx = pPriorCtx;
103781  if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
103782
103783  if( SQLITE_OK!=rc ){
103784    if( zErr==0 ){
103785      *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
103786    }else {
103787      *pzErr = sqlite3MPrintf(db, "%s", zErr);
103788      sqlite3_free(zErr);
103789    }
103790    sqlite3DbFree(db, pVTable);
103791  }else if( ALWAYS(pVTable->pVtab) ){
103792    /* Justification of ALWAYS():  A correct vtab constructor must allocate
103793    ** the sqlite3_vtab object if successful.  */
103794    pVTable->pVtab->pModule = pMod->pModule;
103795    pVTable->nRef = 1;
103796    if( sCtx.pTab ){
103797      const char *zFormat = "vtable constructor did not declare schema: %s";
103798      *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
103799      sqlite3VtabUnlock(pVTable);
103800      rc = SQLITE_ERROR;
103801    }else{
103802      int iCol;
103803      /* If everything went according to plan, link the new VTable structure
103804      ** into the linked list headed by pTab->pVTable. Then loop through the
103805      ** columns of the table to see if any of them contain the token "hidden".
103806      ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
103807      ** the type string.  */
103808      pVTable->pNext = pTab->pVTable;
103809      pTab->pVTable = pVTable;
103810
103811      for(iCol=0; iCol<pTab->nCol; iCol++){
103812        char *zType = pTab->aCol[iCol].zType;
103813        int nType;
103814        int i = 0;
103815        if( !zType ) continue;
103816        nType = sqlite3Strlen30(zType);
103817        if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
103818          for(i=0; i<nType; i++){
103819            if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
103820             && (zType[i+7]=='\0' || zType[i+7]==' ')
103821            ){
103822              i++;
103823              break;
103824            }
103825          }
103826        }
103827        if( i<nType ){
103828          int j;
103829          int nDel = 6 + (zType[i+6] ? 1 : 0);
103830          for(j=i; (j+nDel)<=nType; j++){
103831            zType[j] = zType[j+nDel];
103832          }
103833          if( zType[i]=='\0' && i>0 ){
103834            assert(zType[i-1]==' ');
103835            zType[i-1] = '\0';
103836          }
103837          pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
103838        }
103839      }
103840    }
103841  }
103842
103843  sqlite3DbFree(db, zModuleName);
103844  return rc;
103845}
103846
103847/*
103848** This function is invoked by the parser to call the xConnect() method
103849** of the virtual table pTab. If an error occurs, an error code is returned
103850** and an error left in pParse.
103851**
103852** This call is a no-op if table pTab is not a virtual table.
103853*/
103854SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
103855  sqlite3 *db = pParse->db;
103856  const char *zMod;
103857  Module *pMod;
103858  int rc;
103859
103860  assert( pTab );
103861  if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
103862    return SQLITE_OK;
103863  }
103864
103865  /* Locate the required virtual table module */
103866  zMod = pTab->azModuleArg[0];
103867  pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
103868
103869  if( !pMod ){
103870    const char *zModule = pTab->azModuleArg[0];
103871    sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
103872    rc = SQLITE_ERROR;
103873  }else{
103874    char *zErr = 0;
103875    rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
103876    if( rc!=SQLITE_OK ){
103877      sqlite3ErrorMsg(pParse, "%s", zErr);
103878    }
103879    sqlite3DbFree(db, zErr);
103880  }
103881
103882  return rc;
103883}
103884/*
103885** Grow the db->aVTrans[] array so that there is room for at least one
103886** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
103887*/
103888static int growVTrans(sqlite3 *db){
103889  const int ARRAY_INCR = 5;
103890
103891  /* Grow the sqlite3.aVTrans array if required */
103892  if( (db->nVTrans%ARRAY_INCR)==0 ){
103893    VTable **aVTrans;
103894    int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
103895    aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
103896    if( !aVTrans ){
103897      return SQLITE_NOMEM;
103898    }
103899    memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
103900    db->aVTrans = aVTrans;
103901  }
103902
103903  return SQLITE_OK;
103904}
103905
103906/*
103907** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
103908** have already been reserved using growVTrans().
103909*/
103910static void addToVTrans(sqlite3 *db, VTable *pVTab){
103911  /* Add pVtab to the end of sqlite3.aVTrans */
103912  db->aVTrans[db->nVTrans++] = pVTab;
103913  sqlite3VtabLock(pVTab);
103914}
103915
103916/*
103917** This function is invoked by the vdbe to call the xCreate method
103918** of the virtual table named zTab in database iDb.
103919**
103920** If an error occurs, *pzErr is set to point an an English language
103921** description of the error and an SQLITE_XXX error code is returned.
103922** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
103923*/
103924SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
103925  int rc = SQLITE_OK;
103926  Table *pTab;
103927  Module *pMod;
103928  const char *zMod;
103929
103930  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
103931  assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
103932
103933  /* Locate the required virtual table module */
103934  zMod = pTab->azModuleArg[0];
103935  pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
103936
103937  /* If the module has been registered and includes a Create method,
103938  ** invoke it now. If the module has not been registered, return an
103939  ** error. Otherwise, do nothing.
103940  */
103941  if( !pMod ){
103942    *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
103943    rc = SQLITE_ERROR;
103944  }else{
103945    rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
103946  }
103947
103948  /* Justification of ALWAYS():  The xConstructor method is required to
103949  ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
103950  if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
103951    rc = growVTrans(db);
103952    if( rc==SQLITE_OK ){
103953      addToVTrans(db, sqlite3GetVTable(db, pTab));
103954    }
103955  }
103956
103957  return rc;
103958}
103959
103960/*
103961** This function is used to set the schema of a virtual table.  It is only
103962** valid to call this function from within the xCreate() or xConnect() of a
103963** virtual table module.
103964*/
103965SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
103966  Parse *pParse;
103967
103968  int rc = SQLITE_OK;
103969  Table *pTab;
103970  char *zErr = 0;
103971
103972  sqlite3_mutex_enter(db->mutex);
103973  if( !db->pVtabCtx || !(pTab = db->pVtabCtx->pTab) ){
103974    sqlite3Error(db, SQLITE_MISUSE, 0);
103975    sqlite3_mutex_leave(db->mutex);
103976    return SQLITE_MISUSE_BKPT;
103977  }
103978  assert( (pTab->tabFlags & TF_Virtual)!=0 );
103979
103980  pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
103981  if( pParse==0 ){
103982    rc = SQLITE_NOMEM;
103983  }else{
103984    pParse->declareVtab = 1;
103985    pParse->db = db;
103986    pParse->nQueryLoop = 1;
103987
103988    if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
103989     && pParse->pNewTable
103990     && !db->mallocFailed
103991     && !pParse->pNewTable->pSelect
103992     && (pParse->pNewTable->tabFlags & TF_Virtual)==0
103993    ){
103994      if( !pTab->aCol ){
103995        pTab->aCol = pParse->pNewTable->aCol;
103996        pTab->nCol = pParse->pNewTable->nCol;
103997        pParse->pNewTable->nCol = 0;
103998        pParse->pNewTable->aCol = 0;
103999      }
104000      db->pVtabCtx->pTab = 0;
104001    }else{
104002      sqlite3Error(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
104003      sqlite3DbFree(db, zErr);
104004      rc = SQLITE_ERROR;
104005    }
104006    pParse->declareVtab = 0;
104007
104008    if( pParse->pVdbe ){
104009      sqlite3VdbeFinalize(pParse->pVdbe);
104010    }
104011    sqlite3DeleteTable(db, pParse->pNewTable);
104012    sqlite3StackFree(db, pParse);
104013  }
104014
104015  assert( (rc&0xff)==rc );
104016  rc = sqlite3ApiExit(db, rc);
104017  sqlite3_mutex_leave(db->mutex);
104018  return rc;
104019}
104020
104021/*
104022** This function is invoked by the vdbe to call the xDestroy method
104023** of the virtual table named zTab in database iDb. This occurs
104024** when a DROP TABLE is mentioned.
104025**
104026** This call is a no-op if zTab is not a virtual table.
104027*/
104028SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
104029  int rc = SQLITE_OK;
104030  Table *pTab;
104031
104032  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
104033  if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
104034    VTable *p = vtabDisconnectAll(db, pTab);
104035
104036    assert( rc==SQLITE_OK );
104037    rc = p->pMod->pModule->xDestroy(p->pVtab);
104038
104039    /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
104040    if( rc==SQLITE_OK ){
104041      assert( pTab->pVTable==p && p->pNext==0 );
104042      p->pVtab = 0;
104043      pTab->pVTable = 0;
104044      sqlite3VtabUnlock(p);
104045    }
104046  }
104047
104048  return rc;
104049}
104050
104051/*
104052** This function invokes either the xRollback or xCommit method
104053** of each of the virtual tables in the sqlite3.aVTrans array. The method
104054** called is identified by the second argument, "offset", which is
104055** the offset of the method to call in the sqlite3_module structure.
104056**
104057** The array is cleared after invoking the callbacks.
104058*/
104059static void callFinaliser(sqlite3 *db, int offset){
104060  int i;
104061  if( db->aVTrans ){
104062    for(i=0; i<db->nVTrans; i++){
104063      VTable *pVTab = db->aVTrans[i];
104064      sqlite3_vtab *p = pVTab->pVtab;
104065      if( p ){
104066        int (*x)(sqlite3_vtab *);
104067        x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
104068        if( x ) x(p);
104069      }
104070      pVTab->iSavepoint = 0;
104071      sqlite3VtabUnlock(pVTab);
104072    }
104073    sqlite3DbFree(db, db->aVTrans);
104074    db->nVTrans = 0;
104075    db->aVTrans = 0;
104076  }
104077}
104078
104079/*
104080** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
104081** array. Return the error code for the first error that occurs, or
104082** SQLITE_OK if all xSync operations are successful.
104083**
104084** Set *pzErrmsg to point to a buffer that should be released using
104085** sqlite3DbFree() containing an error message, if one is available.
104086*/
104087SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **pzErrmsg){
104088  int i;
104089  int rc = SQLITE_OK;
104090  VTable **aVTrans = db->aVTrans;
104091
104092  db->aVTrans = 0;
104093  for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
104094    int (*x)(sqlite3_vtab *);
104095    sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
104096    if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
104097      rc = x(pVtab);
104098      sqlite3DbFree(db, *pzErrmsg);
104099      *pzErrmsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
104100      sqlite3_free(pVtab->zErrMsg);
104101    }
104102  }
104103  db->aVTrans = aVTrans;
104104  return rc;
104105}
104106
104107/*
104108** Invoke the xRollback method of all virtual tables in the
104109** sqlite3.aVTrans array. Then clear the array itself.
104110*/
104111SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
104112  callFinaliser(db, offsetof(sqlite3_module,xRollback));
104113  return SQLITE_OK;
104114}
104115
104116/*
104117** Invoke the xCommit method of all virtual tables in the
104118** sqlite3.aVTrans array. Then clear the array itself.
104119*/
104120SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
104121  callFinaliser(db, offsetof(sqlite3_module,xCommit));
104122  return SQLITE_OK;
104123}
104124
104125/*
104126** If the virtual table pVtab supports the transaction interface
104127** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
104128** not currently open, invoke the xBegin method now.
104129**
104130** If the xBegin call is successful, place the sqlite3_vtab pointer
104131** in the sqlite3.aVTrans array.
104132*/
104133SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
104134  int rc = SQLITE_OK;
104135  const sqlite3_module *pModule;
104136
104137  /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
104138  ** than zero, then this function is being called from within a
104139  ** virtual module xSync() callback. It is illegal to write to
104140  ** virtual module tables in this case, so return SQLITE_LOCKED.
104141  */
104142  if( sqlite3VtabInSync(db) ){
104143    return SQLITE_LOCKED;
104144  }
104145  if( !pVTab ){
104146    return SQLITE_OK;
104147  }
104148  pModule = pVTab->pVtab->pModule;
104149
104150  if( pModule->xBegin ){
104151    int i;
104152
104153    /* If pVtab is already in the aVTrans array, return early */
104154    for(i=0; i<db->nVTrans; i++){
104155      if( db->aVTrans[i]==pVTab ){
104156        return SQLITE_OK;
104157      }
104158    }
104159
104160    /* Invoke the xBegin method. If successful, add the vtab to the
104161    ** sqlite3.aVTrans[] array. */
104162    rc = growVTrans(db);
104163    if( rc==SQLITE_OK ){
104164      rc = pModule->xBegin(pVTab->pVtab);
104165      if( rc==SQLITE_OK ){
104166        addToVTrans(db, pVTab);
104167      }
104168    }
104169  }
104170  return rc;
104171}
104172
104173/*
104174** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
104175** virtual tables that currently have an open transaction. Pass iSavepoint
104176** as the second argument to the virtual table method invoked.
104177**
104178** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
104179** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
104180** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
104181** an open transaction is invoked.
104182**
104183** If any virtual table method returns an error code other than SQLITE_OK,
104184** processing is abandoned and the error returned to the caller of this
104185** function immediately. If all calls to virtual table methods are successful,
104186** SQLITE_OK is returned.
104187*/
104188SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
104189  int rc = SQLITE_OK;
104190
104191  assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
104192  assert( iSavepoint>=0 );
104193  if( db->aVTrans ){
104194    int i;
104195    for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
104196      VTable *pVTab = db->aVTrans[i];
104197      const sqlite3_module *pMod = pVTab->pMod->pModule;
104198      if( pVTab->pVtab && pMod->iVersion>=2 ){
104199        int (*xMethod)(sqlite3_vtab *, int);
104200        switch( op ){
104201          case SAVEPOINT_BEGIN:
104202            xMethod = pMod->xSavepoint;
104203            pVTab->iSavepoint = iSavepoint+1;
104204            break;
104205          case SAVEPOINT_ROLLBACK:
104206            xMethod = pMod->xRollbackTo;
104207            break;
104208          default:
104209            xMethod = pMod->xRelease;
104210            break;
104211        }
104212        if( xMethod && pVTab->iSavepoint>iSavepoint ){
104213          rc = xMethod(pVTab->pVtab, iSavepoint);
104214        }
104215      }
104216    }
104217  }
104218  return rc;
104219}
104220
104221/*
104222** The first parameter (pDef) is a function implementation.  The
104223** second parameter (pExpr) is the first argument to this function.
104224** If pExpr is a column in a virtual table, then let the virtual
104225** table implementation have an opportunity to overload the function.
104226**
104227** This routine is used to allow virtual table implementations to
104228** overload MATCH, LIKE, GLOB, and REGEXP operators.
104229**
104230** Return either the pDef argument (indicating no change) or a
104231** new FuncDef structure that is marked as ephemeral using the
104232** SQLITE_FUNC_EPHEM flag.
104233*/
104234SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
104235  sqlite3 *db,    /* Database connection for reporting malloc problems */
104236  FuncDef *pDef,  /* Function to possibly overload */
104237  int nArg,       /* Number of arguments to the function */
104238  Expr *pExpr     /* First argument to the function */
104239){
104240  Table *pTab;
104241  sqlite3_vtab *pVtab;
104242  sqlite3_module *pMod;
104243  void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
104244  void *pArg = 0;
104245  FuncDef *pNew;
104246  int rc = 0;
104247  char *zLowerName;
104248  unsigned char *z;
104249
104250
104251  /* Check to see the left operand is a column in a virtual table */
104252  if( NEVER(pExpr==0) ) return pDef;
104253  if( pExpr->op!=TK_COLUMN ) return pDef;
104254  pTab = pExpr->pTab;
104255  if( NEVER(pTab==0) ) return pDef;
104256  if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
104257  pVtab = sqlite3GetVTable(db, pTab)->pVtab;
104258  assert( pVtab!=0 );
104259  assert( pVtab->pModule!=0 );
104260  pMod = (sqlite3_module *)pVtab->pModule;
104261  if( pMod->xFindFunction==0 ) return pDef;
104262
104263  /* Call the xFindFunction method on the virtual table implementation
104264  ** to see if the implementation wants to overload this function
104265  */
104266  zLowerName = sqlite3DbStrDup(db, pDef->zName);
104267  if( zLowerName ){
104268    for(z=(unsigned char*)zLowerName; *z; z++){
104269      *z = sqlite3UpperToLower[*z];
104270    }
104271    rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
104272    sqlite3DbFree(db, zLowerName);
104273  }
104274  if( rc==0 ){
104275    return pDef;
104276  }
104277
104278  /* Create a new ephemeral function definition for the overloaded
104279  ** function */
104280  pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
104281                             + sqlite3Strlen30(pDef->zName) + 1);
104282  if( pNew==0 ){
104283    return pDef;
104284  }
104285  *pNew = *pDef;
104286  pNew->zName = (char *)&pNew[1];
104287  memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
104288  pNew->xFunc = xFunc;
104289  pNew->pUserData = pArg;
104290  pNew->flags |= SQLITE_FUNC_EPHEM;
104291  return pNew;
104292}
104293
104294/*
104295** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
104296** array so that an OP_VBegin will get generated for it.  Add pTab to the
104297** array if it is missing.  If pTab is already in the array, this routine
104298** is a no-op.
104299*/
104300SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
104301  Parse *pToplevel = sqlite3ParseToplevel(pParse);
104302  int i, n;
104303  Table **apVtabLock;
104304
104305  assert( IsVirtual(pTab) );
104306  for(i=0; i<pToplevel->nVtabLock; i++){
104307    if( pTab==pToplevel->apVtabLock[i] ) return;
104308  }
104309  n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
104310  apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
104311  if( apVtabLock ){
104312    pToplevel->apVtabLock = apVtabLock;
104313    pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
104314  }else{
104315    pToplevel->db->mallocFailed = 1;
104316  }
104317}
104318
104319/*
104320** Return the ON CONFLICT resolution mode in effect for the virtual
104321** table update operation currently in progress.
104322**
104323** The results of this routine are undefined unless it is called from
104324** within an xUpdate method.
104325*/
104326SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){
104327  static const unsigned char aMap[] = {
104328    SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE
104329  };
104330  assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
104331  assert( OE_Ignore==4 && OE_Replace==5 );
104332  assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
104333  return (int)aMap[db->vtabOnConflict-1];
104334}
104335
104336/*
104337** Call from within the xCreate() or xConnect() methods to provide
104338** the SQLite core with additional information about the behavior
104339** of the virtual table being implemented.
104340*/
104341SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
104342  va_list ap;
104343  int rc = SQLITE_OK;
104344
104345  sqlite3_mutex_enter(db->mutex);
104346
104347  va_start(ap, op);
104348  switch( op ){
104349    case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
104350      VtabCtx *p = db->pVtabCtx;
104351      if( !p ){
104352        rc = SQLITE_MISUSE_BKPT;
104353      }else{
104354        assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 );
104355        p->pVTable->bConstraint = (u8)va_arg(ap, int);
104356      }
104357      break;
104358    }
104359    default:
104360      rc = SQLITE_MISUSE_BKPT;
104361      break;
104362  }
104363  va_end(ap);
104364
104365  if( rc!=SQLITE_OK ) sqlite3Error(db, rc, 0);
104366  sqlite3_mutex_leave(db->mutex);
104367  return rc;
104368}
104369
104370#endif /* SQLITE_OMIT_VIRTUALTABLE */
104371
104372/************** End of vtab.c ************************************************/
104373/************** Begin file where.c *******************************************/
104374/*
104375** 2001 September 15
104376**
104377** The author disclaims copyright to this source code.  In place of
104378** a legal notice, here is a blessing:
104379**
104380**    May you do good and not evil.
104381**    May you find forgiveness for yourself and forgive others.
104382**    May you share freely, never taking more than you give.
104383**
104384*************************************************************************
104385** This module contains C code that generates VDBE code used to process
104386** the WHERE clause of SQL statements.  This module is responsible for
104387** generating the code that loops through a table looking for applicable
104388** rows.  Indices are selected and used to speed the search when doing
104389** so is applicable.  Because this module is responsible for selecting
104390** indices, you might also think of this module as the "query optimizer".
104391*/
104392
104393
104394/*
104395** Trace output macros
104396*/
104397#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
104398/***/ int sqlite3WhereTrace = 0;
104399#endif
104400#if defined(SQLITE_DEBUG) \
104401    && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
104402# define WHERETRACE(X)  if(sqlite3WhereTrace) sqlite3DebugPrintf X
104403#else
104404# define WHERETRACE(X)
104405#endif
104406
104407/* Forward reference
104408*/
104409typedef struct WhereClause WhereClause;
104410typedef struct WhereMaskSet WhereMaskSet;
104411typedef struct WhereOrInfo WhereOrInfo;
104412typedef struct WhereAndInfo WhereAndInfo;
104413typedef struct WhereCost WhereCost;
104414
104415/*
104416** The query generator uses an array of instances of this structure to
104417** help it analyze the subexpressions of the WHERE clause.  Each WHERE
104418** clause subexpression is separated from the others by AND operators,
104419** usually, or sometimes subexpressions separated by OR.
104420**
104421** All WhereTerms are collected into a single WhereClause structure.
104422** The following identity holds:
104423**
104424**        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
104425**
104426** When a term is of the form:
104427**
104428**              X <op> <expr>
104429**
104430** where X is a column name and <op> is one of certain operators,
104431** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
104432** cursor number and column number for X.  WhereTerm.eOperator records
104433** the <op> using a bitmask encoding defined by WO_xxx below.  The
104434** use of a bitmask encoding for the operator allows us to search
104435** quickly for terms that match any of several different operators.
104436**
104437** A WhereTerm might also be two or more subterms connected by OR:
104438**
104439**         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
104440**
104441** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR
104442** and the WhereTerm.u.pOrInfo field points to auxiliary information that
104443** is collected about the
104444**
104445** If a term in the WHERE clause does not match either of the two previous
104446** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
104447** to the original subexpression content and wtFlags is set up appropriately
104448** but no other fields in the WhereTerm object are meaningful.
104449**
104450** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
104451** but they do so indirectly.  A single WhereMaskSet structure translates
104452** cursor number into bits and the translated bit is stored in the prereq
104453** fields.  The translation is used in order to maximize the number of
104454** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
104455** spread out over the non-negative integers.  For example, the cursor
104456** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
104457** translates these sparse cursor numbers into consecutive integers
104458** beginning with 0 in order to make the best possible use of the available
104459** bits in the Bitmask.  So, in the example above, the cursor numbers
104460** would be mapped into integers 0 through 7.
104461**
104462** The number of terms in a join is limited by the number of bits
104463** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
104464** is only able to process joins with 64 or fewer tables.
104465*/
104466typedef struct WhereTerm WhereTerm;
104467struct WhereTerm {
104468  Expr *pExpr;            /* Pointer to the subexpression that is this term */
104469  int iParent;            /* Disable pWC->a[iParent] when this term disabled */
104470  int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
104471  union {
104472    int leftColumn;         /* Column number of X in "X <op> <expr>" */
104473    WhereOrInfo *pOrInfo;   /* Extra information if (eOperator & WO_OR)!=0 */
104474    WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
104475  } u;
104476  u16 eOperator;          /* A WO_xx value describing <op> */
104477  u8 wtFlags;             /* TERM_xxx bit flags.  See below */
104478  u8 nChild;              /* Number of children that must disable us */
104479  WhereClause *pWC;       /* The clause this term is part of */
104480  Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
104481  Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
104482};
104483
104484/*
104485** Allowed values of WhereTerm.wtFlags
104486*/
104487#define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
104488#define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
104489#define TERM_CODED      0x04   /* This term is already coded */
104490#define TERM_COPIED     0x08   /* Has a child */
104491#define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
104492#define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
104493#define TERM_OR_OK      0x40   /* Used during OR-clause processing */
104494#ifdef SQLITE_ENABLE_STAT3
104495#  define TERM_VNULL    0x80   /* Manufactured x>NULL or x<=NULL term */
104496#else
104497#  define TERM_VNULL    0x00   /* Disabled if not using stat3 */
104498#endif
104499
104500/*
104501** An instance of the following structure holds all information about a
104502** WHERE clause.  Mostly this is a container for one or more WhereTerms.
104503**
104504** Explanation of pOuter:  For a WHERE clause of the form
104505**
104506**           a AND ((b AND c) OR (d AND e)) AND f
104507**
104508** There are separate WhereClause objects for the whole clause and for
104509** the subclauses "(b AND c)" and "(d AND e)".  The pOuter field of the
104510** subclauses points to the WhereClause object for the whole clause.
104511*/
104512struct WhereClause {
104513  Parse *pParse;           /* The parser context */
104514  WhereMaskSet *pMaskSet;  /* Mapping of table cursor numbers to bitmasks */
104515  WhereClause *pOuter;     /* Outer conjunction */
104516  u8 op;                   /* Split operator.  TK_AND or TK_OR */
104517  u16 wctrlFlags;          /* Might include WHERE_AND_ONLY */
104518  int nTerm;               /* Number of terms */
104519  int nSlot;               /* Number of entries in a[] */
104520  WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
104521#if defined(SQLITE_SMALL_STACK)
104522  WhereTerm aStatic[1];    /* Initial static space for a[] */
104523#else
104524  WhereTerm aStatic[8];    /* Initial static space for a[] */
104525#endif
104526};
104527
104528/*
104529** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
104530** a dynamically allocated instance of the following structure.
104531*/
104532struct WhereOrInfo {
104533  WhereClause wc;          /* Decomposition into subterms */
104534  Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
104535};
104536
104537/*
104538** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
104539** a dynamically allocated instance of the following structure.
104540*/
104541struct WhereAndInfo {
104542  WhereClause wc;          /* The subexpression broken out */
104543};
104544
104545/*
104546** An instance of the following structure keeps track of a mapping
104547** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
104548**
104549** The VDBE cursor numbers are small integers contained in
104550** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE
104551** clause, the cursor numbers might not begin with 0 and they might
104552** contain gaps in the numbering sequence.  But we want to make maximum
104553** use of the bits in our bitmasks.  This structure provides a mapping
104554** from the sparse cursor numbers into consecutive integers beginning
104555** with 0.
104556**
104557** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
104558** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
104559**
104560** For example, if the WHERE clause expression used these VDBE
104561** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
104562** would map those cursor numbers into bits 0 through 5.
104563**
104564** Note that the mapping is not necessarily ordered.  In the example
104565** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
104566** 57->5, 73->4.  Or one of 719 other combinations might be used. It
104567** does not really matter.  What is important is that sparse cursor
104568** numbers all get mapped into bit numbers that begin with 0 and contain
104569** no gaps.
104570*/
104571struct WhereMaskSet {
104572  int n;                        /* Number of assigned cursor values */
104573  int ix[BMS];                  /* Cursor assigned to each bit */
104574};
104575
104576/*
104577** A WhereCost object records a lookup strategy and the estimated
104578** cost of pursuing that strategy.
104579*/
104580struct WhereCost {
104581  WherePlan plan;    /* The lookup strategy */
104582  double rCost;      /* Overall cost of pursuing this search strategy */
104583  Bitmask used;      /* Bitmask of cursors used by this plan */
104584};
104585
104586/*
104587** Bitmasks for the operators that indices are able to exploit.  An
104588** OR-ed combination of these values can be used when searching for
104589** terms in the where clause.
104590*/
104591#define WO_IN     0x001
104592#define WO_EQ     0x002
104593#define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
104594#define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
104595#define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
104596#define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
104597#define WO_MATCH  0x040
104598#define WO_ISNULL 0x080
104599#define WO_OR     0x100       /* Two or more OR-connected terms */
104600#define WO_AND    0x200       /* Two or more AND-connected terms */
104601#define WO_EQUIV  0x400       /* Of the form A==B, both columns */
104602#define WO_NOOP   0x800       /* This term does not restrict search space */
104603
104604#define WO_ALL    0xfff       /* Mask of all possible WO_* values */
104605#define WO_SINGLE 0x0ff       /* Mask of all non-compound WO_* values */
104606
104607/*
104608** Value for wsFlags returned by bestIndex() and stored in
104609** WhereLevel.wsFlags.  These flags determine which search
104610** strategies are appropriate.
104611**
104612** The least significant 12 bits is reserved as a mask for WO_ values above.
104613** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
104614** But if the table is the right table of a left join, WhereLevel.wsFlags
104615** is set to WO_IN|WO_EQ.  The WhereLevel.wsFlags field can then be used as
104616** the "op" parameter to findTerm when we are resolving equality constraints.
104617** ISNULL constraints will then not be used on the right table of a left
104618** join.  Tickets #2177 and #2189.
104619*/
104620#define WHERE_ROWID_EQ     0x00001000  /* rowid=EXPR or rowid IN (...) */
104621#define WHERE_ROWID_RANGE  0x00002000  /* rowid<EXPR and/or rowid>EXPR */
104622#define WHERE_COLUMN_EQ    0x00010000  /* x=EXPR or x IN (...) or x IS NULL */
104623#define WHERE_COLUMN_RANGE 0x00020000  /* x<EXPR and/or x>EXPR */
104624#define WHERE_COLUMN_IN    0x00040000  /* x IN (...) */
104625#define WHERE_COLUMN_NULL  0x00080000  /* x IS NULL */
104626#define WHERE_INDEXED      0x000f0000  /* Anything that uses an index */
104627#define WHERE_NOT_FULLSCAN 0x100f3000  /* Does not do a full table scan */
104628#define WHERE_IN_ABLE      0x080f1000  /* Able to support an IN operator */
104629#define WHERE_TOP_LIMIT    0x00100000  /* x<EXPR or x<=EXPR constraint */
104630#define WHERE_BTM_LIMIT    0x00200000  /* x>EXPR or x>=EXPR constraint */
104631#define WHERE_BOTH_LIMIT   0x00300000  /* Both x>EXPR and x<EXPR */
104632#define WHERE_IDX_ONLY     0x00400000  /* Use index only - omit table */
104633#define WHERE_ORDERED      0x00800000  /* Output will appear in correct order */
104634#define WHERE_REVERSE      0x01000000  /* Scan in reverse order */
104635#define WHERE_UNIQUE       0x02000000  /* Selects no more than one row */
104636#define WHERE_ALL_UNIQUE   0x04000000  /* This and all prior have one row */
104637#define WHERE_OB_UNIQUE    0x00004000  /* Values in ORDER BY columns are
104638                                       ** different for every output row */
104639#define WHERE_VIRTUALTABLE 0x08000000  /* Use virtual-table processing */
104640#define WHERE_MULTI_OR     0x10000000  /* OR using multiple indices */
104641#define WHERE_TEMP_INDEX   0x20000000  /* Uses an ephemeral index */
104642#define WHERE_DISTINCT     0x40000000  /* Correct order for DISTINCT */
104643#define WHERE_COVER_SCAN   0x80000000  /* Full scan of a covering index */
104644
104645/*
104646** This module contains many separate subroutines that work together to
104647** find the best indices to use for accessing a particular table in a query.
104648** An instance of the following structure holds context information about the
104649** index search so that it can be more easily passed between the various
104650** routines.
104651*/
104652typedef struct WhereBestIdx WhereBestIdx;
104653struct WhereBestIdx {
104654  Parse *pParse;                  /* Parser context */
104655  WhereClause *pWC;               /* The WHERE clause */
104656  struct SrcList_item *pSrc;      /* The FROM clause term to search */
104657  Bitmask notReady;               /* Mask of cursors not available */
104658  Bitmask notValid;               /* Cursors not available for any purpose */
104659  ExprList *pOrderBy;             /* The ORDER BY clause */
104660  ExprList *pDistinct;            /* The select-list if query is DISTINCT */
104661  sqlite3_index_info **ppIdxInfo; /* Index information passed to xBestIndex */
104662  int i, n;                       /* Which loop is being coded; # of loops */
104663  WhereLevel *aLevel;             /* Info about outer loops */
104664  WhereCost cost;                 /* Lowest cost query plan */
104665};
104666
104667/*
104668** Return TRUE if the probe cost is less than the baseline cost
104669*/
104670static int compareCost(const WhereCost *pProbe, const WhereCost *pBaseline){
104671  if( pProbe->rCost<pBaseline->rCost ) return 1;
104672  if( pProbe->rCost>pBaseline->rCost ) return 0;
104673  if( pProbe->plan.nOBSat>pBaseline->plan.nOBSat ) return 1;
104674  if( pProbe->plan.nRow<pBaseline->plan.nRow ) return 1;
104675  return 0;
104676}
104677
104678/*
104679** Initialize a preallocated WhereClause structure.
104680*/
104681static void whereClauseInit(
104682  WhereClause *pWC,        /* The WhereClause to be initialized */
104683  Parse *pParse,           /* The parsing context */
104684  WhereMaskSet *pMaskSet,  /* Mapping from table cursor numbers to bitmasks */
104685  u16 wctrlFlags           /* Might include WHERE_AND_ONLY */
104686){
104687  pWC->pParse = pParse;
104688  pWC->pMaskSet = pMaskSet;
104689  pWC->pOuter = 0;
104690  pWC->nTerm = 0;
104691  pWC->nSlot = ArraySize(pWC->aStatic);
104692  pWC->a = pWC->aStatic;
104693  pWC->wctrlFlags = wctrlFlags;
104694}
104695
104696/* Forward reference */
104697static void whereClauseClear(WhereClause*);
104698
104699/*
104700** Deallocate all memory associated with a WhereOrInfo object.
104701*/
104702static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
104703  whereClauseClear(&p->wc);
104704  sqlite3DbFree(db, p);
104705}
104706
104707/*
104708** Deallocate all memory associated with a WhereAndInfo object.
104709*/
104710static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
104711  whereClauseClear(&p->wc);
104712  sqlite3DbFree(db, p);
104713}
104714
104715/*
104716** Deallocate a WhereClause structure.  The WhereClause structure
104717** itself is not freed.  This routine is the inverse of whereClauseInit().
104718*/
104719static void whereClauseClear(WhereClause *pWC){
104720  int i;
104721  WhereTerm *a;
104722  sqlite3 *db = pWC->pParse->db;
104723  for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
104724    if( a->wtFlags & TERM_DYNAMIC ){
104725      sqlite3ExprDelete(db, a->pExpr);
104726    }
104727    if( a->wtFlags & TERM_ORINFO ){
104728      whereOrInfoDelete(db, a->u.pOrInfo);
104729    }else if( a->wtFlags & TERM_ANDINFO ){
104730      whereAndInfoDelete(db, a->u.pAndInfo);
104731    }
104732  }
104733  if( pWC->a!=pWC->aStatic ){
104734    sqlite3DbFree(db, pWC->a);
104735  }
104736}
104737
104738/*
104739** Add a single new WhereTerm entry to the WhereClause object pWC.
104740** The new WhereTerm object is constructed from Expr p and with wtFlags.
104741** The index in pWC->a[] of the new WhereTerm is returned on success.
104742** 0 is returned if the new WhereTerm could not be added due to a memory
104743** allocation error.  The memory allocation failure will be recorded in
104744** the db->mallocFailed flag so that higher-level functions can detect it.
104745**
104746** This routine will increase the size of the pWC->a[] array as necessary.
104747**
104748** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
104749** for freeing the expression p is assumed by the WhereClause object pWC.
104750** This is true even if this routine fails to allocate a new WhereTerm.
104751**
104752** WARNING:  This routine might reallocate the space used to store
104753** WhereTerms.  All pointers to WhereTerms should be invalidated after
104754** calling this routine.  Such pointers may be reinitialized by referencing
104755** the pWC->a[] array.
104756*/
104757static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
104758  WhereTerm *pTerm;
104759  int idx;
104760  testcase( wtFlags & TERM_VIRTUAL );  /* EV: R-00211-15100 */
104761  if( pWC->nTerm>=pWC->nSlot ){
104762    WhereTerm *pOld = pWC->a;
104763    sqlite3 *db = pWC->pParse->db;
104764    pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
104765    if( pWC->a==0 ){
104766      if( wtFlags & TERM_DYNAMIC ){
104767        sqlite3ExprDelete(db, p);
104768      }
104769      pWC->a = pOld;
104770      return 0;
104771    }
104772    memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
104773    if( pOld!=pWC->aStatic ){
104774      sqlite3DbFree(db, pOld);
104775    }
104776    pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
104777  }
104778  pTerm = &pWC->a[idx = pWC->nTerm++];
104779  pTerm->pExpr = sqlite3ExprSkipCollate(p);
104780  pTerm->wtFlags = wtFlags;
104781  pTerm->pWC = pWC;
104782  pTerm->iParent = -1;
104783  return idx;
104784}
104785
104786/*
104787** This routine identifies subexpressions in the WHERE clause where
104788** each subexpression is separated by the AND operator or some other
104789** operator specified in the op parameter.  The WhereClause structure
104790** is filled with pointers to subexpressions.  For example:
104791**
104792**    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
104793**           \________/     \_______________/     \________________/
104794**            slot[0]            slot[1]               slot[2]
104795**
104796** The original WHERE clause in pExpr is unaltered.  All this routine
104797** does is make slot[] entries point to substructure within pExpr.
104798**
104799** In the previous sentence and in the diagram, "slot[]" refers to
104800** the WhereClause.a[] array.  The slot[] array grows as needed to contain
104801** all terms of the WHERE clause.
104802*/
104803static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
104804  pWC->op = (u8)op;
104805  if( pExpr==0 ) return;
104806  if( pExpr->op!=op ){
104807    whereClauseInsert(pWC, pExpr, 0);
104808  }else{
104809    whereSplit(pWC, pExpr->pLeft, op);
104810    whereSplit(pWC, pExpr->pRight, op);
104811  }
104812}
104813
104814/*
104815** Initialize an expression mask set (a WhereMaskSet object)
104816*/
104817#define initMaskSet(P)  memset(P, 0, sizeof(*P))
104818
104819/*
104820** Return the bitmask for the given cursor number.  Return 0 if
104821** iCursor is not in the set.
104822*/
104823static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
104824  int i;
104825  assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
104826  for(i=0; i<pMaskSet->n; i++){
104827    if( pMaskSet->ix[i]==iCursor ){
104828      return ((Bitmask)1)<<i;
104829    }
104830  }
104831  return 0;
104832}
104833
104834/*
104835** Create a new mask for cursor iCursor.
104836**
104837** There is one cursor per table in the FROM clause.  The number of
104838** tables in the FROM clause is limited by a test early in the
104839** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
104840** array will never overflow.
104841*/
104842static void createMask(WhereMaskSet *pMaskSet, int iCursor){
104843  assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
104844  pMaskSet->ix[pMaskSet->n++] = iCursor;
104845}
104846
104847/*
104848** This routine walks (recursively) an expression tree and generates
104849** a bitmask indicating which tables are used in that expression
104850** tree.
104851**
104852** In order for this routine to work, the calling function must have
104853** previously invoked sqlite3ResolveExprNames() on the expression.  See
104854** the header comment on that routine for additional information.
104855** The sqlite3ResolveExprNames() routines looks for column names and
104856** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
104857** the VDBE cursor number of the table.  This routine just has to
104858** translate the cursor numbers into bitmask values and OR all
104859** the bitmasks together.
104860*/
104861static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
104862static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
104863static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
104864  Bitmask mask = 0;
104865  if( p==0 ) return 0;
104866  if( p->op==TK_COLUMN ){
104867    mask = getMask(pMaskSet, p->iTable);
104868    return mask;
104869  }
104870  mask = exprTableUsage(pMaskSet, p->pRight);
104871  mask |= exprTableUsage(pMaskSet, p->pLeft);
104872  if( ExprHasProperty(p, EP_xIsSelect) ){
104873    mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
104874  }else{
104875    mask |= exprListTableUsage(pMaskSet, p->x.pList);
104876  }
104877  return mask;
104878}
104879static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
104880  int i;
104881  Bitmask mask = 0;
104882  if( pList ){
104883    for(i=0; i<pList->nExpr; i++){
104884      mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
104885    }
104886  }
104887  return mask;
104888}
104889static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
104890  Bitmask mask = 0;
104891  while( pS ){
104892    SrcList *pSrc = pS->pSrc;
104893    mask |= exprListTableUsage(pMaskSet, pS->pEList);
104894    mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
104895    mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
104896    mask |= exprTableUsage(pMaskSet, pS->pWhere);
104897    mask |= exprTableUsage(pMaskSet, pS->pHaving);
104898    if( ALWAYS(pSrc!=0) ){
104899      int i;
104900      for(i=0; i<pSrc->nSrc; i++){
104901        mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect);
104902        mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn);
104903      }
104904    }
104905    pS = pS->pPrior;
104906  }
104907  return mask;
104908}
104909
104910/*
104911** Return TRUE if the given operator is one of the operators that is
104912** allowed for an indexable WHERE clause term.  The allowed operators are
104913** "=", "<", ">", "<=", ">=", and "IN".
104914**
104915** IMPLEMENTATION-OF: R-59926-26393 To be usable by an index a term must be
104916** of one of the following forms: column = expression column > expression
104917** column >= expression column < expression column <= expression
104918** expression = column expression > column expression >= column
104919** expression < column expression <= column column IN
104920** (expression-list) column IN (subquery) column IS NULL
104921*/
104922static int allowedOp(int op){
104923  assert( TK_GT>TK_EQ && TK_GT<TK_GE );
104924  assert( TK_LT>TK_EQ && TK_LT<TK_GE );
104925  assert( TK_LE>TK_EQ && TK_LE<TK_GE );
104926  assert( TK_GE==TK_EQ+4 );
104927  return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
104928}
104929
104930/*
104931** Swap two objects of type TYPE.
104932*/
104933#define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
104934
104935/*
104936** Commute a comparison operator.  Expressions of the form "X op Y"
104937** are converted into "Y op X".
104938**
104939** If left/right precedence rules come into play when determining the
104940** collating
104941** side of the comparison, it remains associated with the same side after
104942** the commutation. So "Y collate NOCASE op X" becomes
104943** "X op Y". This is because any collation sequence on
104944** the left hand side of a comparison overrides any collation sequence
104945** attached to the right. For the same reason the EP_Collate flag
104946** is not commuted.
104947*/
104948static void exprCommute(Parse *pParse, Expr *pExpr){
104949  u16 expRight = (pExpr->pRight->flags & EP_Collate);
104950  u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
104951  assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
104952  if( expRight==expLeft ){
104953    /* Either X and Y both have COLLATE operator or neither do */
104954    if( expRight ){
104955      /* Both X and Y have COLLATE operators.  Make sure X is always
104956      ** used by clearing the EP_Collate flag from Y. */
104957      pExpr->pRight->flags &= ~EP_Collate;
104958    }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
104959      /* Neither X nor Y have COLLATE operators, but X has a non-default
104960      ** collating sequence.  So add the EP_Collate marker on X to cause
104961      ** it to be searched first. */
104962      pExpr->pLeft->flags |= EP_Collate;
104963    }
104964  }
104965  SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
104966  if( pExpr->op>=TK_GT ){
104967    assert( TK_LT==TK_GT+2 );
104968    assert( TK_GE==TK_LE+2 );
104969    assert( TK_GT>TK_EQ );
104970    assert( TK_GT<TK_LE );
104971    assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
104972    pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
104973  }
104974}
104975
104976/*
104977** Translate from TK_xx operator to WO_xx bitmask.
104978*/
104979static u16 operatorMask(int op){
104980  u16 c;
104981  assert( allowedOp(op) );
104982  if( op==TK_IN ){
104983    c = WO_IN;
104984  }else if( op==TK_ISNULL ){
104985    c = WO_ISNULL;
104986  }else{
104987    assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
104988    c = (u16)(WO_EQ<<(op-TK_EQ));
104989  }
104990  assert( op!=TK_ISNULL || c==WO_ISNULL );
104991  assert( op!=TK_IN || c==WO_IN );
104992  assert( op!=TK_EQ || c==WO_EQ );
104993  assert( op!=TK_LT || c==WO_LT );
104994  assert( op!=TK_LE || c==WO_LE );
104995  assert( op!=TK_GT || c==WO_GT );
104996  assert( op!=TK_GE || c==WO_GE );
104997  return c;
104998}
104999
105000/*
105001** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
105002** where X is a reference to the iColumn of table iCur and <op> is one of
105003** the WO_xx operator codes specified by the op parameter.
105004** Return a pointer to the term.  Return 0 if not found.
105005**
105006** The term returned might by Y=<expr> if there is another constraint in
105007** the WHERE clause that specifies that X=Y.  Any such constraints will be
105008** identified by the WO_EQUIV bit in the pTerm->eOperator field.  The
105009** aEquiv[] array holds X and all its equivalents, with each SQL variable
105010** taking up two slots in aEquiv[].  The first slot is for the cursor number
105011** and the second is for the column number.  There are 22 slots in aEquiv[]
105012** so that means we can look for X plus up to 10 other equivalent values.
105013** Hence a search for X will return <expr> if X=A1 and A1=A2 and A2=A3
105014** and ... and A9=A10 and A10=<expr>.
105015**
105016** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
105017** then try for the one with no dependencies on <expr> - in other words where
105018** <expr> is a constant expression of some kind.  Only return entries of
105019** the form "X <op> Y" where Y is a column in another table if no terms of
105020** the form "X <op> <const-expr>" exist.   If no terms with a constant RHS
105021** exist, try to return a term that does not use WO_EQUIV.
105022*/
105023static WhereTerm *findTerm(
105024  WhereClause *pWC,     /* The WHERE clause to be searched */
105025  int iCur,             /* Cursor number of LHS */
105026  int iColumn,          /* Column number of LHS */
105027  Bitmask notReady,     /* RHS must not overlap with this mask */
105028  u32 op,               /* Mask of WO_xx values describing operator */
105029  Index *pIdx           /* Must be compatible with this index, if not NULL */
105030){
105031  WhereTerm *pTerm;            /* Term being examined as possible result */
105032  WhereTerm *pResult = 0;      /* The answer to return */
105033  WhereClause *pWCOrig = pWC;  /* Original pWC value */
105034  int j, k;                    /* Loop counters */
105035  Expr *pX;                /* Pointer to an expression */
105036  Parse *pParse;           /* Parsing context */
105037  int iOrigCol = iColumn;  /* Original value of iColumn */
105038  int nEquiv = 2;          /* Number of entires in aEquiv[] */
105039  int iEquiv = 2;          /* Number of entries of aEquiv[] processed so far */
105040  int aEquiv[22];          /* iCur,iColumn and up to 10 other equivalents */
105041
105042  assert( iCur>=0 );
105043  aEquiv[0] = iCur;
105044  aEquiv[1] = iColumn;
105045  for(;;){
105046    for(pWC=pWCOrig; pWC; pWC=pWC->pOuter){
105047      for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
105048        if( pTerm->leftCursor==iCur
105049          && pTerm->u.leftColumn==iColumn
105050        ){
105051          if( (pTerm->prereqRight & notReady)==0
105052           && (pTerm->eOperator & op & WO_ALL)!=0
105053          ){
105054            if( iOrigCol>=0 && pIdx && (pTerm->eOperator & WO_ISNULL)==0 ){
105055              CollSeq *pColl;
105056              char idxaff;
105057
105058              pX = pTerm->pExpr;
105059              pParse = pWC->pParse;
105060              idxaff = pIdx->pTable->aCol[iOrigCol].affinity;
105061              if( !sqlite3IndexAffinityOk(pX, idxaff) ){
105062                continue;
105063              }
105064
105065              /* Figure out the collation sequence required from an index for
105066              ** it to be useful for optimising expression pX. Store this
105067              ** value in variable pColl.
105068              */
105069              assert(pX->pLeft);
105070              pColl = sqlite3BinaryCompareCollSeq(pParse,pX->pLeft,pX->pRight);
105071              if( pColl==0 ) pColl = pParse->db->pDfltColl;
105072
105073              for(j=0; pIdx->aiColumn[j]!=iOrigCol; j++){
105074                if( NEVER(j>=pIdx->nColumn) ) return 0;
105075              }
105076              if( sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ){
105077                continue;
105078              }
105079            }
105080            if( pTerm->prereqRight==0 && (pTerm->eOperator&WO_EQ)!=0 ){
105081              pResult = pTerm;
105082              goto findTerm_success;
105083            }else if( pResult==0 ){
105084              pResult = pTerm;
105085            }
105086          }
105087          if( (pTerm->eOperator & WO_EQUIV)!=0
105088           && nEquiv<ArraySize(aEquiv)
105089          ){
105090            pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight);
105091            assert( pX->op==TK_COLUMN );
105092            for(j=0; j<nEquiv; j+=2){
105093              if( aEquiv[j]==pX->iTable && aEquiv[j+1]==pX->iColumn ) break;
105094            }
105095            if( j==nEquiv ){
105096              aEquiv[j] = pX->iTable;
105097              aEquiv[j+1] = pX->iColumn;
105098              nEquiv += 2;
105099            }
105100          }
105101        }
105102      }
105103    }
105104    if( iEquiv>=nEquiv ) break;
105105    iCur = aEquiv[iEquiv++];
105106    iColumn = aEquiv[iEquiv++];
105107  }
105108findTerm_success:
105109  return pResult;
105110}
105111
105112/* Forward reference */
105113static void exprAnalyze(SrcList*, WhereClause*, int);
105114
105115/*
105116** Call exprAnalyze on all terms in a WHERE clause.
105117**
105118**
105119*/
105120static void exprAnalyzeAll(
105121  SrcList *pTabList,       /* the FROM clause */
105122  WhereClause *pWC         /* the WHERE clause to be analyzed */
105123){
105124  int i;
105125  for(i=pWC->nTerm-1; i>=0; i--){
105126    exprAnalyze(pTabList, pWC, i);
105127  }
105128}
105129
105130#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
105131/*
105132** Check to see if the given expression is a LIKE or GLOB operator that
105133** can be optimized using inequality constraints.  Return TRUE if it is
105134** so and false if not.
105135**
105136** In order for the operator to be optimizible, the RHS must be a string
105137** literal that does not begin with a wildcard.
105138*/
105139static int isLikeOrGlob(
105140  Parse *pParse,    /* Parsing and code generating context */
105141  Expr *pExpr,      /* Test this expression */
105142  Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
105143  int *pisComplete, /* True if the only wildcard is % in the last character */
105144  int *pnoCase      /* True if uppercase is equivalent to lowercase */
105145){
105146  const char *z = 0;         /* String on RHS of LIKE operator */
105147  Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
105148  ExprList *pList;           /* List of operands to the LIKE operator */
105149  int c;                     /* One character in z[] */
105150  int cnt;                   /* Number of non-wildcard prefix characters */
105151  char wc[3];                /* Wildcard characters */
105152  sqlite3 *db = pParse->db;  /* Database connection */
105153  sqlite3_value *pVal = 0;
105154  int op;                    /* Opcode of pRight */
105155
105156  if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
105157    return 0;
105158  }
105159#ifdef SQLITE_EBCDIC
105160  if( *pnoCase ) return 0;
105161#endif
105162  pList = pExpr->x.pList;
105163  pLeft = pList->a[1].pExpr;
105164  if( pLeft->op!=TK_COLUMN
105165   || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
105166   || IsVirtual(pLeft->pTab)
105167  ){
105168    /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
105169    ** be the name of an indexed column with TEXT affinity. */
105170    return 0;
105171  }
105172  assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
105173
105174  pRight = pList->a[0].pExpr;
105175  op = pRight->op;
105176  if( op==TK_REGISTER ){
105177    op = pRight->op2;
105178  }
105179  if( op==TK_VARIABLE ){
105180    Vdbe *pReprepare = pParse->pReprepare;
105181    int iCol = pRight->iColumn;
105182    pVal = sqlite3VdbeGetValue(pReprepare, iCol, SQLITE_AFF_NONE);
105183    if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
105184      z = (char *)sqlite3_value_text(pVal);
105185    }
105186    sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
105187    assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
105188  }else if( op==TK_STRING ){
105189    z = pRight->u.zToken;
105190  }
105191  if( z ){
105192    cnt = 0;
105193    while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
105194      cnt++;
105195    }
105196    if( cnt!=0 && 255!=(u8)z[cnt-1] ){
105197      Expr *pPrefix;
105198      *pisComplete = c==wc[0] && z[cnt+1]==0;
105199      pPrefix = sqlite3Expr(db, TK_STRING, z);
105200      if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
105201      *ppPrefix = pPrefix;
105202      if( op==TK_VARIABLE ){
105203        Vdbe *v = pParse->pVdbe;
105204        sqlite3VdbeSetVarmask(v, pRight->iColumn);
105205        if( *pisComplete && pRight->u.zToken[1] ){
105206          /* If the rhs of the LIKE expression is a variable, and the current
105207          ** value of the variable means there is no need to invoke the LIKE
105208          ** function, then no OP_Variable will be added to the program.
105209          ** This causes problems for the sqlite3_bind_parameter_name()
105210          ** API. To workaround them, add a dummy OP_Variable here.
105211          */
105212          int r1 = sqlite3GetTempReg(pParse);
105213          sqlite3ExprCodeTarget(pParse, pRight, r1);
105214          sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
105215          sqlite3ReleaseTempReg(pParse, r1);
105216        }
105217      }
105218    }else{
105219      z = 0;
105220    }
105221  }
105222
105223  sqlite3ValueFree(pVal);
105224  return (z!=0);
105225}
105226#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
105227
105228
105229#ifndef SQLITE_OMIT_VIRTUALTABLE
105230/*
105231** Check to see if the given expression is of the form
105232**
105233**         column MATCH expr
105234**
105235** If it is then return TRUE.  If not, return FALSE.
105236*/
105237static int isMatchOfColumn(
105238  Expr *pExpr      /* Test this expression */
105239){
105240  ExprList *pList;
105241
105242  if( pExpr->op!=TK_FUNCTION ){
105243    return 0;
105244  }
105245  if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
105246    return 0;
105247  }
105248  pList = pExpr->x.pList;
105249  if( pList->nExpr!=2 ){
105250    return 0;
105251  }
105252  if( pList->a[1].pExpr->op != TK_COLUMN ){
105253    return 0;
105254  }
105255  return 1;
105256}
105257#endif /* SQLITE_OMIT_VIRTUALTABLE */
105258
105259/*
105260** If the pBase expression originated in the ON or USING clause of
105261** a join, then transfer the appropriate markings over to derived.
105262*/
105263static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
105264  pDerived->flags |= pBase->flags & EP_FromJoin;
105265  pDerived->iRightJoinTable = pBase->iRightJoinTable;
105266}
105267
105268#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
105269/*
105270** Analyze a term that consists of two or more OR-connected
105271** subterms.  So in:
105272**
105273**     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
105274**                          ^^^^^^^^^^^^^^^^^^^^
105275**
105276** This routine analyzes terms such as the middle term in the above example.
105277** A WhereOrTerm object is computed and attached to the term under
105278** analysis, regardless of the outcome of the analysis.  Hence:
105279**
105280**     WhereTerm.wtFlags   |=  TERM_ORINFO
105281**     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
105282**
105283** The term being analyzed must have two or more of OR-connected subterms.
105284** A single subterm might be a set of AND-connected sub-subterms.
105285** Examples of terms under analysis:
105286**
105287**     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
105288**     (B)     x=expr1 OR expr2=x OR x=expr3
105289**     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
105290**     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
105291**     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
105292**
105293** CASE 1:
105294**
105295** If all subterms are of the form T.C=expr for some single column of C and
105296** a single table T (as shown in example B above) then create a new virtual
105297** term that is an equivalent IN expression.  In other words, if the term
105298** being analyzed is:
105299**
105300**      x = expr1  OR  expr2 = x  OR  x = expr3
105301**
105302** then create a new virtual term like this:
105303**
105304**      x IN (expr1,expr2,expr3)
105305**
105306** CASE 2:
105307**
105308** If all subterms are indexable by a single table T, then set
105309**
105310**     WhereTerm.eOperator              =  WO_OR
105311**     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
105312**
105313** A subterm is "indexable" if it is of the form
105314** "T.C <op> <expr>" where C is any column of table T and
105315** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
105316** A subterm is also indexable if it is an AND of two or more
105317** subsubterms at least one of which is indexable.  Indexable AND
105318** subterms have their eOperator set to WO_AND and they have
105319** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
105320**
105321** From another point of view, "indexable" means that the subterm could
105322** potentially be used with an index if an appropriate index exists.
105323** This analysis does not consider whether or not the index exists; that
105324** is something the bestIndex() routine will determine.  This analysis
105325** only looks at whether subterms appropriate for indexing exist.
105326**
105327** All examples A through E above all satisfy case 2.  But if a term
105328** also statisfies case 1 (such as B) we know that the optimizer will
105329** always prefer case 1, so in that case we pretend that case 2 is not
105330** satisfied.
105331**
105332** It might be the case that multiple tables are indexable.  For example,
105333** (E) above is indexable on tables P, Q, and R.
105334**
105335** Terms that satisfy case 2 are candidates for lookup by using
105336** separate indices to find rowids for each subterm and composing
105337** the union of all rowids using a RowSet object.  This is similar
105338** to "bitmap indices" in other database engines.
105339**
105340** OTHERWISE:
105341**
105342** If neither case 1 nor case 2 apply, then leave the eOperator set to
105343** zero.  This term is not useful for search.
105344*/
105345static void exprAnalyzeOrTerm(
105346  SrcList *pSrc,            /* the FROM clause */
105347  WhereClause *pWC,         /* the complete WHERE clause */
105348  int idxTerm               /* Index of the OR-term to be analyzed */
105349){
105350  Parse *pParse = pWC->pParse;            /* Parser context */
105351  sqlite3 *db = pParse->db;               /* Database connection */
105352  WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
105353  Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
105354  WhereMaskSet *pMaskSet = pWC->pMaskSet; /* Table use masks */
105355  int i;                                  /* Loop counters */
105356  WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
105357  WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
105358  WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
105359  Bitmask chngToIN;         /* Tables that might satisfy case 1 */
105360  Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
105361
105362  /*
105363  ** Break the OR clause into its separate subterms.  The subterms are
105364  ** stored in a WhereClause structure containing within the WhereOrInfo
105365  ** object that is attached to the original OR clause term.
105366  */
105367  assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
105368  assert( pExpr->op==TK_OR );
105369  pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
105370  if( pOrInfo==0 ) return;
105371  pTerm->wtFlags |= TERM_ORINFO;
105372  pOrWc = &pOrInfo->wc;
105373  whereClauseInit(pOrWc, pWC->pParse, pMaskSet, pWC->wctrlFlags);
105374  whereSplit(pOrWc, pExpr, TK_OR);
105375  exprAnalyzeAll(pSrc, pOrWc);
105376  if( db->mallocFailed ) return;
105377  assert( pOrWc->nTerm>=2 );
105378
105379  /*
105380  ** Compute the set of tables that might satisfy cases 1 or 2.
105381  */
105382  indexable = ~(Bitmask)0;
105383  chngToIN = ~(Bitmask)0;
105384  for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
105385    if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
105386      WhereAndInfo *pAndInfo;
105387      assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
105388      chngToIN = 0;
105389      pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
105390      if( pAndInfo ){
105391        WhereClause *pAndWC;
105392        WhereTerm *pAndTerm;
105393        int j;
105394        Bitmask b = 0;
105395        pOrTerm->u.pAndInfo = pAndInfo;
105396        pOrTerm->wtFlags |= TERM_ANDINFO;
105397        pOrTerm->eOperator = WO_AND;
105398        pAndWC = &pAndInfo->wc;
105399        whereClauseInit(pAndWC, pWC->pParse, pMaskSet, pWC->wctrlFlags);
105400        whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
105401        exprAnalyzeAll(pSrc, pAndWC);
105402        pAndWC->pOuter = pWC;
105403        testcase( db->mallocFailed );
105404        if( !db->mallocFailed ){
105405          for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
105406            assert( pAndTerm->pExpr );
105407            if( allowedOp(pAndTerm->pExpr->op) ){
105408              b |= getMask(pMaskSet, pAndTerm->leftCursor);
105409            }
105410          }
105411        }
105412        indexable &= b;
105413      }
105414    }else if( pOrTerm->wtFlags & TERM_COPIED ){
105415      /* Skip this term for now.  We revisit it when we process the
105416      ** corresponding TERM_VIRTUAL term */
105417    }else{
105418      Bitmask b;
105419      b = getMask(pMaskSet, pOrTerm->leftCursor);
105420      if( pOrTerm->wtFlags & TERM_VIRTUAL ){
105421        WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
105422        b |= getMask(pMaskSet, pOther->leftCursor);
105423      }
105424      indexable &= b;
105425      if( (pOrTerm->eOperator & WO_EQ)==0 ){
105426        chngToIN = 0;
105427      }else{
105428        chngToIN &= b;
105429      }
105430    }
105431  }
105432
105433  /*
105434  ** Record the set of tables that satisfy case 2.  The set might be
105435  ** empty.
105436  */
105437  pOrInfo->indexable = indexable;
105438  pTerm->eOperator = indexable==0 ? 0 : WO_OR;
105439
105440  /*
105441  ** chngToIN holds a set of tables that *might* satisfy case 1.  But
105442  ** we have to do some additional checking to see if case 1 really
105443  ** is satisfied.
105444  **
105445  ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
105446  ** that there is no possibility of transforming the OR clause into an
105447  ** IN operator because one or more terms in the OR clause contain
105448  ** something other than == on a column in the single table.  The 1-bit
105449  ** case means that every term of the OR clause is of the form
105450  ** "table.column=expr" for some single table.  The one bit that is set
105451  ** will correspond to the common table.  We still need to check to make
105452  ** sure the same column is used on all terms.  The 2-bit case is when
105453  ** the all terms are of the form "table1.column=table2.column".  It
105454  ** might be possible to form an IN operator with either table1.column
105455  ** or table2.column as the LHS if either is common to every term of
105456  ** the OR clause.
105457  **
105458  ** Note that terms of the form "table.column1=table.column2" (the
105459  ** same table on both sizes of the ==) cannot be optimized.
105460  */
105461  if( chngToIN ){
105462    int okToChngToIN = 0;     /* True if the conversion to IN is valid */
105463    int iColumn = -1;         /* Column index on lhs of IN operator */
105464    int iCursor = -1;         /* Table cursor common to all terms */
105465    int j = 0;                /* Loop counter */
105466
105467    /* Search for a table and column that appears on one side or the
105468    ** other of the == operator in every subterm.  That table and column
105469    ** will be recorded in iCursor and iColumn.  There might not be any
105470    ** such table and column.  Set okToChngToIN if an appropriate table
105471    ** and column is found but leave okToChngToIN false if not found.
105472    */
105473    for(j=0; j<2 && !okToChngToIN; j++){
105474      pOrTerm = pOrWc->a;
105475      for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
105476        assert( pOrTerm->eOperator & WO_EQ );
105477        pOrTerm->wtFlags &= ~TERM_OR_OK;
105478        if( pOrTerm->leftCursor==iCursor ){
105479          /* This is the 2-bit case and we are on the second iteration and
105480          ** current term is from the first iteration.  So skip this term. */
105481          assert( j==1 );
105482          continue;
105483        }
105484        if( (chngToIN & getMask(pMaskSet, pOrTerm->leftCursor))==0 ){
105485          /* This term must be of the form t1.a==t2.b where t2 is in the
105486          ** chngToIN set but t1 is not.  This term will be either preceeded
105487          ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term
105488          ** and use its inversion. */
105489          testcase( pOrTerm->wtFlags & TERM_COPIED );
105490          testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
105491          assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
105492          continue;
105493        }
105494        iColumn = pOrTerm->u.leftColumn;
105495        iCursor = pOrTerm->leftCursor;
105496        break;
105497      }
105498      if( i<0 ){
105499        /* No candidate table+column was found.  This can only occur
105500        ** on the second iteration */
105501        assert( j==1 );
105502        assert( IsPowerOfTwo(chngToIN) );
105503        assert( chngToIN==getMask(pMaskSet, iCursor) );
105504        break;
105505      }
105506      testcase( j==1 );
105507
105508      /* We have found a candidate table and column.  Check to see if that
105509      ** table and column is common to every term in the OR clause */
105510      okToChngToIN = 1;
105511      for(; i>=0 && okToChngToIN; i--, pOrTerm++){
105512        assert( pOrTerm->eOperator & WO_EQ );
105513        if( pOrTerm->leftCursor!=iCursor ){
105514          pOrTerm->wtFlags &= ~TERM_OR_OK;
105515        }else if( pOrTerm->u.leftColumn!=iColumn ){
105516          okToChngToIN = 0;
105517        }else{
105518          int affLeft, affRight;
105519          /* If the right-hand side is also a column, then the affinities
105520          ** of both right and left sides must be such that no type
105521          ** conversions are required on the right.  (Ticket #2249)
105522          */
105523          affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
105524          affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
105525          if( affRight!=0 && affRight!=affLeft ){
105526            okToChngToIN = 0;
105527          }else{
105528            pOrTerm->wtFlags |= TERM_OR_OK;
105529          }
105530        }
105531      }
105532    }
105533
105534    /* At this point, okToChngToIN is true if original pTerm satisfies
105535    ** case 1.  In that case, construct a new virtual term that is
105536    ** pTerm converted into an IN operator.
105537    **
105538    ** EV: R-00211-15100
105539    */
105540    if( okToChngToIN ){
105541      Expr *pDup;            /* A transient duplicate expression */
105542      ExprList *pList = 0;   /* The RHS of the IN operator */
105543      Expr *pLeft = 0;       /* The LHS of the IN operator */
105544      Expr *pNew;            /* The complete IN operator */
105545
105546      for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
105547        if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
105548        assert( pOrTerm->eOperator & WO_EQ );
105549        assert( pOrTerm->leftCursor==iCursor );
105550        assert( pOrTerm->u.leftColumn==iColumn );
105551        pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
105552        pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup);
105553        pLeft = pOrTerm->pExpr->pLeft;
105554      }
105555      assert( pLeft!=0 );
105556      pDup = sqlite3ExprDup(db, pLeft, 0);
105557      pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
105558      if( pNew ){
105559        int idxNew;
105560        transferJoinMarkings(pNew, pExpr);
105561        assert( !ExprHasProperty(pNew, EP_xIsSelect) );
105562        pNew->x.pList = pList;
105563        idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
105564        testcase( idxNew==0 );
105565        exprAnalyze(pSrc, pWC, idxNew);
105566        pTerm = &pWC->a[idxTerm];
105567        pWC->a[idxNew].iParent = idxTerm;
105568        pTerm->nChild = 1;
105569      }else{
105570        sqlite3ExprListDelete(db, pList);
105571      }
105572      pTerm->eOperator = WO_NOOP;  /* case 1 trumps case 2 */
105573    }
105574  }
105575}
105576#endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
105577
105578/*
105579** The input to this routine is an WhereTerm structure with only the
105580** "pExpr" field filled in.  The job of this routine is to analyze the
105581** subexpression and populate all the other fields of the WhereTerm
105582** structure.
105583**
105584** If the expression is of the form "<expr> <op> X" it gets commuted
105585** to the standard form of "X <op> <expr>".
105586**
105587** If the expression is of the form "X <op> Y" where both X and Y are
105588** columns, then the original expression is unchanged and a new virtual
105589** term of the form "Y <op> X" is added to the WHERE clause and
105590** analyzed separately.  The original term is marked with TERM_COPIED
105591** and the new term is marked with TERM_DYNAMIC (because it's pExpr
105592** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
105593** is a commuted copy of a prior term.)  The original term has nChild=1
105594** and the copy has idxParent set to the index of the original term.
105595*/
105596static void exprAnalyze(
105597  SrcList *pSrc,            /* the FROM clause */
105598  WhereClause *pWC,         /* the WHERE clause */
105599  int idxTerm               /* Index of the term to be analyzed */
105600){
105601  WhereTerm *pTerm;                /* The term to be analyzed */
105602  WhereMaskSet *pMaskSet;          /* Set of table index masks */
105603  Expr *pExpr;                     /* The expression to be analyzed */
105604  Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
105605  Bitmask prereqAll;               /* Prerequesites of pExpr */
105606  Bitmask extraRight = 0;          /* Extra dependencies on LEFT JOIN */
105607  Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
105608  int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
105609  int noCase = 0;                  /* LIKE/GLOB distinguishes case */
105610  int op;                          /* Top-level operator.  pExpr->op */
105611  Parse *pParse = pWC->pParse;     /* Parsing context */
105612  sqlite3 *db = pParse->db;        /* Database connection */
105613
105614  if( db->mallocFailed ){
105615    return;
105616  }
105617  pTerm = &pWC->a[idxTerm];
105618  pMaskSet = pWC->pMaskSet;
105619  pExpr = pTerm->pExpr;
105620  assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
105621  prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
105622  op = pExpr->op;
105623  if( op==TK_IN ){
105624    assert( pExpr->pRight==0 );
105625    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
105626      pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
105627    }else{
105628      pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
105629    }
105630  }else if( op==TK_ISNULL ){
105631    pTerm->prereqRight = 0;
105632  }else{
105633    pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
105634  }
105635  prereqAll = exprTableUsage(pMaskSet, pExpr);
105636  if( ExprHasProperty(pExpr, EP_FromJoin) ){
105637    Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
105638    prereqAll |= x;
105639    extraRight = x-1;  /* ON clause terms may not be used with an index
105640                       ** on left table of a LEFT JOIN.  Ticket #3015 */
105641  }
105642  pTerm->prereqAll = prereqAll;
105643  pTerm->leftCursor = -1;
105644  pTerm->iParent = -1;
105645  pTerm->eOperator = 0;
105646  if( allowedOp(op) ){
105647    Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
105648    Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
105649    u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
105650    if( pLeft->op==TK_COLUMN ){
105651      pTerm->leftCursor = pLeft->iTable;
105652      pTerm->u.leftColumn = pLeft->iColumn;
105653      pTerm->eOperator = operatorMask(op) & opMask;
105654    }
105655    if( pRight && pRight->op==TK_COLUMN ){
105656      WhereTerm *pNew;
105657      Expr *pDup;
105658      u16 eExtraOp = 0;        /* Extra bits for pNew->eOperator */
105659      if( pTerm->leftCursor>=0 ){
105660        int idxNew;
105661        pDup = sqlite3ExprDup(db, pExpr, 0);
105662        if( db->mallocFailed ){
105663          sqlite3ExprDelete(db, pDup);
105664          return;
105665        }
105666        idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
105667        if( idxNew==0 ) return;
105668        pNew = &pWC->a[idxNew];
105669        pNew->iParent = idxTerm;
105670        pTerm = &pWC->a[idxTerm];
105671        pTerm->nChild = 1;
105672        pTerm->wtFlags |= TERM_COPIED;
105673        if( pExpr->op==TK_EQ
105674         && !ExprHasProperty(pExpr, EP_FromJoin)
105675         && OptimizationEnabled(db, SQLITE_Transitive)
105676        ){
105677          pTerm->eOperator |= WO_EQUIV;
105678          eExtraOp = WO_EQUIV;
105679        }
105680      }else{
105681        pDup = pExpr;
105682        pNew = pTerm;
105683      }
105684      exprCommute(pParse, pDup);
105685      pLeft = sqlite3ExprSkipCollate(pDup->pLeft);
105686      pNew->leftCursor = pLeft->iTable;
105687      pNew->u.leftColumn = pLeft->iColumn;
105688      testcase( (prereqLeft | extraRight) != prereqLeft );
105689      pNew->prereqRight = prereqLeft | extraRight;
105690      pNew->prereqAll = prereqAll;
105691      pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
105692    }
105693  }
105694
105695#ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
105696  /* If a term is the BETWEEN operator, create two new virtual terms
105697  ** that define the range that the BETWEEN implements.  For example:
105698  **
105699  **      a BETWEEN b AND c
105700  **
105701  ** is converted into:
105702  **
105703  **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
105704  **
105705  ** The two new terms are added onto the end of the WhereClause object.
105706  ** The new terms are "dynamic" and are children of the original BETWEEN
105707  ** term.  That means that if the BETWEEN term is coded, the children are
105708  ** skipped.  Or, if the children are satisfied by an index, the original
105709  ** BETWEEN term is skipped.
105710  */
105711  else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
105712    ExprList *pList = pExpr->x.pList;
105713    int i;
105714    static const u8 ops[] = {TK_GE, TK_LE};
105715    assert( pList!=0 );
105716    assert( pList->nExpr==2 );
105717    for(i=0; i<2; i++){
105718      Expr *pNewExpr;
105719      int idxNew;
105720      pNewExpr = sqlite3PExpr(pParse, ops[i],
105721                             sqlite3ExprDup(db, pExpr->pLeft, 0),
105722                             sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
105723      idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
105724      testcase( idxNew==0 );
105725      exprAnalyze(pSrc, pWC, idxNew);
105726      pTerm = &pWC->a[idxTerm];
105727      pWC->a[idxNew].iParent = idxTerm;
105728    }
105729    pTerm->nChild = 2;
105730  }
105731#endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
105732
105733#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
105734  /* Analyze a term that is composed of two or more subterms connected by
105735  ** an OR operator.
105736  */
105737  else if( pExpr->op==TK_OR ){
105738    assert( pWC->op==TK_AND );
105739    exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
105740    pTerm = &pWC->a[idxTerm];
105741  }
105742#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
105743
105744#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
105745  /* Add constraints to reduce the search space on a LIKE or GLOB
105746  ** operator.
105747  **
105748  ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
105749  **
105750  **          x>='abc' AND x<'abd' AND x LIKE 'abc%'
105751  **
105752  ** The last character of the prefix "abc" is incremented to form the
105753  ** termination condition "abd".
105754  */
105755  if( pWC->op==TK_AND
105756   && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
105757  ){
105758    Expr *pLeft;       /* LHS of LIKE/GLOB operator */
105759    Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
105760    Expr *pNewExpr1;
105761    Expr *pNewExpr2;
105762    int idxNew1;
105763    int idxNew2;
105764    Token sCollSeqName;  /* Name of collating sequence */
105765
105766    pLeft = pExpr->x.pList->a[1].pExpr;
105767    pStr2 = sqlite3ExprDup(db, pStr1, 0);
105768    if( !db->mallocFailed ){
105769      u8 c, *pC;       /* Last character before the first wildcard */
105770      pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
105771      c = *pC;
105772      if( noCase ){
105773        /* The point is to increment the last character before the first
105774        ** wildcard.  But if we increment '@', that will push it into the
105775        ** alphabetic range where case conversions will mess up the
105776        ** inequality.  To avoid this, make sure to also run the full
105777        ** LIKE on all candidate expressions by clearing the isComplete flag
105778        */
105779        if( c=='A'-1 ) isComplete = 0;   /* EV: R-64339-08207 */
105780
105781
105782        c = sqlite3UpperToLower[c];
105783      }
105784      *pC = c + 1;
105785    }
105786    sCollSeqName.z = noCase ? "NOCASE" : "BINARY";
105787    sCollSeqName.n = 6;
105788    pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
105789    pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
105790           sqlite3ExprAddCollateToken(pParse,pNewExpr1,&sCollSeqName),
105791           pStr1, 0);
105792    idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
105793    testcase( idxNew1==0 );
105794    exprAnalyze(pSrc, pWC, idxNew1);
105795    pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
105796    pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
105797           sqlite3ExprAddCollateToken(pParse,pNewExpr2,&sCollSeqName),
105798           pStr2, 0);
105799    idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
105800    testcase( idxNew2==0 );
105801    exprAnalyze(pSrc, pWC, idxNew2);
105802    pTerm = &pWC->a[idxTerm];
105803    if( isComplete ){
105804      pWC->a[idxNew1].iParent = idxTerm;
105805      pWC->a[idxNew2].iParent = idxTerm;
105806      pTerm->nChild = 2;
105807    }
105808  }
105809#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
105810
105811#ifndef SQLITE_OMIT_VIRTUALTABLE
105812  /* Add a WO_MATCH auxiliary term to the constraint set if the
105813  ** current expression is of the form:  column MATCH expr.
105814  ** This information is used by the xBestIndex methods of
105815  ** virtual tables.  The native query optimizer does not attempt
105816  ** to do anything with MATCH functions.
105817  */
105818  if( isMatchOfColumn(pExpr) ){
105819    int idxNew;
105820    Expr *pRight, *pLeft;
105821    WhereTerm *pNewTerm;
105822    Bitmask prereqColumn, prereqExpr;
105823
105824    pRight = pExpr->x.pList->a[0].pExpr;
105825    pLeft = pExpr->x.pList->a[1].pExpr;
105826    prereqExpr = exprTableUsage(pMaskSet, pRight);
105827    prereqColumn = exprTableUsage(pMaskSet, pLeft);
105828    if( (prereqExpr & prereqColumn)==0 ){
105829      Expr *pNewExpr;
105830      pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
105831                              0, sqlite3ExprDup(db, pRight, 0), 0);
105832      idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
105833      testcase( idxNew==0 );
105834      pNewTerm = &pWC->a[idxNew];
105835      pNewTerm->prereqRight = prereqExpr;
105836      pNewTerm->leftCursor = pLeft->iTable;
105837      pNewTerm->u.leftColumn = pLeft->iColumn;
105838      pNewTerm->eOperator = WO_MATCH;
105839      pNewTerm->iParent = idxTerm;
105840      pTerm = &pWC->a[idxTerm];
105841      pTerm->nChild = 1;
105842      pTerm->wtFlags |= TERM_COPIED;
105843      pNewTerm->prereqAll = pTerm->prereqAll;
105844    }
105845  }
105846#endif /* SQLITE_OMIT_VIRTUALTABLE */
105847
105848#ifdef SQLITE_ENABLE_STAT3
105849  /* When sqlite_stat3 histogram data is available an operator of the
105850  ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
105851  ** as "x>NULL" if x is not an INTEGER PRIMARY KEY.  So construct a
105852  ** virtual term of that form.
105853  **
105854  ** Note that the virtual term must be tagged with TERM_VNULL.  This
105855  ** TERM_VNULL tag will suppress the not-null check at the beginning
105856  ** of the loop.  Without the TERM_VNULL flag, the not-null check at
105857  ** the start of the loop will prevent any results from being returned.
105858  */
105859  if( pExpr->op==TK_NOTNULL
105860   && pExpr->pLeft->op==TK_COLUMN
105861   && pExpr->pLeft->iColumn>=0
105862  ){
105863    Expr *pNewExpr;
105864    Expr *pLeft = pExpr->pLeft;
105865    int idxNew;
105866    WhereTerm *pNewTerm;
105867
105868    pNewExpr = sqlite3PExpr(pParse, TK_GT,
105869                            sqlite3ExprDup(db, pLeft, 0),
105870                            sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
105871
105872    idxNew = whereClauseInsert(pWC, pNewExpr,
105873                              TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
105874    if( idxNew ){
105875      pNewTerm = &pWC->a[idxNew];
105876      pNewTerm->prereqRight = 0;
105877      pNewTerm->leftCursor = pLeft->iTable;
105878      pNewTerm->u.leftColumn = pLeft->iColumn;
105879      pNewTerm->eOperator = WO_GT;
105880      pNewTerm->iParent = idxTerm;
105881      pTerm = &pWC->a[idxTerm];
105882      pTerm->nChild = 1;
105883      pTerm->wtFlags |= TERM_COPIED;
105884      pNewTerm->prereqAll = pTerm->prereqAll;
105885    }
105886  }
105887#endif /* SQLITE_ENABLE_STAT */
105888
105889  /* Prevent ON clause terms of a LEFT JOIN from being used to drive
105890  ** an index for tables to the left of the join.
105891  */
105892  pTerm->prereqRight |= extraRight;
105893}
105894
105895/*
105896** This function searches the expression list passed as the second argument
105897** for an expression of type TK_COLUMN that refers to the same column and
105898** uses the same collation sequence as the iCol'th column of index pIdx.
105899** Argument iBase is the cursor number used for the table that pIdx refers
105900** to.
105901**
105902** If such an expression is found, its index in pList->a[] is returned. If
105903** no expression is found, -1 is returned.
105904*/
105905static int findIndexCol(
105906  Parse *pParse,                  /* Parse context */
105907  ExprList *pList,                /* Expression list to search */
105908  int iBase,                      /* Cursor for table associated with pIdx */
105909  Index *pIdx,                    /* Index to match column of */
105910  int iCol                        /* Column of index to match */
105911){
105912  int i;
105913  const char *zColl = pIdx->azColl[iCol];
105914
105915  for(i=0; i<pList->nExpr; i++){
105916    Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
105917    if( p->op==TK_COLUMN
105918     && p->iColumn==pIdx->aiColumn[iCol]
105919     && p->iTable==iBase
105920    ){
105921      CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
105922      if( ALWAYS(pColl) && 0==sqlite3StrICmp(pColl->zName, zColl) ){
105923        return i;
105924      }
105925    }
105926  }
105927
105928  return -1;
105929}
105930
105931/*
105932** This routine determines if pIdx can be used to assist in processing a
105933** DISTINCT qualifier. In other words, it tests whether or not using this
105934** index for the outer loop guarantees that rows with equal values for
105935** all expressions in the pDistinct list are delivered grouped together.
105936**
105937** For example, the query
105938**
105939**   SELECT DISTINCT a, b, c FROM tbl WHERE a = ?
105940**
105941** can benefit from any index on columns "b" and "c".
105942*/
105943static int isDistinctIndex(
105944  Parse *pParse,                  /* Parsing context */
105945  WhereClause *pWC,               /* The WHERE clause */
105946  Index *pIdx,                    /* The index being considered */
105947  int base,                       /* Cursor number for the table pIdx is on */
105948  ExprList *pDistinct,            /* The DISTINCT expressions */
105949  int nEqCol                      /* Number of index columns with == */
105950){
105951  Bitmask mask = 0;               /* Mask of unaccounted for pDistinct exprs */
105952  int i;                          /* Iterator variable */
105953
105954  assert( pDistinct!=0 );
105955  if( pIdx->zName==0 || pDistinct->nExpr>=BMS ) return 0;
105956  testcase( pDistinct->nExpr==BMS-1 );
105957
105958  /* Loop through all the expressions in the distinct list. If any of them
105959  ** are not simple column references, return early. Otherwise, test if the
105960  ** WHERE clause contains a "col=X" clause. If it does, the expression
105961  ** can be ignored. If it does not, and the column does not belong to the
105962  ** same table as index pIdx, return early. Finally, if there is no
105963  ** matching "col=X" expression and the column is on the same table as pIdx,
105964  ** set the corresponding bit in variable mask.
105965  */
105966  for(i=0; i<pDistinct->nExpr; i++){
105967    WhereTerm *pTerm;
105968    Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
105969    if( p->op!=TK_COLUMN ) return 0;
105970    pTerm = findTerm(pWC, p->iTable, p->iColumn, ~(Bitmask)0, WO_EQ, 0);
105971    if( pTerm ){
105972      Expr *pX = pTerm->pExpr;
105973      CollSeq *p1 = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
105974      CollSeq *p2 = sqlite3ExprCollSeq(pParse, p);
105975      if( p1==p2 ) continue;
105976    }
105977    if( p->iTable!=base ) return 0;
105978    mask |= (((Bitmask)1) << i);
105979  }
105980
105981  for(i=nEqCol; mask && i<pIdx->nColumn; i++){
105982    int iExpr = findIndexCol(pParse, pDistinct, base, pIdx, i);
105983    if( iExpr<0 ) break;
105984    mask &= ~(((Bitmask)1) << iExpr);
105985  }
105986
105987  return (mask==0);
105988}
105989
105990
105991/*
105992** Return true if the DISTINCT expression-list passed as the third argument
105993** is redundant. A DISTINCT list is redundant if the database contains a
105994** UNIQUE index that guarantees that the result of the query will be distinct
105995** anyway.
105996*/
105997static int isDistinctRedundant(
105998  Parse *pParse,
105999  SrcList *pTabList,
106000  WhereClause *pWC,
106001  ExprList *pDistinct
106002){
106003  Table *pTab;
106004  Index *pIdx;
106005  int i;
106006  int iBase;
106007
106008  /* If there is more than one table or sub-select in the FROM clause of
106009  ** this query, then it will not be possible to show that the DISTINCT
106010  ** clause is redundant. */
106011  if( pTabList->nSrc!=1 ) return 0;
106012  iBase = pTabList->a[0].iCursor;
106013  pTab = pTabList->a[0].pTab;
106014
106015  /* If any of the expressions is an IPK column on table iBase, then return
106016  ** true. Note: The (p->iTable==iBase) part of this test may be false if the
106017  ** current SELECT is a correlated sub-query.
106018  */
106019  for(i=0; i<pDistinct->nExpr; i++){
106020    Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
106021    if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
106022  }
106023
106024  /* Loop through all indices on the table, checking each to see if it makes
106025  ** the DISTINCT qualifier redundant. It does so if:
106026  **
106027  **   1. The index is itself UNIQUE, and
106028  **
106029  **   2. All of the columns in the index are either part of the pDistinct
106030  **      list, or else the WHERE clause contains a term of the form "col=X",
106031  **      where X is a constant value. The collation sequences of the
106032  **      comparison and select-list expressions must match those of the index.
106033  **
106034  **   3. All of those index columns for which the WHERE clause does not
106035  **      contain a "col=X" term are subject to a NOT NULL constraint.
106036  */
106037  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
106038    if( pIdx->onError==OE_None ) continue;
106039    for(i=0; i<pIdx->nColumn; i++){
106040      int iCol = pIdx->aiColumn[i];
106041      if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) ){
106042        int iIdxCol = findIndexCol(pParse, pDistinct, iBase, pIdx, i);
106043        if( iIdxCol<0 || pTab->aCol[pIdx->aiColumn[i]].notNull==0 ){
106044          break;
106045        }
106046      }
106047    }
106048    if( i==pIdx->nColumn ){
106049      /* This index implies that the DISTINCT qualifier is redundant. */
106050      return 1;
106051    }
106052  }
106053
106054  return 0;
106055}
106056
106057/*
106058** Prepare a crude estimate of the logarithm of the input value.
106059** The results need not be exact.  This is only used for estimating
106060** the total cost of performing operations with O(logN) or O(NlogN)
106061** complexity.  Because N is just a guess, it is no great tragedy if
106062** logN is a little off.
106063*/
106064static double estLog(double N){
106065  double logN = 1;
106066  double x = 10;
106067  while( N>x ){
106068    logN += 1;
106069    x *= 10;
106070  }
106071  return logN;
106072}
106073
106074/*
106075** Two routines for printing the content of an sqlite3_index_info
106076** structure.  Used for testing and debugging only.  If neither
106077** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
106078** are no-ops.
106079*/
106080#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
106081static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
106082  int i;
106083  if( !sqlite3WhereTrace ) return;
106084  for(i=0; i<p->nConstraint; i++){
106085    sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
106086       i,
106087       p->aConstraint[i].iColumn,
106088       p->aConstraint[i].iTermOffset,
106089       p->aConstraint[i].op,
106090       p->aConstraint[i].usable);
106091  }
106092  for(i=0; i<p->nOrderBy; i++){
106093    sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
106094       i,
106095       p->aOrderBy[i].iColumn,
106096       p->aOrderBy[i].desc);
106097  }
106098}
106099static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
106100  int i;
106101  if( !sqlite3WhereTrace ) return;
106102  for(i=0; i<p->nConstraint; i++){
106103    sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
106104       i,
106105       p->aConstraintUsage[i].argvIndex,
106106       p->aConstraintUsage[i].omit);
106107  }
106108  sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
106109  sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
106110  sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
106111  sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
106112}
106113#else
106114#define TRACE_IDX_INPUTS(A)
106115#define TRACE_IDX_OUTPUTS(A)
106116#endif
106117
106118/*
106119** Required because bestIndex() is called by bestOrClauseIndex()
106120*/
106121static void bestIndex(WhereBestIdx*);
106122
106123/*
106124** This routine attempts to find an scanning strategy that can be used
106125** to optimize an 'OR' expression that is part of a WHERE clause.
106126**
106127** The table associated with FROM clause term pSrc may be either a
106128** regular B-Tree table or a virtual table.
106129*/
106130static void bestOrClauseIndex(WhereBestIdx *p){
106131#ifndef SQLITE_OMIT_OR_OPTIMIZATION
106132  WhereClause *pWC = p->pWC;           /* The WHERE clause */
106133  struct SrcList_item *pSrc = p->pSrc; /* The FROM clause term to search */
106134  const int iCur = pSrc->iCursor;      /* The cursor of the table  */
106135  const Bitmask maskSrc = getMask(pWC->pMaskSet, iCur);  /* Bitmask for pSrc */
106136  WhereTerm * const pWCEnd = &pWC->a[pWC->nTerm];        /* End of pWC->a[] */
106137  WhereTerm *pTerm;                    /* A single term of the WHERE clause */
106138
106139  /* The OR-clause optimization is disallowed if the INDEXED BY or
106140  ** NOT INDEXED clauses are used or if the WHERE_AND_ONLY bit is set. */
106141  if( pSrc->notIndexed || pSrc->pIndex!=0 ){
106142    return;
106143  }
106144  if( pWC->wctrlFlags & WHERE_AND_ONLY ){
106145    return;
106146  }
106147
106148  /* Search the WHERE clause terms for a usable WO_OR term. */
106149  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
106150    if( (pTerm->eOperator & WO_OR)!=0
106151     && ((pTerm->prereqAll & ~maskSrc) & p->notReady)==0
106152     && (pTerm->u.pOrInfo->indexable & maskSrc)!=0
106153    ){
106154      WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
106155      WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
106156      WhereTerm *pOrTerm;
106157      int flags = WHERE_MULTI_OR;
106158      double rTotal = 0;
106159      double nRow = 0;
106160      Bitmask used = 0;
106161      WhereBestIdx sBOI;
106162
106163      sBOI = *p;
106164      sBOI.pOrderBy = 0;
106165      sBOI.pDistinct = 0;
106166      sBOI.ppIdxInfo = 0;
106167      for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
106168        WHERETRACE(("... Multi-index OR testing for term %d of %d....\n",
106169          (pOrTerm - pOrWC->a), (pTerm - pWC->a)
106170        ));
106171        if( (pOrTerm->eOperator& WO_AND)!=0 ){
106172          sBOI.pWC = &pOrTerm->u.pAndInfo->wc;
106173          bestIndex(&sBOI);
106174        }else if( pOrTerm->leftCursor==iCur ){
106175          WhereClause tempWC;
106176          tempWC.pParse = pWC->pParse;
106177          tempWC.pMaskSet = pWC->pMaskSet;
106178          tempWC.pOuter = pWC;
106179          tempWC.op = TK_AND;
106180          tempWC.a = pOrTerm;
106181          tempWC.wctrlFlags = 0;
106182          tempWC.nTerm = 1;
106183          sBOI.pWC = &tempWC;
106184          bestIndex(&sBOI);
106185        }else{
106186          continue;
106187        }
106188        rTotal += sBOI.cost.rCost;
106189        nRow += sBOI.cost.plan.nRow;
106190        used |= sBOI.cost.used;
106191        if( rTotal>=p->cost.rCost ) break;
106192      }
106193
106194      /* If there is an ORDER BY clause, increase the scan cost to account
106195      ** for the cost of the sort. */
106196      if( p->pOrderBy!=0 ){
106197        WHERETRACE(("... sorting increases OR cost %.9g to %.9g\n",
106198                    rTotal, rTotal+nRow*estLog(nRow)));
106199        rTotal += nRow*estLog(nRow);
106200      }
106201
106202      /* If the cost of scanning using this OR term for optimization is
106203      ** less than the current cost stored in pCost, replace the contents
106204      ** of pCost. */
106205      WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n", rTotal, nRow));
106206      if( rTotal<p->cost.rCost ){
106207        p->cost.rCost = rTotal;
106208        p->cost.used = used;
106209        p->cost.plan.nRow = nRow;
106210        p->cost.plan.nOBSat = p->i ? p->aLevel[p->i-1].plan.nOBSat : 0;
106211        p->cost.plan.wsFlags = flags;
106212        p->cost.plan.u.pTerm = pTerm;
106213      }
106214    }
106215  }
106216#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
106217}
106218
106219#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
106220/*
106221** Return TRUE if the WHERE clause term pTerm is of a form where it
106222** could be used with an index to access pSrc, assuming an appropriate
106223** index existed.
106224*/
106225static int termCanDriveIndex(
106226  WhereTerm *pTerm,              /* WHERE clause term to check */
106227  struct SrcList_item *pSrc,     /* Table we are trying to access */
106228  Bitmask notReady               /* Tables in outer loops of the join */
106229){
106230  char aff;
106231  if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
106232  if( (pTerm->eOperator & WO_EQ)==0 ) return 0;
106233  if( (pTerm->prereqRight & notReady)!=0 ) return 0;
106234  aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
106235  if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
106236  return 1;
106237}
106238#endif
106239
106240#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
106241/*
106242** If the query plan for pSrc specified in pCost is a full table scan
106243** and indexing is allows (if there is no NOT INDEXED clause) and it
106244** possible to construct a transient index that would perform better
106245** than a full table scan even when the cost of constructing the index
106246** is taken into account, then alter the query plan to use the
106247** transient index.
106248*/
106249static void bestAutomaticIndex(WhereBestIdx *p){
106250  Parse *pParse = p->pParse;            /* The parsing context */
106251  WhereClause *pWC = p->pWC;            /* The WHERE clause */
106252  struct SrcList_item *pSrc = p->pSrc;  /* The FROM clause term to search */
106253  double nTableRow;                     /* Rows in the input table */
106254  double logN;                          /* log(nTableRow) */
106255  double costTempIdx;         /* per-query cost of the transient index */
106256  WhereTerm *pTerm;           /* A single term of the WHERE clause */
106257  WhereTerm *pWCEnd;          /* End of pWC->a[] */
106258  Table *pTable;              /* Table tht might be indexed */
106259
106260  if( pParse->nQueryLoop<=(double)1 ){
106261    /* There is no point in building an automatic index for a single scan */
106262    return;
106263  }
106264  if( (pParse->db->flags & SQLITE_AutoIndex)==0 ){
106265    /* Automatic indices are disabled at run-time */
106266    return;
106267  }
106268  if( (p->cost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0
106269   && (p->cost.plan.wsFlags & WHERE_COVER_SCAN)==0
106270  ){
106271    /* We already have some kind of index in use for this query. */
106272    return;
106273  }
106274  if( pSrc->viaCoroutine ){
106275    /* Cannot index a co-routine */
106276    return;
106277  }
106278  if( pSrc->notIndexed ){
106279    /* The NOT INDEXED clause appears in the SQL. */
106280    return;
106281  }
106282  if( pSrc->isCorrelated ){
106283    /* The source is a correlated sub-query. No point in indexing it. */
106284    return;
106285  }
106286
106287  assert( pParse->nQueryLoop >= (double)1 );
106288  pTable = pSrc->pTab;
106289  nTableRow = pTable->nRowEst;
106290  logN = estLog(nTableRow);
106291  costTempIdx = 2*logN*(nTableRow/pParse->nQueryLoop + 1);
106292  if( costTempIdx>=p->cost.rCost ){
106293    /* The cost of creating the transient table would be greater than
106294    ** doing the full table scan */
106295    return;
106296  }
106297
106298  /* Search for any equality comparison term */
106299  pWCEnd = &pWC->a[pWC->nTerm];
106300  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
106301    if( termCanDriveIndex(pTerm, pSrc, p->notReady) ){
106302      WHERETRACE(("auto-index reduces cost from %.1f to %.1f\n",
106303                    p->cost.rCost, costTempIdx));
106304      p->cost.rCost = costTempIdx;
106305      p->cost.plan.nRow = logN + 1;
106306      p->cost.plan.wsFlags = WHERE_TEMP_INDEX;
106307      p->cost.used = pTerm->prereqRight;
106308      break;
106309    }
106310  }
106311}
106312#else
106313# define bestAutomaticIndex(A)  /* no-op */
106314#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
106315
106316
106317#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
106318/*
106319** Generate code to construct the Index object for an automatic index
106320** and to set up the WhereLevel object pLevel so that the code generator
106321** makes use of the automatic index.
106322*/
106323static void constructAutomaticIndex(
106324  Parse *pParse,              /* The parsing context */
106325  WhereClause *pWC,           /* The WHERE clause */
106326  struct SrcList_item *pSrc,  /* The FROM clause term to get the next index */
106327  Bitmask notReady,           /* Mask of cursors that are not available */
106328  WhereLevel *pLevel          /* Write new index here */
106329){
106330  int nColumn;                /* Number of columns in the constructed index */
106331  WhereTerm *pTerm;           /* A single term of the WHERE clause */
106332  WhereTerm *pWCEnd;          /* End of pWC->a[] */
106333  int nByte;                  /* Byte of memory needed for pIdx */
106334  Index *pIdx;                /* Object describing the transient index */
106335  Vdbe *v;                    /* Prepared statement under construction */
106336  int addrInit;               /* Address of the initialization bypass jump */
106337  Table *pTable;              /* The table being indexed */
106338  KeyInfo *pKeyinfo;          /* Key information for the index */
106339  int addrTop;                /* Top of the index fill loop */
106340  int regRecord;              /* Register holding an index record */
106341  int n;                      /* Column counter */
106342  int i;                      /* Loop counter */
106343  int mxBitCol;               /* Maximum column in pSrc->colUsed */
106344  CollSeq *pColl;             /* Collating sequence to on a column */
106345  Bitmask idxCols;            /* Bitmap of columns used for indexing */
106346  Bitmask extraCols;          /* Bitmap of additional columns */
106347
106348  /* Generate code to skip over the creation and initialization of the
106349  ** transient index on 2nd and subsequent iterations of the loop. */
106350  v = pParse->pVdbe;
106351  assert( v!=0 );
106352  addrInit = sqlite3CodeOnce(pParse);
106353
106354  /* Count the number of columns that will be added to the index
106355  ** and used to match WHERE clause constraints */
106356  nColumn = 0;
106357  pTable = pSrc->pTab;
106358  pWCEnd = &pWC->a[pWC->nTerm];
106359  idxCols = 0;
106360  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
106361    if( termCanDriveIndex(pTerm, pSrc, notReady) ){
106362      int iCol = pTerm->u.leftColumn;
106363      Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
106364      testcase( iCol==BMS );
106365      testcase( iCol==BMS-1 );
106366      if( (idxCols & cMask)==0 ){
106367        nColumn++;
106368        idxCols |= cMask;
106369      }
106370    }
106371  }
106372  assert( nColumn>0 );
106373  pLevel->plan.nEq = nColumn;
106374
106375  /* Count the number of additional columns needed to create a
106376  ** covering index.  A "covering index" is an index that contains all
106377  ** columns that are needed by the query.  With a covering index, the
106378  ** original table never needs to be accessed.  Automatic indices must
106379  ** be a covering index because the index will not be updated if the
106380  ** original table changes and the index and table cannot both be used
106381  ** if they go out of sync.
106382  */
106383  extraCols = pSrc->colUsed & (~idxCols | (((Bitmask)1)<<(BMS-1)));
106384  mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
106385  testcase( pTable->nCol==BMS-1 );
106386  testcase( pTable->nCol==BMS-2 );
106387  for(i=0; i<mxBitCol; i++){
106388    if( extraCols & (((Bitmask)1)<<i) ) nColumn++;
106389  }
106390  if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
106391    nColumn += pTable->nCol - BMS + 1;
106392  }
106393  pLevel->plan.wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WO_EQ;
106394
106395  /* Construct the Index object to describe this index */
106396  nByte = sizeof(Index);
106397  nByte += nColumn*sizeof(int);     /* Index.aiColumn */
106398  nByte += nColumn*sizeof(char*);   /* Index.azColl */
106399  nByte += nColumn;                 /* Index.aSortOrder */
106400  pIdx = sqlite3DbMallocZero(pParse->db, nByte);
106401  if( pIdx==0 ) return;
106402  pLevel->plan.u.pIdx = pIdx;
106403  pIdx->azColl = (char**)&pIdx[1];
106404  pIdx->aiColumn = (int*)&pIdx->azColl[nColumn];
106405  pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn];
106406  pIdx->zName = "auto-index";
106407  pIdx->nColumn = nColumn;
106408  pIdx->pTable = pTable;
106409  n = 0;
106410  idxCols = 0;
106411  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
106412    if( termCanDriveIndex(pTerm, pSrc, notReady) ){
106413      int iCol = pTerm->u.leftColumn;
106414      Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
106415      if( (idxCols & cMask)==0 ){
106416        Expr *pX = pTerm->pExpr;
106417        idxCols |= cMask;
106418        pIdx->aiColumn[n] = pTerm->u.leftColumn;
106419        pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
106420        pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
106421        n++;
106422      }
106423    }
106424  }
106425  assert( (u32)n==pLevel->plan.nEq );
106426
106427  /* Add additional columns needed to make the automatic index into
106428  ** a covering index */
106429  for(i=0; i<mxBitCol; i++){
106430    if( extraCols & (((Bitmask)1)<<i) ){
106431      pIdx->aiColumn[n] = i;
106432      pIdx->azColl[n] = "BINARY";
106433      n++;
106434    }
106435  }
106436  if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
106437    for(i=BMS-1; i<pTable->nCol; i++){
106438      pIdx->aiColumn[n] = i;
106439      pIdx->azColl[n] = "BINARY";
106440      n++;
106441    }
106442  }
106443  assert( n==nColumn );
106444
106445  /* Create the automatic index */
106446  pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx);
106447  assert( pLevel->iIdxCur>=0 );
106448  sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,
106449                    (char*)pKeyinfo, P4_KEYINFO_HANDOFF);
106450  VdbeComment((v, "for %s", pTable->zName));
106451
106452  /* Fill the automatic index with content */
106453  addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);
106454  regRecord = sqlite3GetTempReg(pParse);
106455  sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1);
106456  sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
106457  sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
106458  sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
106459  sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
106460  sqlite3VdbeJumpHere(v, addrTop);
106461  sqlite3ReleaseTempReg(pParse, regRecord);
106462
106463  /* Jump here when skipping the initialization */
106464  sqlite3VdbeJumpHere(v, addrInit);
106465}
106466#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
106467
106468#ifndef SQLITE_OMIT_VIRTUALTABLE
106469/*
106470** Allocate and populate an sqlite3_index_info structure. It is the
106471** responsibility of the caller to eventually release the structure
106472** by passing the pointer returned by this function to sqlite3_free().
106473*/
106474static sqlite3_index_info *allocateIndexInfo(WhereBestIdx *p){
106475  Parse *pParse = p->pParse;
106476  WhereClause *pWC = p->pWC;
106477  struct SrcList_item *pSrc = p->pSrc;
106478  ExprList *pOrderBy = p->pOrderBy;
106479  int i, j;
106480  int nTerm;
106481  struct sqlite3_index_constraint *pIdxCons;
106482  struct sqlite3_index_orderby *pIdxOrderBy;
106483  struct sqlite3_index_constraint_usage *pUsage;
106484  WhereTerm *pTerm;
106485  int nOrderBy;
106486  sqlite3_index_info *pIdxInfo;
106487
106488  WHERETRACE(("Recomputing index info for %s...\n", pSrc->pTab->zName));
106489
106490  /* Count the number of possible WHERE clause constraints referring
106491  ** to this virtual table */
106492  for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
106493    if( pTerm->leftCursor != pSrc->iCursor ) continue;
106494    assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
106495    testcase( pTerm->eOperator & WO_IN );
106496    testcase( pTerm->eOperator & WO_ISNULL );
106497    if( pTerm->eOperator & (WO_ISNULL) ) continue;
106498    if( pTerm->wtFlags & TERM_VNULL ) continue;
106499    nTerm++;
106500  }
106501
106502  /* If the ORDER BY clause contains only columns in the current
106503  ** virtual table then allocate space for the aOrderBy part of
106504  ** the sqlite3_index_info structure.
106505  */
106506  nOrderBy = 0;
106507  if( pOrderBy ){
106508    int n = pOrderBy->nExpr;
106509    for(i=0; i<n; i++){
106510      Expr *pExpr = pOrderBy->a[i].pExpr;
106511      if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
106512    }
106513    if( i==n){
106514      nOrderBy = n;
106515    }
106516  }
106517
106518  /* Allocate the sqlite3_index_info structure
106519  */
106520  pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
106521                           + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
106522                           + sizeof(*pIdxOrderBy)*nOrderBy );
106523  if( pIdxInfo==0 ){
106524    sqlite3ErrorMsg(pParse, "out of memory");
106525    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
106526    return 0;
106527  }
106528
106529  /* Initialize the structure.  The sqlite3_index_info structure contains
106530  ** many fields that are declared "const" to prevent xBestIndex from
106531  ** changing them.  We have to do some funky casting in order to
106532  ** initialize those fields.
106533  */
106534  pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
106535  pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
106536  pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
106537  *(int*)&pIdxInfo->nConstraint = nTerm;
106538  *(int*)&pIdxInfo->nOrderBy = nOrderBy;
106539  *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
106540  *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
106541  *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
106542                                                                   pUsage;
106543
106544  for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
106545    u8 op;
106546    if( pTerm->leftCursor != pSrc->iCursor ) continue;
106547    assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
106548    testcase( pTerm->eOperator & WO_IN );
106549    testcase( pTerm->eOperator & WO_ISNULL );
106550    if( pTerm->eOperator & (WO_ISNULL) ) continue;
106551    if( pTerm->wtFlags & TERM_VNULL ) continue;
106552    pIdxCons[j].iColumn = pTerm->u.leftColumn;
106553    pIdxCons[j].iTermOffset = i;
106554    op = (u8)pTerm->eOperator & WO_ALL;
106555    if( op==WO_IN ) op = WO_EQ;
106556    pIdxCons[j].op = op;
106557    /* The direct assignment in the previous line is possible only because
106558    ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
106559    ** following asserts verify this fact. */
106560    assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
106561    assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
106562    assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
106563    assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
106564    assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
106565    assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
106566    assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
106567    j++;
106568  }
106569  for(i=0; i<nOrderBy; i++){
106570    Expr *pExpr = pOrderBy->a[i].pExpr;
106571    pIdxOrderBy[i].iColumn = pExpr->iColumn;
106572    pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
106573  }
106574
106575  return pIdxInfo;
106576}
106577
106578/*
106579** The table object reference passed as the second argument to this function
106580** must represent a virtual table. This function invokes the xBestIndex()
106581** method of the virtual table with the sqlite3_index_info pointer passed
106582** as the argument.
106583**
106584** If an error occurs, pParse is populated with an error message and a
106585** non-zero value is returned. Otherwise, 0 is returned and the output
106586** part of the sqlite3_index_info structure is left populated.
106587**
106588** Whether or not an error is returned, it is the responsibility of the
106589** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
106590** that this is required.
106591*/
106592static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
106593  sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
106594  int i;
106595  int rc;
106596
106597  WHERETRACE(("xBestIndex for %s\n", pTab->zName));
106598  TRACE_IDX_INPUTS(p);
106599  rc = pVtab->pModule->xBestIndex(pVtab, p);
106600  TRACE_IDX_OUTPUTS(p);
106601
106602  if( rc!=SQLITE_OK ){
106603    if( rc==SQLITE_NOMEM ){
106604      pParse->db->mallocFailed = 1;
106605    }else if( !pVtab->zErrMsg ){
106606      sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
106607    }else{
106608      sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
106609    }
106610  }
106611  sqlite3_free(pVtab->zErrMsg);
106612  pVtab->zErrMsg = 0;
106613
106614  for(i=0; i<p->nConstraint; i++){
106615    if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
106616      sqlite3ErrorMsg(pParse,
106617          "table %s: xBestIndex returned an invalid plan", pTab->zName);
106618    }
106619  }
106620
106621  return pParse->nErr;
106622}
106623
106624
106625/*
106626** Compute the best index for a virtual table.
106627**
106628** The best index is computed by the xBestIndex method of the virtual
106629** table module.  This routine is really just a wrapper that sets up
106630** the sqlite3_index_info structure that is used to communicate with
106631** xBestIndex.
106632**
106633** In a join, this routine might be called multiple times for the
106634** same virtual table.  The sqlite3_index_info structure is created
106635** and initialized on the first invocation and reused on all subsequent
106636** invocations.  The sqlite3_index_info structure is also used when
106637** code is generated to access the virtual table.  The whereInfoDelete()
106638** routine takes care of freeing the sqlite3_index_info structure after
106639** everybody has finished with it.
106640*/
106641static void bestVirtualIndex(WhereBestIdx *p){
106642  Parse *pParse = p->pParse;      /* The parsing context */
106643  WhereClause *pWC = p->pWC;      /* The WHERE clause */
106644  struct SrcList_item *pSrc = p->pSrc; /* The FROM clause term to search */
106645  Table *pTab = pSrc->pTab;
106646  sqlite3_index_info *pIdxInfo;
106647  struct sqlite3_index_constraint *pIdxCons;
106648  struct sqlite3_index_constraint_usage *pUsage;
106649  WhereTerm *pTerm;
106650  int i, j;
106651  int nOrderBy;
106652  int bAllowIN;                   /* Allow IN optimizations */
106653  double rCost;
106654
106655  /* Make sure wsFlags is initialized to some sane value. Otherwise, if the
106656  ** malloc in allocateIndexInfo() fails and this function returns leaving
106657  ** wsFlags in an uninitialized state, the caller may behave unpredictably.
106658  */
106659  memset(&p->cost, 0, sizeof(p->cost));
106660  p->cost.plan.wsFlags = WHERE_VIRTUALTABLE;
106661
106662  /* If the sqlite3_index_info structure has not been previously
106663  ** allocated and initialized, then allocate and initialize it now.
106664  */
106665  pIdxInfo = *p->ppIdxInfo;
106666  if( pIdxInfo==0 ){
106667    *p->ppIdxInfo = pIdxInfo = allocateIndexInfo(p);
106668  }
106669  if( pIdxInfo==0 ){
106670    return;
106671  }
106672
106673  /* At this point, the sqlite3_index_info structure that pIdxInfo points
106674  ** to will have been initialized, either during the current invocation or
106675  ** during some prior invocation.  Now we just have to customize the
106676  ** details of pIdxInfo for the current invocation and pass it to
106677  ** xBestIndex.
106678  */
106679
106680  /* The module name must be defined. Also, by this point there must
106681  ** be a pointer to an sqlite3_vtab structure. Otherwise
106682  ** sqlite3ViewGetColumnNames() would have picked up the error.
106683  */
106684  assert( pTab->azModuleArg && pTab->azModuleArg[0] );
106685  assert( sqlite3GetVTable(pParse->db, pTab) );
106686
106687  /* Try once or twice.  On the first attempt, allow IN optimizations.
106688  ** If an IN optimization is accepted by the virtual table xBestIndex
106689  ** method, but the  pInfo->aConstrainUsage.omit flag is not set, then
106690  ** the query will not work because it might allow duplicate rows in
106691  ** output.  In that case, run the xBestIndex method a second time
106692  ** without the IN constraints.  Usually this loop only runs once.
106693  ** The loop will exit using a "break" statement.
106694  */
106695  for(bAllowIN=1; 1; bAllowIN--){
106696    assert( bAllowIN==0 || bAllowIN==1 );
106697
106698    /* Set the aConstraint[].usable fields and initialize all
106699    ** output variables to zero.
106700    **
106701    ** aConstraint[].usable is true for constraints where the right-hand
106702    ** side contains only references to tables to the left of the current
106703    ** table.  In other words, if the constraint is of the form:
106704    **
106705    **           column = expr
106706    **
106707    ** and we are evaluating a join, then the constraint on column is
106708    ** only valid if all tables referenced in expr occur to the left
106709    ** of the table containing column.
106710    **
106711    ** The aConstraints[] array contains entries for all constraints
106712    ** on the current table.  That way we only have to compute it once
106713    ** even though we might try to pick the best index multiple times.
106714    ** For each attempt at picking an index, the order of tables in the
106715    ** join might be different so we have to recompute the usable flag
106716    ** each time.
106717    */
106718    pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
106719    pUsage = pIdxInfo->aConstraintUsage;
106720    for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
106721      j = pIdxCons->iTermOffset;
106722      pTerm = &pWC->a[j];
106723      if( (pTerm->prereqRight&p->notReady)==0
106724       && (bAllowIN || (pTerm->eOperator & WO_IN)==0)
106725      ){
106726        pIdxCons->usable = 1;
106727      }else{
106728        pIdxCons->usable = 0;
106729      }
106730    }
106731    memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
106732    if( pIdxInfo->needToFreeIdxStr ){
106733      sqlite3_free(pIdxInfo->idxStr);
106734    }
106735    pIdxInfo->idxStr = 0;
106736    pIdxInfo->idxNum = 0;
106737    pIdxInfo->needToFreeIdxStr = 0;
106738    pIdxInfo->orderByConsumed = 0;
106739    /* ((double)2) In case of SQLITE_OMIT_FLOATING_POINT... */
106740    pIdxInfo->estimatedCost = SQLITE_BIG_DBL / ((double)2);
106741    nOrderBy = pIdxInfo->nOrderBy;
106742    if( !p->pOrderBy ){
106743      pIdxInfo->nOrderBy = 0;
106744    }
106745
106746    if( vtabBestIndex(pParse, pTab, pIdxInfo) ){
106747      return;
106748    }
106749
106750    pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
106751    for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
106752      if( pUsage[i].argvIndex>0 ){
106753        j = pIdxCons->iTermOffset;
106754        pTerm = &pWC->a[j];
106755        p->cost.used |= pTerm->prereqRight;
106756        if( (pTerm->eOperator & WO_IN)!=0 ){
106757          if( pUsage[i].omit==0 ){
106758            /* Do not attempt to use an IN constraint if the virtual table
106759            ** says that the equivalent EQ constraint cannot be safely omitted.
106760            ** If we do attempt to use such a constraint, some rows might be
106761            ** repeated in the output. */
106762            break;
106763          }
106764          /* A virtual table that is constrained by an IN clause may not
106765          ** consume the ORDER BY clause because (1) the order of IN terms
106766          ** is not necessarily related to the order of output terms and
106767          ** (2) Multiple outputs from a single IN value will not merge
106768          ** together.  */
106769          pIdxInfo->orderByConsumed = 0;
106770        }
106771      }
106772    }
106773    if( i>=pIdxInfo->nConstraint ) break;
106774  }
106775
106776  /* The orderByConsumed signal is only valid if all outer loops collectively
106777  ** generate just a single row of output.
106778  */
106779  if( pIdxInfo->orderByConsumed ){
106780    for(i=0; i<p->i; i++){
106781      if( (p->aLevel[i].plan.wsFlags & WHERE_UNIQUE)==0 ){
106782        pIdxInfo->orderByConsumed = 0;
106783      }
106784    }
106785  }
106786
106787  /* If there is an ORDER BY clause, and the selected virtual table index
106788  ** does not satisfy it, increase the cost of the scan accordingly. This
106789  ** matches the processing for non-virtual tables in bestBtreeIndex().
106790  */
106791  rCost = pIdxInfo->estimatedCost;
106792  if( p->pOrderBy && pIdxInfo->orderByConsumed==0 ){
106793    rCost += estLog(rCost)*rCost;
106794  }
106795
106796  /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
106797  ** inital value of lowestCost in this loop. If it is, then the
106798  ** (cost<lowestCost) test below will never be true.
106799  **
106800  ** Use "(double)2" instead of "2.0" in case OMIT_FLOATING_POINT
106801  ** is defined.
106802  */
106803  if( (SQLITE_BIG_DBL/((double)2))<rCost ){
106804    p->cost.rCost = (SQLITE_BIG_DBL/((double)2));
106805  }else{
106806    p->cost.rCost = rCost;
106807  }
106808  p->cost.plan.u.pVtabIdx = pIdxInfo;
106809  if( pIdxInfo->orderByConsumed ){
106810    p->cost.plan.wsFlags |= WHERE_ORDERED;
106811    p->cost.plan.nOBSat = nOrderBy;
106812  }else{
106813    p->cost.plan.nOBSat = p->i ? p->aLevel[p->i-1].plan.nOBSat : 0;
106814  }
106815  p->cost.plan.nEq = 0;
106816  pIdxInfo->nOrderBy = nOrderBy;
106817
106818  /* Try to find a more efficient access pattern by using multiple indexes
106819  ** to optimize an OR expression within the WHERE clause.
106820  */
106821  bestOrClauseIndex(p);
106822}
106823#endif /* SQLITE_OMIT_VIRTUALTABLE */
106824
106825#ifdef SQLITE_ENABLE_STAT3
106826/*
106827** Estimate the location of a particular key among all keys in an
106828** index.  Store the results in aStat as follows:
106829**
106830**    aStat[0]      Est. number of rows less than pVal
106831**    aStat[1]      Est. number of rows equal to pVal
106832**
106833** Return SQLITE_OK on success.
106834*/
106835static int whereKeyStats(
106836  Parse *pParse,              /* Database connection */
106837  Index *pIdx,                /* Index to consider domain of */
106838  sqlite3_value *pVal,        /* Value to consider */
106839  int roundUp,                /* Round up if true.  Round down if false */
106840  tRowcnt *aStat              /* OUT: stats written here */
106841){
106842  tRowcnt n;
106843  IndexSample *aSample;
106844  int i, eType;
106845  int isEq = 0;
106846  i64 v;
106847  double r, rS;
106848
106849  assert( roundUp==0 || roundUp==1 );
106850  assert( pIdx->nSample>0 );
106851  if( pVal==0 ) return SQLITE_ERROR;
106852  n = pIdx->aiRowEst[0];
106853  aSample = pIdx->aSample;
106854  eType = sqlite3_value_type(pVal);
106855
106856  if( eType==SQLITE_INTEGER ){
106857    v = sqlite3_value_int64(pVal);
106858    r = (i64)v;
106859    for(i=0; i<pIdx->nSample; i++){
106860      if( aSample[i].eType==SQLITE_NULL ) continue;
106861      if( aSample[i].eType>=SQLITE_TEXT ) break;
106862      if( aSample[i].eType==SQLITE_INTEGER ){
106863        if( aSample[i].u.i>=v ){
106864          isEq = aSample[i].u.i==v;
106865          break;
106866        }
106867      }else{
106868        assert( aSample[i].eType==SQLITE_FLOAT );
106869        if( aSample[i].u.r>=r ){
106870          isEq = aSample[i].u.r==r;
106871          break;
106872        }
106873      }
106874    }
106875  }else if( eType==SQLITE_FLOAT ){
106876    r = sqlite3_value_double(pVal);
106877    for(i=0; i<pIdx->nSample; i++){
106878      if( aSample[i].eType==SQLITE_NULL ) continue;
106879      if( aSample[i].eType>=SQLITE_TEXT ) break;
106880      if( aSample[i].eType==SQLITE_FLOAT ){
106881        rS = aSample[i].u.r;
106882      }else{
106883        rS = aSample[i].u.i;
106884      }
106885      if( rS>=r ){
106886        isEq = rS==r;
106887        break;
106888      }
106889    }
106890  }else if( eType==SQLITE_NULL ){
106891    i = 0;
106892    if( aSample[0].eType==SQLITE_NULL ) isEq = 1;
106893  }else{
106894    assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
106895    for(i=0; i<pIdx->nSample; i++){
106896      if( aSample[i].eType==SQLITE_TEXT || aSample[i].eType==SQLITE_BLOB ){
106897        break;
106898      }
106899    }
106900    if( i<pIdx->nSample ){
106901      sqlite3 *db = pParse->db;
106902      CollSeq *pColl;
106903      const u8 *z;
106904      if( eType==SQLITE_BLOB ){
106905        z = (const u8 *)sqlite3_value_blob(pVal);
106906        pColl = db->pDfltColl;
106907        assert( pColl->enc==SQLITE_UTF8 );
106908      }else{
106909        pColl = sqlite3GetCollSeq(pParse, SQLITE_UTF8, 0, *pIdx->azColl);
106910        if( pColl==0 ){
106911          return SQLITE_ERROR;
106912        }
106913        z = (const u8 *)sqlite3ValueText(pVal, pColl->enc);
106914        if( !z ){
106915          return SQLITE_NOMEM;
106916        }
106917        assert( z && pColl && pColl->xCmp );
106918      }
106919      n = sqlite3ValueBytes(pVal, pColl->enc);
106920
106921      for(; i<pIdx->nSample; i++){
106922        int c;
106923        int eSampletype = aSample[i].eType;
106924        if( eSampletype<eType ) continue;
106925        if( eSampletype!=eType ) break;
106926#ifndef SQLITE_OMIT_UTF16
106927        if( pColl->enc!=SQLITE_UTF8 ){
106928          int nSample;
106929          char *zSample = sqlite3Utf8to16(
106930              db, pColl->enc, aSample[i].u.z, aSample[i].nByte, &nSample
106931          );
106932          if( !zSample ){
106933            assert( db->mallocFailed );
106934            return SQLITE_NOMEM;
106935          }
106936          c = pColl->xCmp(pColl->pUser, nSample, zSample, n, z);
106937          sqlite3DbFree(db, zSample);
106938        }else
106939#endif
106940        {
106941          c = pColl->xCmp(pColl->pUser, aSample[i].nByte, aSample[i].u.z, n, z);
106942        }
106943        if( c>=0 ){
106944          if( c==0 ) isEq = 1;
106945          break;
106946        }
106947      }
106948    }
106949  }
106950
106951  /* At this point, aSample[i] is the first sample that is greater than
106952  ** or equal to pVal.  Or if i==pIdx->nSample, then all samples are less
106953  ** than pVal.  If aSample[i]==pVal, then isEq==1.
106954  */
106955  if( isEq ){
106956    assert( i<pIdx->nSample );
106957    aStat[0] = aSample[i].nLt;
106958    aStat[1] = aSample[i].nEq;
106959  }else{
106960    tRowcnt iLower, iUpper, iGap;
106961    if( i==0 ){
106962      iLower = 0;
106963      iUpper = aSample[0].nLt;
106964    }else{
106965      iUpper = i>=pIdx->nSample ? n : aSample[i].nLt;
106966      iLower = aSample[i-1].nEq + aSample[i-1].nLt;
106967    }
106968    aStat[1] = pIdx->avgEq;
106969    if( iLower>=iUpper ){
106970      iGap = 0;
106971    }else{
106972      iGap = iUpper - iLower;
106973    }
106974    if( roundUp ){
106975      iGap = (iGap*2)/3;
106976    }else{
106977      iGap = iGap/3;
106978    }
106979    aStat[0] = iLower + iGap;
106980  }
106981  return SQLITE_OK;
106982}
106983#endif /* SQLITE_ENABLE_STAT3 */
106984
106985/*
106986** If expression pExpr represents a literal value, set *pp to point to
106987** an sqlite3_value structure containing the same value, with affinity
106988** aff applied to it, before returning. It is the responsibility of the
106989** caller to eventually release this structure by passing it to
106990** sqlite3ValueFree().
106991**
106992** If the current parse is a recompile (sqlite3Reprepare()) and pExpr
106993** is an SQL variable that currently has a non-NULL value bound to it,
106994** create an sqlite3_value structure containing this value, again with
106995** affinity aff applied to it, instead.
106996**
106997** If neither of the above apply, set *pp to NULL.
106998**
106999** If an error occurs, return an error code. Otherwise, SQLITE_OK.
107000*/
107001#ifdef SQLITE_ENABLE_STAT3
107002static int valueFromExpr(
107003  Parse *pParse,
107004  Expr *pExpr,
107005  u8 aff,
107006  sqlite3_value **pp
107007){
107008  if( pExpr->op==TK_VARIABLE
107009   || (pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
107010  ){
107011    int iVar = pExpr->iColumn;
107012    sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
107013    *pp = sqlite3VdbeGetValue(pParse->pReprepare, iVar, aff);
107014    return SQLITE_OK;
107015  }
107016  return sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, aff, pp);
107017}
107018#endif
107019
107020/*
107021** This function is used to estimate the number of rows that will be visited
107022** by scanning an index for a range of values. The range may have an upper
107023** bound, a lower bound, or both. The WHERE clause terms that set the upper
107024** and lower bounds are represented by pLower and pUpper respectively. For
107025** example, assuming that index p is on t1(a):
107026**
107027**   ... FROM t1 WHERE a > ? AND a < ? ...
107028**                    |_____|   |_____|
107029**                       |         |
107030**                     pLower    pUpper
107031**
107032** If either of the upper or lower bound is not present, then NULL is passed in
107033** place of the corresponding WhereTerm.
107034**
107035** The nEq parameter is passed the index of the index column subject to the
107036** range constraint. Or, equivalently, the number of equality constraints
107037** optimized by the proposed index scan. For example, assuming index p is
107038** on t1(a, b), and the SQL query is:
107039**
107040**   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
107041**
107042** then nEq should be passed the value 1 (as the range restricted column,
107043** b, is the second left-most column of the index). Or, if the query is:
107044**
107045**   ... FROM t1 WHERE a > ? AND a < ? ...
107046**
107047** then nEq should be passed 0.
107048**
107049** The returned value is an integer divisor to reduce the estimated
107050** search space.  A return value of 1 means that range constraints are
107051** no help at all.  A return value of 2 means range constraints are
107052** expected to reduce the search space by half.  And so forth...
107053**
107054** In the absence of sqlite_stat3 ANALYZE data, each range inequality
107055** reduces the search space by a factor of 4.  Hence a single constraint (x>?)
107056** results in a return of 4 and a range constraint (x>? AND x<?) results
107057** in a return of 16.
107058*/
107059static int whereRangeScanEst(
107060  Parse *pParse,       /* Parsing & code generating context */
107061  Index *p,            /* The index containing the range-compared column; "x" */
107062  int nEq,             /* index into p->aCol[] of the range-compared column */
107063  WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
107064  WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
107065  double *pRangeDiv   /* OUT: Reduce search space by this divisor */
107066){
107067  int rc = SQLITE_OK;
107068
107069#ifdef SQLITE_ENABLE_STAT3
107070
107071  if( nEq==0 && p->nSample ){
107072    sqlite3_value *pRangeVal;
107073    tRowcnt iLower = 0;
107074    tRowcnt iUpper = p->aiRowEst[0];
107075    tRowcnt a[2];
107076    u8 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
107077
107078    if( pLower ){
107079      Expr *pExpr = pLower->pExpr->pRight;
107080      rc = valueFromExpr(pParse, pExpr, aff, &pRangeVal);
107081      assert( (pLower->eOperator & (WO_GT|WO_GE))!=0 );
107082      if( rc==SQLITE_OK
107083       && whereKeyStats(pParse, p, pRangeVal, 0, a)==SQLITE_OK
107084      ){
107085        iLower = a[0];
107086        if( (pLower->eOperator & WO_GT)!=0 ) iLower += a[1];
107087      }
107088      sqlite3ValueFree(pRangeVal);
107089    }
107090    if( rc==SQLITE_OK && pUpper ){
107091      Expr *pExpr = pUpper->pExpr->pRight;
107092      rc = valueFromExpr(pParse, pExpr, aff, &pRangeVal);
107093      assert( (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
107094      if( rc==SQLITE_OK
107095       && whereKeyStats(pParse, p, pRangeVal, 1, a)==SQLITE_OK
107096      ){
107097        iUpper = a[0];
107098        if( (pUpper->eOperator & WO_LE)!=0 ) iUpper += a[1];
107099      }
107100      sqlite3ValueFree(pRangeVal);
107101    }
107102    if( rc==SQLITE_OK ){
107103      if( iUpper<=iLower ){
107104        *pRangeDiv = (double)p->aiRowEst[0];
107105      }else{
107106        *pRangeDiv = (double)p->aiRowEst[0]/(double)(iUpper - iLower);
107107      }
107108      WHERETRACE(("range scan regions: %u..%u  div=%g\n",
107109                  (u32)iLower, (u32)iUpper, *pRangeDiv));
107110      return SQLITE_OK;
107111    }
107112  }
107113#else
107114  UNUSED_PARAMETER(pParse);
107115  UNUSED_PARAMETER(p);
107116  UNUSED_PARAMETER(nEq);
107117#endif
107118  assert( pLower || pUpper );
107119  *pRangeDiv = (double)1;
107120  if( pLower && (pLower->wtFlags & TERM_VNULL)==0 ) *pRangeDiv *= (double)4;
107121  if( pUpper ) *pRangeDiv *= (double)4;
107122  return rc;
107123}
107124
107125#ifdef SQLITE_ENABLE_STAT3
107126/*
107127** Estimate the number of rows that will be returned based on
107128** an equality constraint x=VALUE and where that VALUE occurs in
107129** the histogram data.  This only works when x is the left-most
107130** column of an index and sqlite_stat3 histogram data is available
107131** for that index.  When pExpr==NULL that means the constraint is
107132** "x IS NULL" instead of "x=VALUE".
107133**
107134** Write the estimated row count into *pnRow and return SQLITE_OK.
107135** If unable to make an estimate, leave *pnRow unchanged and return
107136** non-zero.
107137**
107138** This routine can fail if it is unable to load a collating sequence
107139** required for string comparison, or if unable to allocate memory
107140** for a UTF conversion required for comparison.  The error is stored
107141** in the pParse structure.
107142*/
107143static int whereEqualScanEst(
107144  Parse *pParse,       /* Parsing & code generating context */
107145  Index *p,            /* The index whose left-most column is pTerm */
107146  Expr *pExpr,         /* Expression for VALUE in the x=VALUE constraint */
107147  double *pnRow        /* Write the revised row estimate here */
107148){
107149  sqlite3_value *pRhs = 0;  /* VALUE on right-hand side of pTerm */
107150  u8 aff;                   /* Column affinity */
107151  int rc;                   /* Subfunction return code */
107152  tRowcnt a[2];             /* Statistics */
107153
107154  assert( p->aSample!=0 );
107155  assert( p->nSample>0 );
107156  aff = p->pTable->aCol[p->aiColumn[0]].affinity;
107157  if( pExpr ){
107158    rc = valueFromExpr(pParse, pExpr, aff, &pRhs);
107159    if( rc ) goto whereEqualScanEst_cancel;
107160  }else{
107161    pRhs = sqlite3ValueNew(pParse->db);
107162  }
107163  if( pRhs==0 ) return SQLITE_NOTFOUND;
107164  rc = whereKeyStats(pParse, p, pRhs, 0, a);
107165  if( rc==SQLITE_OK ){
107166    WHERETRACE(("equality scan regions: %d\n", (int)a[1]));
107167    *pnRow = a[1];
107168  }
107169whereEqualScanEst_cancel:
107170  sqlite3ValueFree(pRhs);
107171  return rc;
107172}
107173#endif /* defined(SQLITE_ENABLE_STAT3) */
107174
107175#ifdef SQLITE_ENABLE_STAT3
107176/*
107177** Estimate the number of rows that will be returned based on
107178** an IN constraint where the right-hand side of the IN operator
107179** is a list of values.  Example:
107180**
107181**        WHERE x IN (1,2,3,4)
107182**
107183** Write the estimated row count into *pnRow and return SQLITE_OK.
107184** If unable to make an estimate, leave *pnRow unchanged and return
107185** non-zero.
107186**
107187** This routine can fail if it is unable to load a collating sequence
107188** required for string comparison, or if unable to allocate memory
107189** for a UTF conversion required for comparison.  The error is stored
107190** in the pParse structure.
107191*/
107192static int whereInScanEst(
107193  Parse *pParse,       /* Parsing & code generating context */
107194  Index *p,            /* The index whose left-most column is pTerm */
107195  ExprList *pList,     /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
107196  double *pnRow        /* Write the revised row estimate here */
107197){
107198  int rc = SQLITE_OK;         /* Subfunction return code */
107199  double nEst;                /* Number of rows for a single term */
107200  double nRowEst = (double)0; /* New estimate of the number of rows */
107201  int i;                      /* Loop counter */
107202
107203  assert( p->aSample!=0 );
107204  for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
107205    nEst = p->aiRowEst[0];
107206    rc = whereEqualScanEst(pParse, p, pList->a[i].pExpr, &nEst);
107207    nRowEst += nEst;
107208  }
107209  if( rc==SQLITE_OK ){
107210    if( nRowEst > p->aiRowEst[0] ) nRowEst = p->aiRowEst[0];
107211    *pnRow = nRowEst;
107212    WHERETRACE(("IN row estimate: est=%g\n", nRowEst));
107213  }
107214  return rc;
107215}
107216#endif /* defined(SQLITE_ENABLE_STAT3) */
107217
107218/*
107219** Check to see if column iCol of the table with cursor iTab will appear
107220** in sorted order according to the current query plan.
107221**
107222** Return values:
107223**
107224**    0   iCol is not ordered
107225**    1   iCol has only a single value
107226**    2   iCol is in ASC order
107227**    3   iCol is in DESC order
107228*/
107229static int isOrderedColumn(
107230  WhereBestIdx *p,
107231  int iTab,
107232  int iCol
107233){
107234  int i, j;
107235  WhereLevel *pLevel = &p->aLevel[p->i-1];
107236  Index *pIdx;
107237  u8 sortOrder;
107238  for(i=p->i-1; i>=0; i--, pLevel--){
107239    if( pLevel->iTabCur!=iTab ) continue;
107240    if( (pLevel->plan.wsFlags & WHERE_ALL_UNIQUE)!=0 ){
107241      return 1;
107242    }
107243    assert( (pLevel->plan.wsFlags & WHERE_ORDERED)!=0 );
107244    if( (pIdx = pLevel->plan.u.pIdx)!=0 ){
107245      if( iCol<0 ){
107246        sortOrder = 0;
107247        testcase( (pLevel->plan.wsFlags & WHERE_REVERSE)!=0 );
107248      }else{
107249        int n = pIdx->nColumn;
107250        for(j=0; j<n; j++){
107251          if( iCol==pIdx->aiColumn[j] ) break;
107252        }
107253        if( j>=n ) return 0;
107254        sortOrder = pIdx->aSortOrder[j];
107255        testcase( (pLevel->plan.wsFlags & WHERE_REVERSE)!=0 );
107256      }
107257    }else{
107258      if( iCol!=(-1) ) return 0;
107259      sortOrder = 0;
107260      testcase( (pLevel->plan.wsFlags & WHERE_REVERSE)!=0 );
107261    }
107262    if( (pLevel->plan.wsFlags & WHERE_REVERSE)!=0 ){
107263      assert( sortOrder==0 || sortOrder==1 );
107264      testcase( sortOrder==1 );
107265      sortOrder = 1 - sortOrder;
107266    }
107267    return sortOrder+2;
107268  }
107269  return 0;
107270}
107271
107272/*
107273** This routine decides if pIdx can be used to satisfy the ORDER BY
107274** clause, either in whole or in part.  The return value is the
107275** cumulative number of terms in the ORDER BY clause that are satisfied
107276** by the index pIdx and other indices in outer loops.
107277**
107278** The table being queried has a cursor number of "base".  pIdx is the
107279** index that is postulated for use to access the table.
107280**
107281** The *pbRev value is set to 0 order 1 depending on whether or not
107282** pIdx should be run in the forward order or in reverse order.
107283*/
107284static int isSortingIndex(
107285  WhereBestIdx *p,    /* Best index search context */
107286  Index *pIdx,        /* The index we are testing */
107287  int base,           /* Cursor number for the table to be sorted */
107288  int *pbRev,         /* Set to 1 for reverse-order scan of pIdx */
107289  int *pbObUnique     /* ORDER BY column values will different in every row */
107290){
107291  int i;                        /* Number of pIdx terms used */
107292  int j;                        /* Number of ORDER BY terms satisfied */
107293  int sortOrder = 2;            /* 0: forward.  1: backward.  2: unknown */
107294  int nTerm;                    /* Number of ORDER BY terms */
107295  struct ExprList_item *pOBItem;/* A term of the ORDER BY clause */
107296  Table *pTab = pIdx->pTable;   /* Table that owns index pIdx */
107297  ExprList *pOrderBy;           /* The ORDER BY clause */
107298  Parse *pParse = p->pParse;    /* Parser context */
107299  sqlite3 *db = pParse->db;     /* Database connection */
107300  int nPriorSat;                /* ORDER BY terms satisfied by outer loops */
107301  int seenRowid = 0;            /* True if an ORDER BY rowid term is seen */
107302  int uniqueNotNull;            /* pIdx is UNIQUE with all terms are NOT NULL */
107303  int outerObUnique;            /* Outer loops generate different values in
107304                                ** every row for the ORDER BY columns */
107305
107306  if( p->i==0 ){
107307    nPriorSat = 0;
107308    outerObUnique = 1;
107309  }else{
107310    u32 wsFlags = p->aLevel[p->i-1].plan.wsFlags;
107311    nPriorSat = p->aLevel[p->i-1].plan.nOBSat;
107312    if( (wsFlags & WHERE_ORDERED)==0 ){
107313      /* This loop cannot be ordered unless the next outer loop is
107314      ** also ordered */
107315      return nPriorSat;
107316    }
107317    if( OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ){
107318      /* Only look at the outer-most loop if the OrderByIdxJoin
107319      ** optimization is disabled */
107320      return nPriorSat;
107321    }
107322    testcase( wsFlags & WHERE_OB_UNIQUE );
107323    testcase( wsFlags & WHERE_ALL_UNIQUE );
107324    outerObUnique = (wsFlags & (WHERE_OB_UNIQUE|WHERE_ALL_UNIQUE))!=0;
107325  }
107326  pOrderBy = p->pOrderBy;
107327  assert( pOrderBy!=0 );
107328  if( pIdx->bUnordered ){
107329    /* Hash indices (indicated by the "unordered" tag on sqlite_stat1) cannot
107330    ** be used for sorting */
107331    return nPriorSat;
107332  }
107333  nTerm = pOrderBy->nExpr;
107334  uniqueNotNull = pIdx->onError!=OE_None;
107335  assert( nTerm>0 );
107336
107337  /* Argument pIdx must either point to a 'real' named index structure,
107338  ** or an index structure allocated on the stack by bestBtreeIndex() to
107339  ** represent the rowid index that is part of every table.  */
107340  assert( pIdx->zName || (pIdx->nColumn==1 && pIdx->aiColumn[0]==-1) );
107341
107342  /* Match terms of the ORDER BY clause against columns of
107343  ** the index.
107344  **
107345  ** Note that indices have pIdx->nColumn regular columns plus
107346  ** one additional column containing the rowid.  The rowid column
107347  ** of the index is also allowed to match against the ORDER BY
107348  ** clause.
107349  */
107350  j = nPriorSat;
107351  for(i=0,pOBItem=&pOrderBy->a[j]; j<nTerm && i<=pIdx->nColumn; i++){
107352    Expr *pOBExpr;          /* The expression of the ORDER BY pOBItem */
107353    CollSeq *pColl;         /* The collating sequence of pOBExpr */
107354    int termSortOrder;      /* Sort order for this term */
107355    int iColumn;            /* The i-th column of the index.  -1 for rowid */
107356    int iSortOrder;         /* 1 for DESC, 0 for ASC on the i-th index term */
107357    int isEq;               /* Subject to an == or IS NULL constraint */
107358    int isMatch;            /* ORDER BY term matches the index term */
107359    const char *zColl;      /* Name of collating sequence for i-th index term */
107360    WhereTerm *pConstraint; /* A constraint in the WHERE clause */
107361
107362    /* If the next term of the ORDER BY clause refers to anything other than
107363    ** a column in the "base" table, then this index will not be of any
107364    ** further use in handling the ORDER BY. */
107365    pOBExpr = sqlite3ExprSkipCollate(pOBItem->pExpr);
107366    if( pOBExpr->op!=TK_COLUMN || pOBExpr->iTable!=base ){
107367      break;
107368    }
107369
107370    /* Find column number and collating sequence for the next entry
107371    ** in the index */
107372    if( pIdx->zName && i<pIdx->nColumn ){
107373      iColumn = pIdx->aiColumn[i];
107374      if( iColumn==pIdx->pTable->iPKey ){
107375        iColumn = -1;
107376      }
107377      iSortOrder = pIdx->aSortOrder[i];
107378      zColl = pIdx->azColl[i];
107379      assert( zColl!=0 );
107380    }else{
107381      iColumn = -1;
107382      iSortOrder = 0;
107383      zColl = 0;
107384    }
107385
107386    /* Check to see if the column number and collating sequence of the
107387    ** index match the column number and collating sequence of the ORDER BY
107388    ** clause entry.  Set isMatch to 1 if they both match. */
107389    if( pOBExpr->iColumn==iColumn ){
107390      if( zColl ){
107391        pColl = sqlite3ExprCollSeq(pParse, pOBItem->pExpr);
107392        if( !pColl ) pColl = db->pDfltColl;
107393        isMatch = sqlite3StrICmp(pColl->zName, zColl)==0;
107394      }else{
107395        isMatch = 1;
107396      }
107397    }else{
107398      isMatch = 0;
107399    }
107400
107401    /* termSortOrder is 0 or 1 for whether or not the access loop should
107402    ** run forward or backwards (respectively) in order to satisfy this
107403    ** term of the ORDER BY clause. */
107404    assert( pOBItem->sortOrder==0 || pOBItem->sortOrder==1 );
107405    assert( iSortOrder==0 || iSortOrder==1 );
107406    termSortOrder = iSortOrder ^ pOBItem->sortOrder;
107407
107408    /* If X is the column in the index and ORDER BY clause, check to see
107409    ** if there are any X= or X IS NULL constraints in the WHERE clause. */
107410    pConstraint = findTerm(p->pWC, base, iColumn, p->notReady,
107411                           WO_EQ|WO_ISNULL|WO_IN, pIdx);
107412    if( pConstraint==0 ){
107413      isEq = 0;
107414    }else if( (pConstraint->eOperator & WO_IN)!=0 ){
107415      isEq = 0;
107416    }else if( (pConstraint->eOperator & WO_ISNULL)!=0 ){
107417      uniqueNotNull = 0;
107418      isEq = 1;  /* "X IS NULL" means X has only a single value */
107419    }else if( pConstraint->prereqRight==0 ){
107420      isEq = 1;  /* Constraint "X=constant" means X has only a single value */
107421    }else{
107422      Expr *pRight = pConstraint->pExpr->pRight;
107423      if( pRight->op==TK_COLUMN ){
107424        WHERETRACE(("       .. isOrderedColumn(tab=%d,col=%d)",
107425                    pRight->iTable, pRight->iColumn));
107426        isEq = isOrderedColumn(p, pRight->iTable, pRight->iColumn);
107427        WHERETRACE((" -> isEq=%d\n", isEq));
107428
107429        /* If the constraint is of the form X=Y where Y is an ordered value
107430        ** in an outer loop, then make sure the sort order of Y matches the
107431        ** sort order required for X. */
107432        if( isMatch && isEq>=2 && isEq!=pOBItem->sortOrder+2 ){
107433          testcase( isEq==2 );
107434          testcase( isEq==3 );
107435          break;
107436        }
107437      }else{
107438        isEq = 0;  /* "X=expr" places no ordering constraints on X */
107439      }
107440    }
107441    if( !isMatch ){
107442      if( isEq==0 ){
107443        break;
107444      }else{
107445        continue;
107446      }
107447    }else if( isEq!=1 ){
107448      if( sortOrder==2 ){
107449        sortOrder = termSortOrder;
107450      }else if( termSortOrder!=sortOrder ){
107451        break;
107452      }
107453    }
107454    j++;
107455    pOBItem++;
107456    if( iColumn<0 ){
107457      seenRowid = 1;
107458      break;
107459    }else if( pTab->aCol[iColumn].notNull==0 && isEq!=1 ){
107460      testcase( isEq==0 );
107461      testcase( isEq==2 );
107462      testcase( isEq==3 );
107463      uniqueNotNull = 0;
107464    }
107465  }
107466  if( seenRowid ){
107467    uniqueNotNull = 1;
107468  }else if( uniqueNotNull==0 || i<pIdx->nColumn ){
107469    uniqueNotNull = 0;
107470  }
107471
107472  /* If we have not found at least one ORDER BY term that matches the
107473  ** index, then show no progress. */
107474  if( pOBItem==&pOrderBy->a[nPriorSat] ) return nPriorSat;
107475
107476  /* Either the outer queries must generate rows where there are no two
107477  ** rows with the same values in all ORDER BY columns, or else this
107478  ** loop must generate just a single row of output.  Example:  Suppose
107479  ** the outer loops generate A=1 and A=1, and this loop generates B=3
107480  ** and B=4.  Then without the following test, ORDER BY A,B would
107481  ** generate the wrong order output: 1,3 1,4 1,3 1,4
107482  */
107483  if( outerObUnique==0 && uniqueNotNull==0 ) return nPriorSat;
107484  *pbObUnique = uniqueNotNull;
107485
107486  /* Return the necessary scan order back to the caller */
107487  *pbRev = sortOrder & 1;
107488
107489  /* If there was an "ORDER BY rowid" term that matched, or it is only
107490  ** possible for a single row from this table to match, then skip over
107491  ** any additional ORDER BY terms dealing with this table.
107492  */
107493  if( uniqueNotNull ){
107494    /* Advance j over additional ORDER BY terms associated with base */
107495    WhereMaskSet *pMS = p->pWC->pMaskSet;
107496    Bitmask m = ~getMask(pMS, base);
107497    while( j<nTerm && (exprTableUsage(pMS, pOrderBy->a[j].pExpr)&m)==0 ){
107498      j++;
107499    }
107500  }
107501  return j;
107502}
107503
107504/*
107505** Find the best query plan for accessing a particular table.  Write the
107506** best query plan and its cost into the p->cost.
107507**
107508** The lowest cost plan wins.  The cost is an estimate of the amount of
107509** CPU and disk I/O needed to process the requested result.
107510** Factors that influence cost include:
107511**
107512**    *  The estimated number of rows that will be retrieved.  (The
107513**       fewer the better.)
107514**
107515**    *  Whether or not sorting must occur.
107516**
107517**    *  Whether or not there must be separate lookups in the
107518**       index and in the main table.
107519**
107520** If there was an INDEXED BY clause (pSrc->pIndex) attached to the table in
107521** the SQL statement, then this function only considers plans using the
107522** named index. If no such plan is found, then the returned cost is
107523** SQLITE_BIG_DBL. If a plan is found that uses the named index,
107524** then the cost is calculated in the usual way.
107525**
107526** If a NOT INDEXED clause was attached to the table
107527** in the SELECT statement, then no indexes are considered. However, the
107528** selected plan may still take advantage of the built-in rowid primary key
107529** index.
107530*/
107531static void bestBtreeIndex(WhereBestIdx *p){
107532  Parse *pParse = p->pParse;  /* The parsing context */
107533  WhereClause *pWC = p->pWC;  /* The WHERE clause */
107534  struct SrcList_item *pSrc = p->pSrc; /* The FROM clause term to search */
107535  int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
107536  Index *pProbe;              /* An index we are evaluating */
107537  Index *pIdx;                /* Copy of pProbe, or zero for IPK index */
107538  int eqTermMask;             /* Current mask of valid equality operators */
107539  int idxEqTermMask;          /* Index mask of valid equality operators */
107540  Index sPk;                  /* A fake index object for the primary key */
107541  tRowcnt aiRowEstPk[2];      /* The aiRowEst[] value for the sPk index */
107542  int aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
107543  int wsFlagMask;             /* Allowed flags in p->cost.plan.wsFlag */
107544  int nPriorSat;              /* ORDER BY terms satisfied by outer loops */
107545  int nOrderBy;               /* Number of ORDER BY terms */
107546  char bSortInit;             /* Initializer for bSort in inner loop */
107547  char bDistInit;             /* Initializer for bDist in inner loop */
107548
107549
107550  /* Initialize the cost to a worst-case value */
107551  memset(&p->cost, 0, sizeof(p->cost));
107552  p->cost.rCost = SQLITE_BIG_DBL;
107553
107554  /* If the pSrc table is the right table of a LEFT JOIN then we may not
107555  ** use an index to satisfy IS NULL constraints on that table.  This is
107556  ** because columns might end up being NULL if the table does not match -
107557  ** a circumstance which the index cannot help us discover.  Ticket #2177.
107558  */
107559  if( pSrc->jointype & JT_LEFT ){
107560    idxEqTermMask = WO_EQ|WO_IN;
107561  }else{
107562    idxEqTermMask = WO_EQ|WO_IN|WO_ISNULL;
107563  }
107564
107565  if( pSrc->pIndex ){
107566    /* An INDEXED BY clause specifies a particular index to use */
107567    pIdx = pProbe = pSrc->pIndex;
107568    wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
107569    eqTermMask = idxEqTermMask;
107570  }else{
107571    /* There is no INDEXED BY clause.  Create a fake Index object in local
107572    ** variable sPk to represent the rowid primary key index.  Make this
107573    ** fake index the first in a chain of Index objects with all of the real
107574    ** indices to follow */
107575    Index *pFirst;                  /* First of real indices on the table */
107576    memset(&sPk, 0, sizeof(Index));
107577    sPk.nColumn = 1;
107578    sPk.aiColumn = &aiColumnPk;
107579    sPk.aiRowEst = aiRowEstPk;
107580    sPk.onError = OE_Replace;
107581    sPk.pTable = pSrc->pTab;
107582    aiRowEstPk[0] = pSrc->pTab->nRowEst;
107583    aiRowEstPk[1] = 1;
107584    pFirst = pSrc->pTab->pIndex;
107585    if( pSrc->notIndexed==0 ){
107586      /* The real indices of the table are only considered if the
107587      ** NOT INDEXED qualifier is omitted from the FROM clause */
107588      sPk.pNext = pFirst;
107589    }
107590    pProbe = &sPk;
107591    wsFlagMask = ~(
107592        WHERE_COLUMN_IN|WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_RANGE
107593    );
107594    eqTermMask = WO_EQ|WO_IN;
107595    pIdx = 0;
107596  }
107597
107598  nOrderBy = p->pOrderBy ? p->pOrderBy->nExpr : 0;
107599  if( p->i ){
107600    nPriorSat = p->aLevel[p->i-1].plan.nOBSat;
107601    bSortInit = nPriorSat<nOrderBy;
107602    bDistInit = 0;
107603  }else{
107604    nPriorSat = 0;
107605    bSortInit = nOrderBy>0;
107606    bDistInit = p->pDistinct!=0;
107607  }
107608
107609  /* Loop over all indices looking for the best one to use
107610  */
107611  for(; pProbe; pIdx=pProbe=pProbe->pNext){
107612    const tRowcnt * const aiRowEst = pProbe->aiRowEst;
107613    WhereCost pc;               /* Cost of using pProbe */
107614    double log10N = (double)1;  /* base-10 logarithm of nRow (inexact) */
107615
107616    /* The following variables are populated based on the properties of
107617    ** index being evaluated. They are then used to determine the expected
107618    ** cost and number of rows returned.
107619    **
107620    **  pc.plan.nEq:
107621    **    Number of equality terms that can be implemented using the index.
107622    **    In other words, the number of initial fields in the index that
107623    **    are used in == or IN or NOT NULL constraints of the WHERE clause.
107624    **
107625    **  nInMul:
107626    **    The "in-multiplier". This is an estimate of how many seek operations
107627    **    SQLite must perform on the index in question. For example, if the
107628    **    WHERE clause is:
107629    **
107630    **      WHERE a IN (1, 2, 3) AND b IN (4, 5, 6)
107631    **
107632    **    SQLite must perform 9 lookups on an index on (a, b), so nInMul is
107633    **    set to 9. Given the same schema and either of the following WHERE
107634    **    clauses:
107635    **
107636    **      WHERE a =  1
107637    **      WHERE a >= 2
107638    **
107639    **    nInMul is set to 1.
107640    **
107641    **    If there exists a WHERE term of the form "x IN (SELECT ...)", then
107642    **    the sub-select is assumed to return 25 rows for the purposes of
107643    **    determining nInMul.
107644    **
107645    **  bInEst:
107646    **    Set to true if there was at least one "x IN (SELECT ...)" term used
107647    **    in determining the value of nInMul.  Note that the RHS of the
107648    **    IN operator must be a SELECT, not a value list, for this variable
107649    **    to be true.
107650    **
107651    **  rangeDiv:
107652    **    An estimate of a divisor by which to reduce the search space due
107653    **    to inequality constraints.  In the absence of sqlite_stat3 ANALYZE
107654    **    data, a single inequality reduces the search space to 1/4rd its
107655    **    original size (rangeDiv==4).  Two inequalities reduce the search
107656    **    space to 1/16th of its original size (rangeDiv==16).
107657    **
107658    **  bSort:
107659    **    Boolean. True if there is an ORDER BY clause that will require an
107660    **    external sort (i.e. scanning the index being evaluated will not
107661    **    correctly order records).
107662    **
107663    **  bDist:
107664    **    Boolean. True if there is a DISTINCT clause that will require an
107665    **    external btree.
107666    **
107667    **  bLookup:
107668    **    Boolean. True if a table lookup is required for each index entry
107669    **    visited.  In other words, true if this is not a covering index.
107670    **    This is always false for the rowid primary key index of a table.
107671    **    For other indexes, it is true unless all the columns of the table
107672    **    used by the SELECT statement are present in the index (such an
107673    **    index is sometimes described as a covering index).
107674    **    For example, given the index on (a, b), the second of the following
107675    **    two queries requires table b-tree lookups in order to find the value
107676    **    of column c, but the first does not because columns a and b are
107677    **    both available in the index.
107678    **
107679    **             SELECT a, b    FROM tbl WHERE a = 1;
107680    **             SELECT a, b, c FROM tbl WHERE a = 1;
107681    */
107682    int bInEst = 0;               /* True if "x IN (SELECT...)" seen */
107683    int nInMul = 1;               /* Number of distinct equalities to lookup */
107684    double rangeDiv = (double)1;  /* Estimated reduction in search space */
107685    int nBound = 0;               /* Number of range constraints seen */
107686    char bSort = bSortInit;       /* True if external sort required */
107687    char bDist = bDistInit;       /* True if index cannot help with DISTINCT */
107688    char bLookup = 0;             /* True if not a covering index */
107689    WhereTerm *pTerm;             /* A single term of the WHERE clause */
107690#ifdef SQLITE_ENABLE_STAT3
107691    WhereTerm *pFirstTerm = 0;    /* First term matching the index */
107692#endif
107693
107694    WHERETRACE((
107695      "   %s(%s):\n",
107696      pSrc->pTab->zName, (pIdx ? pIdx->zName : "ipk")
107697    ));
107698    memset(&pc, 0, sizeof(pc));
107699    pc.plan.nOBSat = nPriorSat;
107700
107701    /* Determine the values of pc.plan.nEq and nInMul */
107702    for(pc.plan.nEq=0; pc.plan.nEq<pProbe->nColumn; pc.plan.nEq++){
107703      int j = pProbe->aiColumn[pc.plan.nEq];
107704      pTerm = findTerm(pWC, iCur, j, p->notReady, eqTermMask, pIdx);
107705      if( pTerm==0 ) break;
107706      pc.plan.wsFlags |= (WHERE_COLUMN_EQ|WHERE_ROWID_EQ);
107707      testcase( pTerm->pWC!=pWC );
107708      if( pTerm->eOperator & WO_IN ){
107709        Expr *pExpr = pTerm->pExpr;
107710        pc.plan.wsFlags |= WHERE_COLUMN_IN;
107711        if( ExprHasProperty(pExpr, EP_xIsSelect) ){
107712          /* "x IN (SELECT ...)":  Assume the SELECT returns 25 rows */
107713          nInMul *= 25;
107714          bInEst = 1;
107715        }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
107716          /* "x IN (value, value, ...)" */
107717          nInMul *= pExpr->x.pList->nExpr;
107718        }
107719      }else if( pTerm->eOperator & WO_ISNULL ){
107720        pc.plan.wsFlags |= WHERE_COLUMN_NULL;
107721      }
107722#ifdef SQLITE_ENABLE_STAT3
107723      if( pc.plan.nEq==0 && pProbe->aSample ) pFirstTerm = pTerm;
107724#endif
107725      pc.used |= pTerm->prereqRight;
107726    }
107727
107728    /* If the index being considered is UNIQUE, and there is an equality
107729    ** constraint for all columns in the index, then this search will find
107730    ** at most a single row. In this case set the WHERE_UNIQUE flag to
107731    ** indicate this to the caller.
107732    **
107733    ** Otherwise, if the search may find more than one row, test to see if
107734    ** there is a range constraint on indexed column (pc.plan.nEq+1) that
107735    ** can be optimized using the index.
107736    */
107737    if( pc.plan.nEq==pProbe->nColumn && pProbe->onError!=OE_None ){
107738      testcase( pc.plan.wsFlags & WHERE_COLUMN_IN );
107739      testcase( pc.plan.wsFlags & WHERE_COLUMN_NULL );
107740      if( (pc.plan.wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0 ){
107741        pc.plan.wsFlags |= WHERE_UNIQUE;
107742        if( p->i==0 || (p->aLevel[p->i-1].plan.wsFlags & WHERE_ALL_UNIQUE)!=0 ){
107743          pc.plan.wsFlags |= WHERE_ALL_UNIQUE;
107744        }
107745      }
107746    }else if( pProbe->bUnordered==0 ){
107747      int j;
107748      j = (pc.plan.nEq==pProbe->nColumn ? -1 : pProbe->aiColumn[pc.plan.nEq]);
107749      if( findTerm(pWC, iCur, j, p->notReady, WO_LT|WO_LE|WO_GT|WO_GE, pIdx) ){
107750        WhereTerm *pTop, *pBtm;
107751        pTop = findTerm(pWC, iCur, j, p->notReady, WO_LT|WO_LE, pIdx);
107752        pBtm = findTerm(pWC, iCur, j, p->notReady, WO_GT|WO_GE, pIdx);
107753        whereRangeScanEst(pParse, pProbe, pc.plan.nEq, pBtm, pTop, &rangeDiv);
107754        if( pTop ){
107755          nBound = 1;
107756          pc.plan.wsFlags |= WHERE_TOP_LIMIT;
107757          pc.used |= pTop->prereqRight;
107758          testcase( pTop->pWC!=pWC );
107759        }
107760        if( pBtm ){
107761          nBound++;
107762          pc.plan.wsFlags |= WHERE_BTM_LIMIT;
107763          pc.used |= pBtm->prereqRight;
107764          testcase( pBtm->pWC!=pWC );
107765        }
107766        pc.plan.wsFlags |= (WHERE_COLUMN_RANGE|WHERE_ROWID_RANGE);
107767      }
107768    }
107769
107770    /* If there is an ORDER BY clause and the index being considered will
107771    ** naturally scan rows in the required order, set the appropriate flags
107772    ** in pc.plan.wsFlags. Otherwise, if there is an ORDER BY clause but
107773    ** the index will scan rows in a different order, set the bSort
107774    ** variable.  */
107775    if( bSort && (pSrc->jointype & JT_LEFT)==0 ){
107776      int bRev = 2;
107777      int bObUnique = 0;
107778      WHERETRACE(("      --> before isSortIndex: nPriorSat=%d\n",nPriorSat));
107779      pc.plan.nOBSat = isSortingIndex(p, pProbe, iCur, &bRev, &bObUnique);
107780      WHERETRACE(("      --> after  isSortIndex: bRev=%d bObU=%d nOBSat=%d\n",
107781                  bRev, bObUnique, pc.plan.nOBSat));
107782      if( nPriorSat<pc.plan.nOBSat || (pc.plan.wsFlags & WHERE_ALL_UNIQUE)!=0 ){
107783        pc.plan.wsFlags |= WHERE_ORDERED;
107784        if( bObUnique ) pc.plan.wsFlags |= WHERE_OB_UNIQUE;
107785      }
107786      if( nOrderBy==pc.plan.nOBSat ){
107787        bSort = 0;
107788        pc.plan.wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE;
107789      }
107790      if( bRev & 1 ) pc.plan.wsFlags |= WHERE_REVERSE;
107791    }
107792
107793    /* If there is a DISTINCT qualifier and this index will scan rows in
107794    ** order of the DISTINCT expressions, clear bDist and set the appropriate
107795    ** flags in pc.plan.wsFlags. */
107796    if( bDist
107797     && isDistinctIndex(pParse, pWC, pProbe, iCur, p->pDistinct, pc.plan.nEq)
107798     && (pc.plan.wsFlags & WHERE_COLUMN_IN)==0
107799    ){
107800      bDist = 0;
107801      pc.plan.wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_DISTINCT;
107802    }
107803
107804    /* If currently calculating the cost of using an index (not the IPK
107805    ** index), determine if all required column data may be obtained without
107806    ** using the main table (i.e. if the index is a covering
107807    ** index for this query). If it is, set the WHERE_IDX_ONLY flag in
107808    ** pc.plan.wsFlags. Otherwise, set the bLookup variable to true.  */
107809    if( pIdx ){
107810      Bitmask m = pSrc->colUsed;
107811      int j;
107812      for(j=0; j<pIdx->nColumn; j++){
107813        int x = pIdx->aiColumn[j];
107814        if( x<BMS-1 ){
107815          m &= ~(((Bitmask)1)<<x);
107816        }
107817      }
107818      if( m==0 ){
107819        pc.plan.wsFlags |= WHERE_IDX_ONLY;
107820      }else{
107821        bLookup = 1;
107822      }
107823    }
107824
107825    /*
107826    ** Estimate the number of rows of output.  For an "x IN (SELECT...)"
107827    ** constraint, do not let the estimate exceed half the rows in the table.
107828    */
107829    pc.plan.nRow = (double)(aiRowEst[pc.plan.nEq] * nInMul);
107830    if( bInEst && pc.plan.nRow*2>aiRowEst[0] ){
107831      pc.plan.nRow = aiRowEst[0]/2;
107832      nInMul = (int)(pc.plan.nRow / aiRowEst[pc.plan.nEq]);
107833    }
107834
107835#ifdef SQLITE_ENABLE_STAT3
107836    /* If the constraint is of the form x=VALUE or x IN (E1,E2,...)
107837    ** and we do not think that values of x are unique and if histogram
107838    ** data is available for column x, then it might be possible
107839    ** to get a better estimate on the number of rows based on
107840    ** VALUE and how common that value is according to the histogram.
107841    */
107842    if( pc.plan.nRow>(double)1 && pc.plan.nEq==1
107843     && pFirstTerm!=0 && aiRowEst[1]>1 ){
107844      assert( (pFirstTerm->eOperator & (WO_EQ|WO_ISNULL|WO_IN))!=0 );
107845      if( pFirstTerm->eOperator & (WO_EQ|WO_ISNULL) ){
107846        testcase( pFirstTerm->eOperator & WO_EQ );
107847        testcase( pFirstTerm->eOperator & WO_EQUIV );
107848        testcase( pFirstTerm->eOperator & WO_ISNULL );
107849        whereEqualScanEst(pParse, pProbe, pFirstTerm->pExpr->pRight,
107850                          &pc.plan.nRow);
107851      }else if( bInEst==0 ){
107852        assert( pFirstTerm->eOperator & WO_IN );
107853        whereInScanEst(pParse, pProbe, pFirstTerm->pExpr->x.pList,
107854                       &pc.plan.nRow);
107855      }
107856    }
107857#endif /* SQLITE_ENABLE_STAT3 */
107858
107859    /* Adjust the number of output rows and downward to reflect rows
107860    ** that are excluded by range constraints.
107861    */
107862    pc.plan.nRow = pc.plan.nRow/rangeDiv;
107863    if( pc.plan.nRow<1 ) pc.plan.nRow = 1;
107864
107865    /* Experiments run on real SQLite databases show that the time needed
107866    ** to do a binary search to locate a row in a table or index is roughly
107867    ** log10(N) times the time to move from one row to the next row within
107868    ** a table or index.  The actual times can vary, with the size of
107869    ** records being an important factor.  Both moves and searches are
107870    ** slower with larger records, presumably because fewer records fit
107871    ** on one page and hence more pages have to be fetched.
107872    **
107873    ** The ANALYZE command and the sqlite_stat1 and sqlite_stat3 tables do
107874    ** not give us data on the relative sizes of table and index records.
107875    ** So this computation assumes table records are about twice as big
107876    ** as index records
107877    */
107878    if( (pc.plan.wsFlags&~(WHERE_REVERSE|WHERE_ORDERED|WHERE_OB_UNIQUE))
107879                                                              ==WHERE_IDX_ONLY
107880     && (pWC->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
107881     && sqlite3GlobalConfig.bUseCis
107882     && OptimizationEnabled(pParse->db, SQLITE_CoverIdxScan)
107883    ){
107884      /* This index is not useful for indexing, but it is a covering index.
107885      ** A full-scan of the index might be a little faster than a full-scan
107886      ** of the table, so give this case a cost slightly less than a table
107887      ** scan. */
107888      pc.rCost = aiRowEst[0]*3 + pProbe->nColumn;
107889      pc.plan.wsFlags |= WHERE_COVER_SCAN|WHERE_COLUMN_RANGE;
107890    }else if( (pc.plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ){
107891      /* The cost of a full table scan is a number of move operations equal
107892      ** to the number of rows in the table.
107893      **
107894      ** We add an additional 4x penalty to full table scans.  This causes
107895      ** the cost function to err on the side of choosing an index over
107896      ** choosing a full scan.  This 4x full-scan penalty is an arguable
107897      ** decision and one which we expect to revisit in the future.  But
107898      ** it seems to be working well enough at the moment.
107899      */
107900      pc.rCost = aiRowEst[0]*4;
107901      pc.plan.wsFlags &= ~WHERE_IDX_ONLY;
107902      if( pIdx ){
107903        pc.plan.wsFlags &= ~WHERE_ORDERED;
107904        pc.plan.nOBSat = nPriorSat;
107905      }
107906    }else{
107907      log10N = estLog(aiRowEst[0]);
107908      pc.rCost = pc.plan.nRow;
107909      if( pIdx ){
107910        if( bLookup ){
107911          /* For an index lookup followed by a table lookup:
107912          **    nInMul index searches to find the start of each index range
107913          **  + nRow steps through the index
107914          **  + nRow table searches to lookup the table entry using the rowid
107915          */
107916          pc.rCost += (nInMul + pc.plan.nRow)*log10N;
107917        }else{
107918          /* For a covering index:
107919          **     nInMul index searches to find the initial entry
107920          **   + nRow steps through the index
107921          */
107922          pc.rCost += nInMul*log10N;
107923        }
107924      }else{
107925        /* For a rowid primary key lookup:
107926        **    nInMult table searches to find the initial entry for each range
107927        **  + nRow steps through the table
107928        */
107929        pc.rCost += nInMul*log10N;
107930      }
107931    }
107932
107933    /* Add in the estimated cost of sorting the result.  Actual experimental
107934    ** measurements of sorting performance in SQLite show that sorting time
107935    ** adds C*N*log10(N) to the cost, where N is the number of rows to be
107936    ** sorted and C is a factor between 1.95 and 4.3.  We will split the
107937    ** difference and select C of 3.0.
107938    */
107939    if( bSort ){
107940      double m = estLog(pc.plan.nRow*(nOrderBy - pc.plan.nOBSat)/nOrderBy);
107941      m *= (double)(pc.plan.nOBSat ? 2 : 3);
107942      pc.rCost += pc.plan.nRow*m;
107943    }
107944    if( bDist ){
107945      pc.rCost += pc.plan.nRow*estLog(pc.plan.nRow)*3;
107946    }
107947
107948    /**** Cost of using this index has now been computed ****/
107949
107950    /* If there are additional constraints on this table that cannot
107951    ** be used with the current index, but which might lower the number
107952    ** of output rows, adjust the nRow value accordingly.  This only
107953    ** matters if the current index is the least costly, so do not bother
107954    ** with this step if we already know this index will not be chosen.
107955    ** Also, never reduce the output row count below 2 using this step.
107956    **
107957    ** It is critical that the notValid mask be used here instead of
107958    ** the notReady mask.  When computing an "optimal" index, the notReady
107959    ** mask will only have one bit set - the bit for the current table.
107960    ** The notValid mask, on the other hand, always has all bits set for
107961    ** tables that are not in outer loops.  If notReady is used here instead
107962    ** of notValid, then a optimal index that depends on inner joins loops
107963    ** might be selected even when there exists an optimal index that has
107964    ** no such dependency.
107965    */
107966    if( pc.plan.nRow>2 && pc.rCost<=p->cost.rCost ){
107967      int k;                       /* Loop counter */
107968      int nSkipEq = pc.plan.nEq;   /* Number of == constraints to skip */
107969      int nSkipRange = nBound;     /* Number of < constraints to skip */
107970      Bitmask thisTab;             /* Bitmap for pSrc */
107971
107972      thisTab = getMask(pWC->pMaskSet, iCur);
107973      for(pTerm=pWC->a, k=pWC->nTerm; pc.plan.nRow>2 && k; k--, pTerm++){
107974        if( pTerm->wtFlags & TERM_VIRTUAL ) continue;
107975        if( (pTerm->prereqAll & p->notValid)!=thisTab ) continue;
107976        if( pTerm->eOperator & (WO_EQ|WO_IN|WO_ISNULL) ){
107977          if( nSkipEq ){
107978            /* Ignore the first pc.plan.nEq equality matches since the index
107979            ** has already accounted for these */
107980            nSkipEq--;
107981          }else{
107982            /* Assume each additional equality match reduces the result
107983            ** set size by a factor of 10 */
107984            pc.plan.nRow /= 10;
107985          }
107986        }else if( pTerm->eOperator & (WO_LT|WO_LE|WO_GT|WO_GE) ){
107987          if( nSkipRange ){
107988            /* Ignore the first nSkipRange range constraints since the index
107989            ** has already accounted for these */
107990            nSkipRange--;
107991          }else{
107992            /* Assume each additional range constraint reduces the result
107993            ** set size by a factor of 3.  Indexed range constraints reduce
107994            ** the search space by a larger factor: 4.  We make indexed range
107995            ** more selective intentionally because of the subjective
107996            ** observation that indexed range constraints really are more
107997            ** selective in practice, on average. */
107998            pc.plan.nRow /= 3;
107999          }
108000        }else if( (pTerm->eOperator & WO_NOOP)==0 ){
108001          /* Any other expression lowers the output row count by half */
108002          pc.plan.nRow /= 2;
108003        }
108004      }
108005      if( pc.plan.nRow<2 ) pc.plan.nRow = 2;
108006    }
108007
108008
108009    WHERETRACE((
108010      "      nEq=%d nInMul=%d rangeDiv=%d bSort=%d bLookup=%d wsFlags=0x%08x\n"
108011      "      notReady=0x%llx log10N=%.1f nRow=%.1f cost=%.1f\n"
108012      "      used=0x%llx nOBSat=%d\n",
108013      pc.plan.nEq, nInMul, (int)rangeDiv, bSort, bLookup, pc.plan.wsFlags,
108014      p->notReady, log10N, pc.plan.nRow, pc.rCost, pc.used,
108015      pc.plan.nOBSat
108016    ));
108017
108018    /* If this index is the best we have seen so far, then record this
108019    ** index and its cost in the p->cost structure.
108020    */
108021    if( (!pIdx || pc.plan.wsFlags) && compareCost(&pc, &p->cost) ){
108022      p->cost = pc;
108023      p->cost.plan.wsFlags &= wsFlagMask;
108024      p->cost.plan.u.pIdx = pIdx;
108025    }
108026
108027    /* If there was an INDEXED BY clause, then only that one index is
108028    ** considered. */
108029    if( pSrc->pIndex ) break;
108030
108031    /* Reset masks for the next index in the loop */
108032    wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
108033    eqTermMask = idxEqTermMask;
108034  }
108035
108036  /* If there is no ORDER BY clause and the SQLITE_ReverseOrder flag
108037  ** is set, then reverse the order that the index will be scanned
108038  ** in. This is used for application testing, to help find cases
108039  ** where application behavior depends on the (undefined) order that
108040  ** SQLite outputs rows in in the absence of an ORDER BY clause.  */
108041  if( !p->pOrderBy && pParse->db->flags & SQLITE_ReverseOrder ){
108042    p->cost.plan.wsFlags |= WHERE_REVERSE;
108043  }
108044
108045  assert( p->pOrderBy || (p->cost.plan.wsFlags&WHERE_ORDERED)==0 );
108046  assert( p->cost.plan.u.pIdx==0 || (p->cost.plan.wsFlags&WHERE_ROWID_EQ)==0 );
108047  assert( pSrc->pIndex==0
108048       || p->cost.plan.u.pIdx==0
108049       || p->cost.plan.u.pIdx==pSrc->pIndex
108050  );
108051
108052  WHERETRACE(("   best index is %s cost=%.1f\n",
108053         p->cost.plan.u.pIdx ? p->cost.plan.u.pIdx->zName : "ipk",
108054         p->cost.rCost));
108055
108056  bestOrClauseIndex(p);
108057  bestAutomaticIndex(p);
108058  p->cost.plan.wsFlags |= eqTermMask;
108059}
108060
108061/*
108062** Find the query plan for accessing table pSrc->pTab. Write the
108063** best query plan and its cost into the WhereCost object supplied
108064** as the last parameter. This function may calculate the cost of
108065** both real and virtual table scans.
108066**
108067** This function does not take ORDER BY or DISTINCT into account.  Nor
108068** does it remember the virtual table query plan.  All it does is compute
108069** the cost while determining if an OR optimization is applicable.  The
108070** details will be reconsidered later if the optimization is found to be
108071** applicable.
108072*/
108073static void bestIndex(WhereBestIdx *p){
108074#ifndef SQLITE_OMIT_VIRTUALTABLE
108075  if( IsVirtual(p->pSrc->pTab) ){
108076    sqlite3_index_info *pIdxInfo = 0;
108077    p->ppIdxInfo = &pIdxInfo;
108078    bestVirtualIndex(p);
108079    assert( pIdxInfo!=0 || p->pParse->db->mallocFailed );
108080    if( pIdxInfo && pIdxInfo->needToFreeIdxStr ){
108081      sqlite3_free(pIdxInfo->idxStr);
108082    }
108083    sqlite3DbFree(p->pParse->db, pIdxInfo);
108084  }else
108085#endif
108086  {
108087    bestBtreeIndex(p);
108088  }
108089}
108090
108091/*
108092** Disable a term in the WHERE clause.  Except, do not disable the term
108093** if it controls a LEFT OUTER JOIN and it did not originate in the ON
108094** or USING clause of that join.
108095**
108096** Consider the term t2.z='ok' in the following queries:
108097**
108098**   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
108099**   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
108100**   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
108101**
108102** The t2.z='ok' is disabled in the in (2) because it originates
108103** in the ON clause.  The term is disabled in (3) because it is not part
108104** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
108105**
108106** IMPLEMENTATION-OF: R-24597-58655 No tests are done for terms that are
108107** completely satisfied by indices.
108108**
108109** Disabling a term causes that term to not be tested in the inner loop
108110** of the join.  Disabling is an optimization.  When terms are satisfied
108111** by indices, we disable them to prevent redundant tests in the inner
108112** loop.  We would get the correct results if nothing were ever disabled,
108113** but joins might run a little slower.  The trick is to disable as much
108114** as we can without disabling too much.  If we disabled in (1), we'd get
108115** the wrong answer.  See ticket #813.
108116*/
108117static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
108118  if( pTerm
108119      && (pTerm->wtFlags & TERM_CODED)==0
108120      && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
108121  ){
108122    pTerm->wtFlags |= TERM_CODED;
108123    if( pTerm->iParent>=0 ){
108124      WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
108125      if( (--pOther->nChild)==0 ){
108126        disableTerm(pLevel, pOther);
108127      }
108128    }
108129  }
108130}
108131
108132/*
108133** Code an OP_Affinity opcode to apply the column affinity string zAff
108134** to the n registers starting at base.
108135**
108136** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
108137** beginning and end of zAff are ignored.  If all entries in zAff are
108138** SQLITE_AFF_NONE, then no code gets generated.
108139**
108140** This routine makes its own copy of zAff so that the caller is free
108141** to modify zAff after this routine returns.
108142*/
108143static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
108144  Vdbe *v = pParse->pVdbe;
108145  if( zAff==0 ){
108146    assert( pParse->db->mallocFailed );
108147    return;
108148  }
108149  assert( v!=0 );
108150
108151  /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
108152  ** and end of the affinity string.
108153  */
108154  while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
108155    n--;
108156    base++;
108157    zAff++;
108158  }
108159  while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
108160    n--;
108161  }
108162
108163  /* Code the OP_Affinity opcode if there is anything left to do. */
108164  if( n>0 ){
108165    sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
108166    sqlite3VdbeChangeP4(v, -1, zAff, n);
108167    sqlite3ExprCacheAffinityChange(pParse, base, n);
108168  }
108169}
108170
108171
108172/*
108173** Generate code for a single equality term of the WHERE clause.  An equality
108174** term can be either X=expr or X IN (...).   pTerm is the term to be
108175** coded.
108176**
108177** The current value for the constraint is left in register iReg.
108178**
108179** For a constraint of the form X=expr, the expression is evaluated and its
108180** result is left on the stack.  For constraints of the form X IN (...)
108181** this routine sets up a loop that will iterate over all values of X.
108182*/
108183static int codeEqualityTerm(
108184  Parse *pParse,      /* The parsing context */
108185  WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
108186  WhereLevel *pLevel, /* The level of the FROM clause we are working on */
108187  int iEq,            /* Index of the equality term within this level */
108188  int iTarget         /* Attempt to leave results in this register */
108189){
108190  Expr *pX = pTerm->pExpr;
108191  Vdbe *v = pParse->pVdbe;
108192  int iReg;                  /* Register holding results */
108193
108194  assert( iTarget>0 );
108195  if( pX->op==TK_EQ ){
108196    iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
108197  }else if( pX->op==TK_ISNULL ){
108198    iReg = iTarget;
108199    sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
108200#ifndef SQLITE_OMIT_SUBQUERY
108201  }else{
108202    int eType;
108203    int iTab;
108204    struct InLoop *pIn;
108205    u8 bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
108206
108207    if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0
108208      && pLevel->plan.u.pIdx->aSortOrder[iEq]
108209    ){
108210      testcase( iEq==0 );
108211      testcase( iEq==pLevel->plan.u.pIdx->nColumn-1 );
108212      testcase( iEq>0 && iEq+1<pLevel->plan.u.pIdx->nColumn );
108213      testcase( bRev );
108214      bRev = !bRev;
108215    }
108216    assert( pX->op==TK_IN );
108217    iReg = iTarget;
108218    eType = sqlite3FindInIndex(pParse, pX, 0);
108219    if( eType==IN_INDEX_INDEX_DESC ){
108220      testcase( bRev );
108221      bRev = !bRev;
108222    }
108223    iTab = pX->iTable;
108224    sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
108225    assert( pLevel->plan.wsFlags & WHERE_IN_ABLE );
108226    if( pLevel->u.in.nIn==0 ){
108227      pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
108228    }
108229    pLevel->u.in.nIn++;
108230    pLevel->u.in.aInLoop =
108231       sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
108232                              sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
108233    pIn = pLevel->u.in.aInLoop;
108234    if( pIn ){
108235      pIn += pLevel->u.in.nIn - 1;
108236      pIn->iCur = iTab;
108237      if( eType==IN_INDEX_ROWID ){
108238        pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
108239      }else{
108240        pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
108241      }
108242      pIn->eEndLoopOp = bRev ? OP_Prev : OP_Next;
108243      sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
108244    }else{
108245      pLevel->u.in.nIn = 0;
108246    }
108247#endif
108248  }
108249  disableTerm(pLevel, pTerm);
108250  return iReg;
108251}
108252
108253/*
108254** Generate code that will evaluate all == and IN constraints for an
108255** index.
108256**
108257** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
108258** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
108259** The index has as many as three equality constraints, but in this
108260** example, the third "c" value is an inequality.  So only two
108261** constraints are coded.  This routine will generate code to evaluate
108262** a==5 and b IN (1,2,3).  The current values for a and b will be stored
108263** in consecutive registers and the index of the first register is returned.
108264**
108265** In the example above nEq==2.  But this subroutine works for any value
108266** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
108267** The only thing it does is allocate the pLevel->iMem memory cell and
108268** compute the affinity string.
108269**
108270** This routine always allocates at least one memory cell and returns
108271** the index of that memory cell. The code that
108272** calls this routine will use that memory cell to store the termination
108273** key value of the loop.  If one or more IN operators appear, then
108274** this routine allocates an additional nEq memory cells for internal
108275** use.
108276**
108277** Before returning, *pzAff is set to point to a buffer containing a
108278** copy of the column affinity string of the index allocated using
108279** sqlite3DbMalloc(). Except, entries in the copy of the string associated
108280** with equality constraints that use NONE affinity are set to
108281** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
108282**
108283**   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
108284**   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
108285**
108286** In the example above, the index on t1(a) has TEXT affinity. But since
108287** the right hand side of the equality constraint (t2.b) has NONE affinity,
108288** no conversion should be attempted before using a t2.b value as part of
108289** a key to search the index. Hence the first byte in the returned affinity
108290** string in this example would be set to SQLITE_AFF_NONE.
108291*/
108292static int codeAllEqualityTerms(
108293  Parse *pParse,        /* Parsing context */
108294  WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
108295  WhereClause *pWC,     /* The WHERE clause */
108296  Bitmask notReady,     /* Which parts of FROM have not yet been coded */
108297  int nExtraReg,        /* Number of extra registers to allocate */
108298  char **pzAff          /* OUT: Set to point to affinity string */
108299){
108300  int nEq = pLevel->plan.nEq;   /* The number of == or IN constraints to code */
108301  Vdbe *v = pParse->pVdbe;      /* The vm under construction */
108302  Index *pIdx;                  /* The index being used for this loop */
108303  int iCur = pLevel->iTabCur;   /* The cursor of the table */
108304  WhereTerm *pTerm;             /* A single constraint term */
108305  int j;                        /* Loop counter */
108306  int regBase;                  /* Base register */
108307  int nReg;                     /* Number of registers to allocate */
108308  char *zAff;                   /* Affinity string to return */
108309
108310  /* This module is only called on query plans that use an index. */
108311  assert( pLevel->plan.wsFlags & WHERE_INDEXED );
108312  pIdx = pLevel->plan.u.pIdx;
108313
108314  /* Figure out how many memory cells we will need then allocate them.
108315  */
108316  regBase = pParse->nMem + 1;
108317  nReg = pLevel->plan.nEq + nExtraReg;
108318  pParse->nMem += nReg;
108319
108320  zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
108321  if( !zAff ){
108322    pParse->db->mallocFailed = 1;
108323  }
108324
108325  /* Evaluate the equality constraints
108326  */
108327  assert( pIdx->nColumn>=nEq );
108328  for(j=0; j<nEq; j++){
108329    int r1;
108330    int k = pIdx->aiColumn[j];
108331    pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx);
108332    if( pTerm==0 ) break;
108333    /* The following true for indices with redundant columns.
108334    ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
108335    testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
108336    testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
108337    r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, regBase+j);
108338    if( r1!=regBase+j ){
108339      if( nReg==1 ){
108340        sqlite3ReleaseTempReg(pParse, regBase);
108341        regBase = r1;
108342      }else{
108343        sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
108344      }
108345    }
108346    testcase( pTerm->eOperator & WO_ISNULL );
108347    testcase( pTerm->eOperator & WO_IN );
108348    if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
108349      Expr *pRight = pTerm->pExpr->pRight;
108350      sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
108351      if( zAff ){
108352        if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
108353          zAff[j] = SQLITE_AFF_NONE;
108354        }
108355        if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
108356          zAff[j] = SQLITE_AFF_NONE;
108357        }
108358      }
108359    }
108360  }
108361  *pzAff = zAff;
108362  return regBase;
108363}
108364
108365#ifndef SQLITE_OMIT_EXPLAIN
108366/*
108367** This routine is a helper for explainIndexRange() below
108368**
108369** pStr holds the text of an expression that we are building up one term
108370** at a time.  This routine adds a new term to the end of the expression.
108371** Terms are separated by AND so add the "AND" text for second and subsequent
108372** terms only.
108373*/
108374static void explainAppendTerm(
108375  StrAccum *pStr,             /* The text expression being built */
108376  int iTerm,                  /* Index of this term.  First is zero */
108377  const char *zColumn,        /* Name of the column */
108378  const char *zOp             /* Name of the operator */
108379){
108380  if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
108381  sqlite3StrAccumAppend(pStr, zColumn, -1);
108382  sqlite3StrAccumAppend(pStr, zOp, 1);
108383  sqlite3StrAccumAppend(pStr, "?", 1);
108384}
108385
108386/*
108387** Argument pLevel describes a strategy for scanning table pTab. This
108388** function returns a pointer to a string buffer containing a description
108389** of the subset of table rows scanned by the strategy in the form of an
108390** SQL expression. Or, if all rows are scanned, NULL is returned.
108391**
108392** For example, if the query:
108393**
108394**   SELECT * FROM t1 WHERE a=1 AND b>2;
108395**
108396** is run and there is an index on (a, b), then this function returns a
108397** string similar to:
108398**
108399**   "a=? AND b>?"
108400**
108401** The returned pointer points to memory obtained from sqlite3DbMalloc().
108402** It is the responsibility of the caller to free the buffer when it is
108403** no longer required.
108404*/
108405static char *explainIndexRange(sqlite3 *db, WhereLevel *pLevel, Table *pTab){
108406  WherePlan *pPlan = &pLevel->plan;
108407  Index *pIndex = pPlan->u.pIdx;
108408  int nEq = pPlan->nEq;
108409  int i, j;
108410  Column *aCol = pTab->aCol;
108411  int *aiColumn = pIndex->aiColumn;
108412  StrAccum txt;
108413
108414  if( nEq==0 && (pPlan->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
108415    return 0;
108416  }
108417  sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
108418  txt.db = db;
108419  sqlite3StrAccumAppend(&txt, " (", 2);
108420  for(i=0; i<nEq; i++){
108421    explainAppendTerm(&txt, i, aCol[aiColumn[i]].zName, "=");
108422  }
108423
108424  j = i;
108425  if( pPlan->wsFlags&WHERE_BTM_LIMIT ){
108426    char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
108427    explainAppendTerm(&txt, i++, z, ">");
108428  }
108429  if( pPlan->wsFlags&WHERE_TOP_LIMIT ){
108430    char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
108431    explainAppendTerm(&txt, i, z, "<");
108432  }
108433  sqlite3StrAccumAppend(&txt, ")", 1);
108434  return sqlite3StrAccumFinish(&txt);
108435}
108436
108437/*
108438** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
108439** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
108440** record is added to the output to describe the table scan strategy in
108441** pLevel.
108442*/
108443static void explainOneScan(
108444  Parse *pParse,                  /* Parse context */
108445  SrcList *pTabList,              /* Table list this loop refers to */
108446  WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
108447  int iLevel,                     /* Value for "level" column of output */
108448  int iFrom,                      /* Value for "from" column of output */
108449  u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
108450){
108451  if( pParse->explain==2 ){
108452    u32 flags = pLevel->plan.wsFlags;
108453    struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
108454    Vdbe *v = pParse->pVdbe;      /* VM being constructed */
108455    sqlite3 *db = pParse->db;     /* Database handle */
108456    char *zMsg;                   /* Text to add to EQP output */
108457    sqlite3_int64 nRow;           /* Expected number of rows visited by scan */
108458    int iId = pParse->iSelectId;  /* Select id (left-most output column) */
108459    int isSearch;                 /* True for a SEARCH. False for SCAN. */
108460
108461    if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
108462
108463    isSearch = (pLevel->plan.nEq>0)
108464             || (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
108465             || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
108466
108467    zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
108468    if( pItem->pSelect ){
108469      zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
108470    }else{
108471      zMsg = sqlite3MAppendf(db, zMsg, "%s TABLE %s", zMsg, pItem->zName);
108472    }
108473
108474    if( pItem->zAlias ){
108475      zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
108476    }
108477    if( (flags & WHERE_INDEXED)!=0 ){
108478      char *zWhere = explainIndexRange(db, pLevel, pItem->pTab);
108479      zMsg = sqlite3MAppendf(db, zMsg, "%s USING %s%sINDEX%s%s%s", zMsg,
108480          ((flags & WHERE_TEMP_INDEX)?"AUTOMATIC ":""),
108481          ((flags & WHERE_IDX_ONLY)?"COVERING ":""),
108482          ((flags & WHERE_TEMP_INDEX)?"":" "),
108483          ((flags & WHERE_TEMP_INDEX)?"": pLevel->plan.u.pIdx->zName),
108484          zWhere
108485      );
108486      sqlite3DbFree(db, zWhere);
108487    }else if( flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
108488      zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
108489
108490      if( flags&WHERE_ROWID_EQ ){
108491        zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
108492      }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
108493        zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
108494      }else if( flags&WHERE_BTM_LIMIT ){
108495        zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
108496      }else if( flags&WHERE_TOP_LIMIT ){
108497        zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
108498      }
108499    }
108500#ifndef SQLITE_OMIT_VIRTUALTABLE
108501    else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
108502      sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
108503      zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
108504                  pVtabIdx->idxNum, pVtabIdx->idxStr);
108505    }
108506#endif
108507    if( wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX) ){
108508      testcase( wctrlFlags & WHERE_ORDERBY_MIN );
108509      nRow = 1;
108510    }else{
108511      nRow = (sqlite3_int64)pLevel->plan.nRow;
108512    }
108513    zMsg = sqlite3MAppendf(db, zMsg, "%s (~%lld rows)", zMsg, nRow);
108514    sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
108515  }
108516}
108517#else
108518# define explainOneScan(u,v,w,x,y,z)
108519#endif /* SQLITE_OMIT_EXPLAIN */
108520
108521
108522/*
108523** Generate code for the start of the iLevel-th loop in the WHERE clause
108524** implementation described by pWInfo.
108525*/
108526static Bitmask codeOneLoopStart(
108527  WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
108528  int iLevel,          /* Which level of pWInfo->a[] should be coded */
108529  u16 wctrlFlags,      /* One of the WHERE_* flags defined in sqliteInt.h */
108530  Bitmask notReady     /* Which tables are currently available */
108531){
108532  int j, k;            /* Loop counters */
108533  int iCur;            /* The VDBE cursor for the table */
108534  int addrNxt;         /* Where to jump to continue with the next IN case */
108535  int omitTable;       /* True if we use the index only */
108536  int bRev;            /* True if we need to scan in reverse order */
108537  WhereLevel *pLevel;  /* The where level to be coded */
108538  WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
108539  WhereTerm *pTerm;               /* A WHERE clause term */
108540  Parse *pParse;                  /* Parsing context */
108541  Vdbe *v;                        /* The prepared stmt under constructions */
108542  struct SrcList_item *pTabItem;  /* FROM clause term being coded */
108543  int addrBrk;                    /* Jump here to break out of the loop */
108544  int addrCont;                   /* Jump here to continue with next cycle */
108545  int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
108546  int iReleaseReg = 0;      /* Temp register to free before returning */
108547  Bitmask newNotReady;      /* Return value */
108548
108549  pParse = pWInfo->pParse;
108550  v = pParse->pVdbe;
108551  pWC = pWInfo->pWC;
108552  pLevel = &pWInfo->a[iLevel];
108553  pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
108554  iCur = pTabItem->iCursor;
108555  bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
108556  omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0
108557           && (wctrlFlags & WHERE_FORCE_TABLE)==0;
108558  VdbeNoopComment((v, "Begin Join Loop %d", iLevel));
108559
108560  /* Create labels for the "break" and "continue" instructions
108561  ** for the current loop.  Jump to addrBrk to break out of a loop.
108562  ** Jump to cont to go immediately to the next iteration of the
108563  ** loop.
108564  **
108565  ** When there is an IN operator, we also have a "addrNxt" label that
108566  ** means to continue with the next IN value combination.  When
108567  ** there are no IN operators in the constraints, the "addrNxt" label
108568  ** is the same as "addrBrk".
108569  */
108570  addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
108571  addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
108572
108573  /* If this is the right table of a LEFT OUTER JOIN, allocate and
108574  ** initialize a memory cell that records if this table matches any
108575  ** row of the left table of the join.
108576  */
108577  if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
108578    pLevel->iLeftJoin = ++pParse->nMem;
108579    sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
108580    VdbeComment((v, "init LEFT JOIN no-match flag"));
108581  }
108582
108583  /* Special case of a FROM clause subquery implemented as a co-routine */
108584  if( pTabItem->viaCoroutine ){
108585    int regYield = pTabItem->regReturn;
108586    sqlite3VdbeAddOp2(v, OP_Integer, pTabItem->addrFillSub-1, regYield);
108587    pLevel->p2 =  sqlite3VdbeAddOp1(v, OP_Yield, regYield);
108588    VdbeComment((v, "next row of co-routine %s", pTabItem->pTab->zName));
108589    sqlite3VdbeAddOp2(v, OP_If, regYield+1, addrBrk);
108590    pLevel->op = OP_Goto;
108591  }else
108592
108593#ifndef SQLITE_OMIT_VIRTUALTABLE
108594  if(  (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
108595    /* Case 0:  The table is a virtual-table.  Use the VFilter and VNext
108596    **          to access the data.
108597    */
108598    int iReg;   /* P3 Value for OP_VFilter */
108599    int addrNotFound;
108600    sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
108601    int nConstraint = pVtabIdx->nConstraint;
108602    struct sqlite3_index_constraint_usage *aUsage =
108603                                                pVtabIdx->aConstraintUsage;
108604    const struct sqlite3_index_constraint *aConstraint =
108605                                                pVtabIdx->aConstraint;
108606
108607    sqlite3ExprCachePush(pParse);
108608    iReg = sqlite3GetTempRange(pParse, nConstraint+2);
108609    addrNotFound = pLevel->addrBrk;
108610    for(j=1; j<=nConstraint; j++){
108611      for(k=0; k<nConstraint; k++){
108612        if( aUsage[k].argvIndex==j ){
108613          int iTarget = iReg+j+1;
108614          pTerm = &pWC->a[aConstraint[k].iTermOffset];
108615          if( pTerm->eOperator & WO_IN ){
108616            codeEqualityTerm(pParse, pTerm, pLevel, k, iTarget);
108617            addrNotFound = pLevel->addrNxt;
108618          }else{
108619            sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
108620          }
108621          break;
108622        }
108623      }
108624      if( k==nConstraint ) break;
108625    }
108626    sqlite3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg);
108627    sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
108628    sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg, pVtabIdx->idxStr,
108629                      pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
108630    pVtabIdx->needToFreeIdxStr = 0;
108631    for(j=0; j<nConstraint; j++){
108632      if( aUsage[j].omit ){
108633        int iTerm = aConstraint[j].iTermOffset;
108634        disableTerm(pLevel, &pWC->a[iTerm]);
108635      }
108636    }
108637    pLevel->op = OP_VNext;
108638    pLevel->p1 = iCur;
108639    pLevel->p2 = sqlite3VdbeCurrentAddr(v);
108640    sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
108641    sqlite3ExprCachePop(pParse, 1);
108642  }else
108643#endif /* SQLITE_OMIT_VIRTUALTABLE */
108644
108645  if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){
108646    /* Case 1:  We can directly reference a single row using an
108647    **          equality comparison against the ROWID field.  Or
108648    **          we reference multiple rows using a "rowid IN (...)"
108649    **          construct.
108650    */
108651    iReleaseReg = sqlite3GetTempReg(pParse);
108652    pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
108653    assert( pTerm!=0 );
108654    assert( pTerm->pExpr!=0 );
108655    assert( omitTable==0 );
108656    testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
108657    iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, iReleaseReg);
108658    addrNxt = pLevel->addrNxt;
108659    sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
108660    sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
108661    sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
108662    sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
108663    VdbeComment((v, "pk"));
108664    pLevel->op = OP_Noop;
108665  }else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){
108666    /* Case 2:  We have an inequality comparison against the ROWID field.
108667    */
108668    int testOp = OP_Noop;
108669    int start;
108670    int memEndValue = 0;
108671    WhereTerm *pStart, *pEnd;
108672
108673    assert( omitTable==0 );
108674    pStart = findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0);
108675    pEnd = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0);
108676    if( bRev ){
108677      pTerm = pStart;
108678      pStart = pEnd;
108679      pEnd = pTerm;
108680    }
108681    if( pStart ){
108682      Expr *pX;             /* The expression that defines the start bound */
108683      int r1, rTemp;        /* Registers for holding the start boundary */
108684
108685      /* The following constant maps TK_xx codes into corresponding
108686      ** seek opcodes.  It depends on a particular ordering of TK_xx
108687      */
108688      const u8 aMoveOp[] = {
108689           /* TK_GT */  OP_SeekGt,
108690           /* TK_LE */  OP_SeekLe,
108691           /* TK_LT */  OP_SeekLt,
108692           /* TK_GE */  OP_SeekGe
108693      };
108694      assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
108695      assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
108696      assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
108697
108698      testcase( pStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
108699      pX = pStart->pExpr;
108700      assert( pX!=0 );
108701      assert( pStart->leftCursor==iCur );
108702      r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
108703      sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
108704      VdbeComment((v, "pk"));
108705      sqlite3ExprCacheAffinityChange(pParse, r1, 1);
108706      sqlite3ReleaseTempReg(pParse, rTemp);
108707      disableTerm(pLevel, pStart);
108708    }else{
108709      sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
108710    }
108711    if( pEnd ){
108712      Expr *pX;
108713      pX = pEnd->pExpr;
108714      assert( pX!=0 );
108715      assert( pEnd->leftCursor==iCur );
108716      testcase( pEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
108717      memEndValue = ++pParse->nMem;
108718      sqlite3ExprCode(pParse, pX->pRight, memEndValue);
108719      if( pX->op==TK_LT || pX->op==TK_GT ){
108720        testOp = bRev ? OP_Le : OP_Ge;
108721      }else{
108722        testOp = bRev ? OP_Lt : OP_Gt;
108723      }
108724      disableTerm(pLevel, pEnd);
108725    }
108726    start = sqlite3VdbeCurrentAddr(v);
108727    pLevel->op = bRev ? OP_Prev : OP_Next;
108728    pLevel->p1 = iCur;
108729    pLevel->p2 = start;
108730    if( pStart==0 && pEnd==0 ){
108731      pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
108732    }else{
108733      assert( pLevel->p5==0 );
108734    }
108735    if( testOp!=OP_Noop ){
108736      iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
108737      sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
108738      sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
108739      sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
108740      sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
108741    }
108742  }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
108743    /* Case 3: A scan using an index.
108744    **
108745    **         The WHERE clause may contain zero or more equality
108746    **         terms ("==" or "IN" operators) that refer to the N
108747    **         left-most columns of the index. It may also contain
108748    **         inequality constraints (>, <, >= or <=) on the indexed
108749    **         column that immediately follows the N equalities. Only
108750    **         the right-most column can be an inequality - the rest must
108751    **         use the "==" and "IN" operators. For example, if the
108752    **         index is on (x,y,z), then the following clauses are all
108753    **         optimized:
108754    **
108755    **            x=5
108756    **            x=5 AND y=10
108757    **            x=5 AND y<10
108758    **            x=5 AND y>5 AND y<10
108759    **            x=5 AND y=5 AND z<=10
108760    **
108761    **         The z<10 term of the following cannot be used, only
108762    **         the x=5 term:
108763    **
108764    **            x=5 AND z<10
108765    **
108766    **         N may be zero if there are inequality constraints.
108767    **         If there are no inequality constraints, then N is at
108768    **         least one.
108769    **
108770    **         This case is also used when there are no WHERE clause
108771    **         constraints but an index is selected anyway, in order
108772    **         to force the output order to conform to an ORDER BY.
108773    */
108774    static const u8 aStartOp[] = {
108775      0,
108776      0,
108777      OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
108778      OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
108779      OP_SeekGt,           /* 4: (start_constraints  && !startEq && !bRev) */
108780      OP_SeekLt,           /* 5: (start_constraints  && !startEq &&  bRev) */
108781      OP_SeekGe,           /* 6: (start_constraints  &&  startEq && !bRev) */
108782      OP_SeekLe            /* 7: (start_constraints  &&  startEq &&  bRev) */
108783    };
108784    static const u8 aEndOp[] = {
108785      OP_Noop,             /* 0: (!end_constraints) */
108786      OP_IdxGE,            /* 1: (end_constraints && !bRev) */
108787      OP_IdxLT             /* 2: (end_constraints && bRev) */
108788    };
108789    int nEq = pLevel->plan.nEq;  /* Number of == or IN terms */
108790    int isMinQuery = 0;          /* If this is an optimized SELECT min(x).. */
108791    int regBase;                 /* Base register holding constraint values */
108792    int r1;                      /* Temp register */
108793    WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
108794    WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
108795    int startEq;                 /* True if range start uses ==, >= or <= */
108796    int endEq;                   /* True if range end uses ==, >= or <= */
108797    int start_constraints;       /* Start of range is constrained */
108798    int nConstraint;             /* Number of constraint terms */
108799    Index *pIdx;                 /* The index we will be using */
108800    int iIdxCur;                 /* The VDBE cursor for the index */
108801    int nExtraReg = 0;           /* Number of extra registers needed */
108802    int op;                      /* Instruction opcode */
108803    char *zStartAff;             /* Affinity for start of range constraint */
108804    char *zEndAff;               /* Affinity for end of range constraint */
108805
108806    pIdx = pLevel->plan.u.pIdx;
108807    iIdxCur = pLevel->iIdxCur;
108808    k = (nEq==pIdx->nColumn ? -1 : pIdx->aiColumn[nEq]);
108809
108810    /* If this loop satisfies a sort order (pOrderBy) request that
108811    ** was passed to this function to implement a "SELECT min(x) ..."
108812    ** query, then the caller will only allow the loop to run for
108813    ** a single iteration. This means that the first row returned
108814    ** should not have a NULL value stored in 'x'. If column 'x' is
108815    ** the first one after the nEq equality constraints in the index,
108816    ** this requires some special handling.
108817    */
108818    if( (wctrlFlags&WHERE_ORDERBY_MIN)!=0
108819     && (pLevel->plan.wsFlags&WHERE_ORDERED)
108820     && (pIdx->nColumn>nEq)
108821    ){
108822      /* assert( pOrderBy->nExpr==1 ); */
108823      /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
108824      isMinQuery = 1;
108825      nExtraReg = 1;
108826    }
108827
108828    /* Find any inequality constraint terms for the start and end
108829    ** of the range.
108830    */
108831    if( pLevel->plan.wsFlags & WHERE_TOP_LIMIT ){
108832      pRangeEnd = findTerm(pWC, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
108833      nExtraReg = 1;
108834    }
108835    if( pLevel->plan.wsFlags & WHERE_BTM_LIMIT ){
108836      pRangeStart = findTerm(pWC, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
108837      nExtraReg = 1;
108838    }
108839
108840    /* Generate code to evaluate all constraint terms using == or IN
108841    ** and store the values of those terms in an array of registers
108842    ** starting at regBase.
108843    */
108844    regBase = codeAllEqualityTerms(
108845        pParse, pLevel, pWC, notReady, nExtraReg, &zStartAff
108846    );
108847    zEndAff = sqlite3DbStrDup(pParse->db, zStartAff);
108848    addrNxt = pLevel->addrNxt;
108849
108850    /* If we are doing a reverse order scan on an ascending index, or
108851    ** a forward order scan on a descending index, interchange the
108852    ** start and end terms (pRangeStart and pRangeEnd).
108853    */
108854    if( (nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
108855     || (bRev && pIdx->nColumn==nEq)
108856    ){
108857      SWAP(WhereTerm *, pRangeEnd, pRangeStart);
108858    }
108859
108860    testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
108861    testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
108862    testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
108863    testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
108864    startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
108865    endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
108866    start_constraints = pRangeStart || nEq>0;
108867
108868    /* Seek the index cursor to the start of the range. */
108869    nConstraint = nEq;
108870    if( pRangeStart ){
108871      Expr *pRight = pRangeStart->pExpr->pRight;
108872      sqlite3ExprCode(pParse, pRight, regBase+nEq);
108873      if( (pRangeStart->wtFlags & TERM_VNULL)==0 ){
108874        sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
108875      }
108876      if( zStartAff ){
108877        if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
108878          /* Since the comparison is to be performed with no conversions
108879          ** applied to the operands, set the affinity to apply to pRight to
108880          ** SQLITE_AFF_NONE.  */
108881          zStartAff[nEq] = SQLITE_AFF_NONE;
108882        }
108883        if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
108884          zStartAff[nEq] = SQLITE_AFF_NONE;
108885        }
108886      }
108887      nConstraint++;
108888      testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
108889    }else if( isMinQuery ){
108890      sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
108891      nConstraint++;
108892      startEq = 0;
108893      start_constraints = 1;
108894    }
108895    codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);
108896    op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
108897    assert( op!=0 );
108898    testcase( op==OP_Rewind );
108899    testcase( op==OP_Last );
108900    testcase( op==OP_SeekGt );
108901    testcase( op==OP_SeekGe );
108902    testcase( op==OP_SeekLe );
108903    testcase( op==OP_SeekLt );
108904    sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
108905
108906    /* Load the value for the inequality constraint at the end of the
108907    ** range (if any).
108908    */
108909    nConstraint = nEq;
108910    if( pRangeEnd ){
108911      Expr *pRight = pRangeEnd->pExpr->pRight;
108912      sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
108913      sqlite3ExprCode(pParse, pRight, regBase+nEq);
108914      if( (pRangeEnd->wtFlags & TERM_VNULL)==0 ){
108915        sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
108916      }
108917      if( zEndAff ){
108918        if( sqlite3CompareAffinity(pRight, zEndAff[nEq])==SQLITE_AFF_NONE){
108919          /* Since the comparison is to be performed with no conversions
108920          ** applied to the operands, set the affinity to apply to pRight to
108921          ** SQLITE_AFF_NONE.  */
108922          zEndAff[nEq] = SQLITE_AFF_NONE;
108923        }
108924        if( sqlite3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){
108925          zEndAff[nEq] = SQLITE_AFF_NONE;
108926        }
108927      }
108928      codeApplyAffinity(pParse, regBase, nEq+1, zEndAff);
108929      nConstraint++;
108930      testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
108931    }
108932    sqlite3DbFree(pParse->db, zStartAff);
108933    sqlite3DbFree(pParse->db, zEndAff);
108934
108935    /* Top of the loop body */
108936    pLevel->p2 = sqlite3VdbeCurrentAddr(v);
108937
108938    /* Check if the index cursor is past the end of the range. */
108939    op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
108940    testcase( op==OP_Noop );
108941    testcase( op==OP_IdxGE );
108942    testcase( op==OP_IdxLT );
108943    if( op!=OP_Noop ){
108944      sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
108945      sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
108946    }
108947
108948    /* If there are inequality constraints, check that the value
108949    ** of the table column that the inequality contrains is not NULL.
108950    ** If it is, jump to the next iteration of the loop.
108951    */
108952    r1 = sqlite3GetTempReg(pParse);
108953    testcase( pLevel->plan.wsFlags & WHERE_BTM_LIMIT );
108954    testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );
108955    if( (pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 ){
108956      sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
108957      sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
108958    }
108959    sqlite3ReleaseTempReg(pParse, r1);
108960
108961    /* Seek the table cursor, if required */
108962    disableTerm(pLevel, pRangeStart);
108963    disableTerm(pLevel, pRangeEnd);
108964    if( !omitTable ){
108965      iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
108966      sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
108967      sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
108968      sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg);  /* Deferred seek */
108969    }
108970
108971    /* Record the instruction used to terminate the loop. Disable
108972    ** WHERE clause terms made redundant by the index range scan.
108973    */
108974    if( pLevel->plan.wsFlags & WHERE_UNIQUE ){
108975      pLevel->op = OP_Noop;
108976    }else if( bRev ){
108977      pLevel->op = OP_Prev;
108978    }else{
108979      pLevel->op = OP_Next;
108980    }
108981    pLevel->p1 = iIdxCur;
108982    if( pLevel->plan.wsFlags & WHERE_COVER_SCAN ){
108983      pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
108984    }else{
108985      assert( pLevel->p5==0 );
108986    }
108987  }else
108988
108989#ifndef SQLITE_OMIT_OR_OPTIMIZATION
108990  if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
108991    /* Case 4:  Two or more separately indexed terms connected by OR
108992    **
108993    ** Example:
108994    **
108995    **   CREATE TABLE t1(a,b,c,d);
108996    **   CREATE INDEX i1 ON t1(a);
108997    **   CREATE INDEX i2 ON t1(b);
108998    **   CREATE INDEX i3 ON t1(c);
108999    **
109000    **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
109001    **
109002    ** In the example, there are three indexed terms connected by OR.
109003    ** The top of the loop looks like this:
109004    **
109005    **          Null       1                # Zero the rowset in reg 1
109006    **
109007    ** Then, for each indexed term, the following. The arguments to
109008    ** RowSetTest are such that the rowid of the current row is inserted
109009    ** into the RowSet. If it is already present, control skips the
109010    ** Gosub opcode and jumps straight to the code generated by WhereEnd().
109011    **
109012    **        sqlite3WhereBegin(<term>)
109013    **          RowSetTest                  # Insert rowid into rowset
109014    **          Gosub      2 A
109015    **        sqlite3WhereEnd()
109016    **
109017    ** Following the above, code to terminate the loop. Label A, the target
109018    ** of the Gosub above, jumps to the instruction right after the Goto.
109019    **
109020    **          Null       1                # Zero the rowset in reg 1
109021    **          Goto       B                # The loop is finished.
109022    **
109023    **       A: <loop body>                 # Return data, whatever.
109024    **
109025    **          Return     2                # Jump back to the Gosub
109026    **
109027    **       B: <after the loop>
109028    **
109029    */
109030    WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
109031    SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
109032    Index *pCov = 0;             /* Potential covering index (or NULL) */
109033    int iCovCur = pParse->nTab++;  /* Cursor used for index scans (if any) */
109034
109035    int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
109036    int regRowset = 0;                        /* Register for RowSet object */
109037    int regRowid = 0;                         /* Register holding rowid */
109038    int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */
109039    int iRetInit;                             /* Address of regReturn init */
109040    int untestedTerms = 0;             /* Some terms not completely tested */
109041    int ii;                            /* Loop counter */
109042    Expr *pAndExpr = 0;                /* An ".. AND (...)" expression */
109043
109044    pTerm = pLevel->plan.u.pTerm;
109045    assert( pTerm!=0 );
109046    assert( pTerm->eOperator & WO_OR );
109047    assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
109048    pOrWc = &pTerm->u.pOrInfo->wc;
109049    pLevel->op = OP_Return;
109050    pLevel->p1 = regReturn;
109051
109052    /* Set up a new SrcList in pOrTab containing the table being scanned
109053    ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
109054    ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
109055    */
109056    if( pWInfo->nLevel>1 ){
109057      int nNotReady;                 /* The number of notReady tables */
109058      struct SrcList_item *origSrc;     /* Original list of tables */
109059      nNotReady = pWInfo->nLevel - iLevel - 1;
109060      pOrTab = sqlite3StackAllocRaw(pParse->db,
109061                            sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
109062      if( pOrTab==0 ) return notReady;
109063      pOrTab->nAlloc = (i16)(nNotReady + 1);
109064      pOrTab->nSrc = pOrTab->nAlloc;
109065      memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
109066      origSrc = pWInfo->pTabList->a;
109067      for(k=1; k<=nNotReady; k++){
109068        memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
109069      }
109070    }else{
109071      pOrTab = pWInfo->pTabList;
109072    }
109073
109074    /* Initialize the rowset register to contain NULL. An SQL NULL is
109075    ** equivalent to an empty rowset.
109076    **
109077    ** Also initialize regReturn to contain the address of the instruction
109078    ** immediately following the OP_Return at the bottom of the loop. This
109079    ** is required in a few obscure LEFT JOIN cases where control jumps
109080    ** over the top of the loop into the body of it. In this case the
109081    ** correct response for the end-of-loop code (the OP_Return) is to
109082    ** fall through to the next instruction, just as an OP_Next does if
109083    ** called on an uninitialized cursor.
109084    */
109085    if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
109086      regRowset = ++pParse->nMem;
109087      regRowid = ++pParse->nMem;
109088      sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
109089    }
109090    iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
109091
109092    /* If the original WHERE clause is z of the form:  (x1 OR x2 OR ...) AND y
109093    ** Then for every term xN, evaluate as the subexpression: xN AND z
109094    ** That way, terms in y that are factored into the disjunction will
109095    ** be picked up by the recursive calls to sqlite3WhereBegin() below.
109096    **
109097    ** Actually, each subexpression is converted to "xN AND w" where w is
109098    ** the "interesting" terms of z - terms that did not originate in the
109099    ** ON or USING clause of a LEFT JOIN, and terms that are usable as
109100    ** indices.
109101    **
109102    ** This optimization also only applies if the (x1 OR x2 OR ...) term
109103    ** is not contained in the ON clause of a LEFT JOIN.
109104    ** See ticket http://www.sqlite.org/src/info/f2369304e4
109105    */
109106    if( pWC->nTerm>1 ){
109107      int iTerm;
109108      for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
109109        Expr *pExpr = pWC->a[iTerm].pExpr;
109110        if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
109111        if( pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_ORINFO) ) continue;
109112        if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
109113        pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
109114        pAndExpr = sqlite3ExprAnd(pParse->db, pAndExpr, pExpr);
109115      }
109116      if( pAndExpr ){
109117        pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
109118      }
109119    }
109120
109121    for(ii=0; ii<pOrWc->nTerm; ii++){
109122      WhereTerm *pOrTerm = &pOrWc->a[ii];
109123      if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
109124        WhereInfo *pSubWInfo;          /* Info for single OR-term scan */
109125        Expr *pOrExpr = pOrTerm->pExpr;
109126        if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
109127          pAndExpr->pLeft = pOrExpr;
109128          pOrExpr = pAndExpr;
109129        }
109130        /* Loop through table entries that match term pOrTerm. */
109131        pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
109132                        WHERE_OMIT_OPEN_CLOSE | WHERE_AND_ONLY |
109133                        WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY, iCovCur);
109134        assert( pSubWInfo || pParse->nErr || pParse->db->mallocFailed );
109135        if( pSubWInfo ){
109136          WhereLevel *pLvl;
109137          explainOneScan(
109138              pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
109139          );
109140          if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
109141            int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
109142            int r;
109143            r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur,
109144                                         regRowid, 0);
109145            sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
109146                                 sqlite3VdbeCurrentAddr(v)+2, r, iSet);
109147          }
109148          sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
109149
109150          /* The pSubWInfo->untestedTerms flag means that this OR term
109151          ** contained one or more AND term from a notReady table.  The
109152          ** terms from the notReady table could not be tested and will
109153          ** need to be tested later.
109154          */
109155          if( pSubWInfo->untestedTerms ) untestedTerms = 1;
109156
109157          /* If all of the OR-connected terms are optimized using the same
109158          ** index, and the index is opened using the same cursor number
109159          ** by each call to sqlite3WhereBegin() made by this loop, it may
109160          ** be possible to use that index as a covering index.
109161          **
109162          ** If the call to sqlite3WhereBegin() above resulted in a scan that
109163          ** uses an index, and this is either the first OR-connected term
109164          ** processed or the index is the same as that used by all previous
109165          ** terms, set pCov to the candidate covering index. Otherwise, set
109166          ** pCov to NULL to indicate that no candidate covering index will
109167          ** be available.
109168          */
109169          pLvl = &pSubWInfo->a[0];
109170          if( (pLvl->plan.wsFlags & WHERE_INDEXED)!=0
109171           && (pLvl->plan.wsFlags & WHERE_TEMP_INDEX)==0
109172           && (ii==0 || pLvl->plan.u.pIdx==pCov)
109173          ){
109174            assert( pLvl->iIdxCur==iCovCur );
109175            pCov = pLvl->plan.u.pIdx;
109176          }else{
109177            pCov = 0;
109178          }
109179
109180          /* Finish the loop through table entries that match term pOrTerm. */
109181          sqlite3WhereEnd(pSubWInfo);
109182        }
109183      }
109184    }
109185    pLevel->u.pCovidx = pCov;
109186    if( pCov ) pLevel->iIdxCur = iCovCur;
109187    if( pAndExpr ){
109188      pAndExpr->pLeft = 0;
109189      sqlite3ExprDelete(pParse->db, pAndExpr);
109190    }
109191    sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
109192    sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
109193    sqlite3VdbeResolveLabel(v, iLoopBody);
109194
109195    if( pWInfo->nLevel>1 ) sqlite3StackFree(pParse->db, pOrTab);
109196    if( !untestedTerms ) disableTerm(pLevel, pTerm);
109197  }else
109198#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
109199
109200  {
109201    /* Case 5:  There is no usable index.  We must do a complete
109202    **          scan of the entire table.
109203    */
109204    static const u8 aStep[] = { OP_Next, OP_Prev };
109205    static const u8 aStart[] = { OP_Rewind, OP_Last };
109206    assert( bRev==0 || bRev==1 );
109207    assert( omitTable==0 );
109208    pLevel->op = aStep[bRev];
109209    pLevel->p1 = iCur;
109210    pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
109211    pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
109212  }
109213  newNotReady = notReady & ~getMask(pWC->pMaskSet, iCur);
109214
109215  /* Insert code to test every subexpression that can be completely
109216  ** computed using the current set of tables.
109217  **
109218  ** IMPLEMENTATION-OF: R-49525-50935 Terms that cannot be satisfied through
109219  ** the use of indices become tests that are evaluated against each row of
109220  ** the relevant input tables.
109221  */
109222  for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
109223    Expr *pE;
109224    testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* IMP: R-30575-11662 */
109225    testcase( pTerm->wtFlags & TERM_CODED );
109226    if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
109227    if( (pTerm->prereqAll & newNotReady)!=0 ){
109228      testcase( pWInfo->untestedTerms==0
109229               && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
109230      pWInfo->untestedTerms = 1;
109231      continue;
109232    }
109233    pE = pTerm->pExpr;
109234    assert( pE!=0 );
109235    if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
109236      continue;
109237    }
109238    sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
109239    pTerm->wtFlags |= TERM_CODED;
109240  }
109241
109242  /* Insert code to test for implied constraints based on transitivity
109243  ** of the "==" operator.
109244  **
109245  ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
109246  ** and we are coding the t1 loop and the t2 loop has not yet coded,
109247  ** then we cannot use the "t1.a=t2.b" constraint, but we can code
109248  ** the implied "t1.a=123" constraint.
109249  */
109250  for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
109251    Expr *pE;
109252    WhereTerm *pAlt;
109253    Expr sEq;
109254    if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
109255    if( pTerm->eOperator!=(WO_EQUIV|WO_EQ) ) continue;
109256    if( pTerm->leftCursor!=iCur ) continue;
109257    pE = pTerm->pExpr;
109258    assert( !ExprHasProperty(pE, EP_FromJoin) );
109259    assert( (pTerm->prereqRight & newNotReady)!=0 );
109260    pAlt = findTerm(pWC, iCur, pTerm->u.leftColumn, notReady, WO_EQ|WO_IN, 0);
109261    if( pAlt==0 ) continue;
109262    if( pAlt->wtFlags & (TERM_CODED) ) continue;
109263    VdbeNoopComment((v, "begin transitive constraint"));
109264    sEq = *pAlt->pExpr;
109265    sEq.pLeft = pE->pLeft;
109266    sqlite3ExprIfFalse(pParse, &sEq, addrCont, SQLITE_JUMPIFNULL);
109267  }
109268
109269  /* For a LEFT OUTER JOIN, generate code that will record the fact that
109270  ** at least one row of the right table has matched the left table.
109271  */
109272  if( pLevel->iLeftJoin ){
109273    pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
109274    sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
109275    VdbeComment((v, "record LEFT JOIN hit"));
109276    sqlite3ExprCacheClear(pParse);
109277    for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
109278      testcase( pTerm->wtFlags & TERM_VIRTUAL );  /* IMP: R-30575-11662 */
109279      testcase( pTerm->wtFlags & TERM_CODED );
109280      if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
109281      if( (pTerm->prereqAll & newNotReady)!=0 ){
109282        assert( pWInfo->untestedTerms );
109283        continue;
109284      }
109285      assert( pTerm->pExpr );
109286      sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
109287      pTerm->wtFlags |= TERM_CODED;
109288    }
109289  }
109290  sqlite3ReleaseTempReg(pParse, iReleaseReg);
109291
109292  return newNotReady;
109293}
109294
109295#if defined(SQLITE_TEST)
109296/*
109297** The following variable holds a text description of query plan generated
109298** by the most recent call to sqlite3WhereBegin().  Each call to WhereBegin
109299** overwrites the previous.  This information is used for testing and
109300** analysis only.
109301*/
109302SQLITE_API char sqlite3_query_plan[BMS*2*40];  /* Text of the join */
109303static int nQPlan = 0;              /* Next free slow in _query_plan[] */
109304
109305#endif /* SQLITE_TEST */
109306
109307
109308/*
109309** Free a WhereInfo structure
109310*/
109311static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
109312  if( ALWAYS(pWInfo) ){
109313    int i;
109314    for(i=0; i<pWInfo->nLevel; i++){
109315      sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
109316      if( pInfo ){
109317        /* assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed ); */
109318        if( pInfo->needToFreeIdxStr ){
109319          sqlite3_free(pInfo->idxStr);
109320        }
109321        sqlite3DbFree(db, pInfo);
109322      }
109323      if( pWInfo->a[i].plan.wsFlags & WHERE_TEMP_INDEX ){
109324        Index *pIdx = pWInfo->a[i].plan.u.pIdx;
109325        if( pIdx ){
109326          sqlite3DbFree(db, pIdx->zColAff);
109327          sqlite3DbFree(db, pIdx);
109328        }
109329      }
109330    }
109331    whereClauseClear(pWInfo->pWC);
109332    sqlite3DbFree(db, pWInfo);
109333  }
109334}
109335
109336
109337/*
109338** Generate the beginning of the loop used for WHERE clause processing.
109339** The return value is a pointer to an opaque structure that contains
109340** information needed to terminate the loop.  Later, the calling routine
109341** should invoke sqlite3WhereEnd() with the return value of this function
109342** in order to complete the WHERE clause processing.
109343**
109344** If an error occurs, this routine returns NULL.
109345**
109346** The basic idea is to do a nested loop, one loop for each table in
109347** the FROM clause of a select.  (INSERT and UPDATE statements are the
109348** same as a SELECT with only a single table in the FROM clause.)  For
109349** example, if the SQL is this:
109350**
109351**       SELECT * FROM t1, t2, t3 WHERE ...;
109352**
109353** Then the code generated is conceptually like the following:
109354**
109355**      foreach row1 in t1 do       \    Code generated
109356**        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
109357**          foreach row3 in t3 do   /
109358**            ...
109359**          end                     \    Code generated
109360**        end                        |-- by sqlite3WhereEnd()
109361**      end                         /
109362**
109363** Note that the loops might not be nested in the order in which they
109364** appear in the FROM clause if a different order is better able to make
109365** use of indices.  Note also that when the IN operator appears in
109366** the WHERE clause, it might result in additional nested loops for
109367** scanning through all values on the right-hand side of the IN.
109368**
109369** There are Btree cursors associated with each table.  t1 uses cursor
109370** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
109371** And so forth.  This routine generates code to open those VDBE cursors
109372** and sqlite3WhereEnd() generates the code to close them.
109373**
109374** The code that sqlite3WhereBegin() generates leaves the cursors named
109375** in pTabList pointing at their appropriate entries.  The [...] code
109376** can use OP_Column and OP_Rowid opcodes on these cursors to extract
109377** data from the various tables of the loop.
109378**
109379** If the WHERE clause is empty, the foreach loops must each scan their
109380** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
109381** the tables have indices and there are terms in the WHERE clause that
109382** refer to those indices, a complete table scan can be avoided and the
109383** code will run much faster.  Most of the work of this routine is checking
109384** to see if there are indices that can be used to speed up the loop.
109385**
109386** Terms of the WHERE clause are also used to limit which rows actually
109387** make it to the "..." in the middle of the loop.  After each "foreach",
109388** terms of the WHERE clause that use only terms in that loop and outer
109389** loops are evaluated and if false a jump is made around all subsequent
109390** inner loops (or around the "..." if the test occurs within the inner-
109391** most loop)
109392**
109393** OUTER JOINS
109394**
109395** An outer join of tables t1 and t2 is conceptally coded as follows:
109396**
109397**    foreach row1 in t1 do
109398**      flag = 0
109399**      foreach row2 in t2 do
109400**        start:
109401**          ...
109402**          flag = 1
109403**      end
109404**      if flag==0 then
109405**        move the row2 cursor to a null row
109406**        goto start
109407**      fi
109408**    end
109409**
109410** ORDER BY CLAUSE PROCESSING
109411**
109412** pOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
109413** if there is one.  If there is no ORDER BY clause or if this routine
109414** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
109415**
109416** If an index can be used so that the natural output order of the table
109417** scan is correct for the ORDER BY clause, then that index is used and
109418** the returned WhereInfo.nOBSat field is set to pOrderBy->nExpr.  This
109419** is an optimization that prevents an unnecessary sort of the result set
109420** if an index appropriate for the ORDER BY clause already exists.
109421**
109422** If the where clause loops cannot be arranged to provide the correct
109423** output order, then WhereInfo.nOBSat is 0.
109424*/
109425SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
109426  Parse *pParse,        /* The parser context */
109427  SrcList *pTabList,    /* A list of all tables to be scanned */
109428  Expr *pWhere,         /* The WHERE clause */
109429  ExprList *pOrderBy,   /* An ORDER BY clause, or NULL */
109430  ExprList *pDistinct,  /* The select-list for DISTINCT queries - or NULL */
109431  u16 wctrlFlags,       /* One of the WHERE_* flags defined in sqliteInt.h */
109432  int iIdxCur           /* If WHERE_ONETABLE_ONLY is set, index cursor number */
109433){
109434  int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
109435  int nTabList;              /* Number of elements in pTabList */
109436  WhereInfo *pWInfo;         /* Will become the return value of this function */
109437  Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
109438  Bitmask notReady;          /* Cursors that are not yet positioned */
109439  WhereBestIdx sWBI;         /* Best index search context */
109440  WhereMaskSet *pMaskSet;    /* The expression mask set */
109441  WhereLevel *pLevel;        /* A single level in pWInfo->a[] */
109442  int iFrom;                 /* First unused FROM clause element */
109443  int andFlags;              /* AND-ed combination of all pWC->a[].wtFlags */
109444  int ii;                    /* Loop counter */
109445  sqlite3 *db;               /* Database connection */
109446
109447
109448  /* Variable initialization */
109449  memset(&sWBI, 0, sizeof(sWBI));
109450  sWBI.pParse = pParse;
109451
109452  /* The number of tables in the FROM clause is limited by the number of
109453  ** bits in a Bitmask
109454  */
109455  testcase( pTabList->nSrc==BMS );
109456  if( pTabList->nSrc>BMS ){
109457    sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
109458    return 0;
109459  }
109460
109461  /* This function normally generates a nested loop for all tables in
109462  ** pTabList.  But if the WHERE_ONETABLE_ONLY flag is set, then we should
109463  ** only generate code for the first table in pTabList and assume that
109464  ** any cursors associated with subsequent tables are uninitialized.
109465  */
109466  nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
109467
109468  /* Allocate and initialize the WhereInfo structure that will become the
109469  ** return value. A single allocation is used to store the WhereInfo
109470  ** struct, the contents of WhereInfo.a[], the WhereClause structure
109471  ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
109472  ** field (type Bitmask) it must be aligned on an 8-byte boundary on
109473  ** some architectures. Hence the ROUND8() below.
109474  */
109475  db = pParse->db;
109476  nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
109477  pWInfo = sqlite3DbMallocZero(db,
109478      nByteWInfo +
109479      sizeof(WhereClause) +
109480      sizeof(WhereMaskSet)
109481  );
109482  if( db->mallocFailed ){
109483    sqlite3DbFree(db, pWInfo);
109484    pWInfo = 0;
109485    goto whereBeginError;
109486  }
109487  pWInfo->nLevel = nTabList;
109488  pWInfo->pParse = pParse;
109489  pWInfo->pTabList = pTabList;
109490  pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
109491  pWInfo->pWC = sWBI.pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];
109492  pWInfo->wctrlFlags = wctrlFlags;
109493  pWInfo->savedNQueryLoop = pParse->nQueryLoop;
109494  pMaskSet = (WhereMaskSet*)&sWBI.pWC[1];
109495  sWBI.aLevel = pWInfo->a;
109496
109497  /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
109498  ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
109499  if( OptimizationDisabled(db, SQLITE_DistinctOpt) ) pDistinct = 0;
109500
109501  /* Split the WHERE clause into separate subexpressions where each
109502  ** subexpression is separated by an AND operator.
109503  */
109504  initMaskSet(pMaskSet);
109505  whereClauseInit(sWBI.pWC, pParse, pMaskSet, wctrlFlags);
109506  sqlite3ExprCodeConstants(pParse, pWhere);
109507  whereSplit(sWBI.pWC, pWhere, TK_AND);   /* IMP: R-15842-53296 */
109508
109509  /* Special case: a WHERE clause that is constant.  Evaluate the
109510  ** expression and either jump over all of the code or fall thru.
109511  */
109512  if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
109513    sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
109514    pWhere = 0;
109515  }
109516
109517  /* Assign a bit from the bitmask to every term in the FROM clause.
109518  **
109519  ** When assigning bitmask values to FROM clause cursors, it must be
109520  ** the case that if X is the bitmask for the N-th FROM clause term then
109521  ** the bitmask for all FROM clause terms to the left of the N-th term
109522  ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use
109523  ** its Expr.iRightJoinTable value to find the bitmask of the right table
109524  ** of the join.  Subtracting one from the right table bitmask gives a
109525  ** bitmask for all tables to the left of the join.  Knowing the bitmask
109526  ** for all tables to the left of a left join is important.  Ticket #3015.
109527  **
109528  ** Note that bitmasks are created for all pTabList->nSrc tables in
109529  ** pTabList, not just the first nTabList tables.  nTabList is normally
109530  ** equal to pTabList->nSrc but might be shortened to 1 if the
109531  ** WHERE_ONETABLE_ONLY flag is set.
109532  */
109533  for(ii=0; ii<pTabList->nSrc; ii++){
109534    createMask(pMaskSet, pTabList->a[ii].iCursor);
109535  }
109536#ifndef NDEBUG
109537  {
109538    Bitmask toTheLeft = 0;
109539    for(ii=0; ii<pTabList->nSrc; ii++){
109540      Bitmask m = getMask(pMaskSet, pTabList->a[ii].iCursor);
109541      assert( (m-1)==toTheLeft );
109542      toTheLeft |= m;
109543    }
109544  }
109545#endif
109546
109547  /* Analyze all of the subexpressions.  Note that exprAnalyze() might
109548  ** add new virtual terms onto the end of the WHERE clause.  We do not
109549  ** want to analyze these virtual terms, so start analyzing at the end
109550  ** and work forward so that the added virtual terms are never processed.
109551  */
109552  exprAnalyzeAll(pTabList, sWBI.pWC);
109553  if( db->mallocFailed ){
109554    goto whereBeginError;
109555  }
109556
109557  /* Check if the DISTINCT qualifier, if there is one, is redundant.
109558  ** If it is, then set pDistinct to NULL and WhereInfo.eDistinct to
109559  ** WHERE_DISTINCT_UNIQUE to tell the caller to ignore the DISTINCT.
109560  */
109561  if( pDistinct && isDistinctRedundant(pParse, pTabList, sWBI.pWC, pDistinct) ){
109562    pDistinct = 0;
109563    pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
109564  }
109565
109566  /* Chose the best index to use for each table in the FROM clause.
109567  **
109568  ** This loop fills in the following fields:
109569  **
109570  **   pWInfo->a[].pIdx      The index to use for this level of the loop.
109571  **   pWInfo->a[].wsFlags   WHERE_xxx flags associated with pIdx
109572  **   pWInfo->a[].nEq       The number of == and IN constraints
109573  **   pWInfo->a[].iFrom     Which term of the FROM clause is being coded
109574  **   pWInfo->a[].iTabCur   The VDBE cursor for the database table
109575  **   pWInfo->a[].iIdxCur   The VDBE cursor for the index
109576  **   pWInfo->a[].pTerm     When wsFlags==WO_OR, the OR-clause term
109577  **
109578  ** This loop also figures out the nesting order of tables in the FROM
109579  ** clause.
109580  */
109581  sWBI.notValid = ~(Bitmask)0;
109582  sWBI.pOrderBy = pOrderBy;
109583  sWBI.n = nTabList;
109584  sWBI.pDistinct = pDistinct;
109585  andFlags = ~0;
109586  WHERETRACE(("*** Optimizer Start ***\n"));
109587  for(sWBI.i=iFrom=0, pLevel=pWInfo->a; sWBI.i<nTabList; sWBI.i++, pLevel++){
109588    WhereCost bestPlan;         /* Most efficient plan seen so far */
109589    Index *pIdx;                /* Index for FROM table at pTabItem */
109590    int j;                      /* For looping over FROM tables */
109591    int bestJ = -1;             /* The value of j */
109592    Bitmask m;                  /* Bitmask value for j or bestJ */
109593    int isOptimal;              /* Iterator for optimal/non-optimal search */
109594    int ckOptimal;              /* Do the optimal scan check */
109595    int nUnconstrained;         /* Number tables without INDEXED BY */
109596    Bitmask notIndexed;         /* Mask of tables that cannot use an index */
109597
109598    memset(&bestPlan, 0, sizeof(bestPlan));
109599    bestPlan.rCost = SQLITE_BIG_DBL;
109600    WHERETRACE(("*** Begin search for loop %d ***\n", sWBI.i));
109601
109602    /* Loop through the remaining entries in the FROM clause to find the
109603    ** next nested loop. The loop tests all FROM clause entries
109604    ** either once or twice.
109605    **
109606    ** The first test is always performed if there are two or more entries
109607    ** remaining and never performed if there is only one FROM clause entry
109608    ** to choose from.  The first test looks for an "optimal" scan.  In
109609    ** this context an optimal scan is one that uses the same strategy
109610    ** for the given FROM clause entry as would be selected if the entry
109611    ** were used as the innermost nested loop.  In other words, a table
109612    ** is chosen such that the cost of running that table cannot be reduced
109613    ** by waiting for other tables to run first.  This "optimal" test works
109614    ** by first assuming that the FROM clause is on the inner loop and finding
109615    ** its query plan, then checking to see if that query plan uses any
109616    ** other FROM clause terms that are sWBI.notValid.  If no notValid terms
109617    ** are used then the "optimal" query plan works.
109618    **
109619    ** Note that the WhereCost.nRow parameter for an optimal scan might
109620    ** not be as small as it would be if the table really were the innermost
109621    ** join.  The nRow value can be reduced by WHERE clause constraints
109622    ** that do not use indices.  But this nRow reduction only happens if the
109623    ** table really is the innermost join.
109624    **
109625    ** The second loop iteration is only performed if no optimal scan
109626    ** strategies were found by the first iteration. This second iteration
109627    ** is used to search for the lowest cost scan overall.
109628    **
109629    ** Without the optimal scan step (the first iteration) a suboptimal
109630    ** plan might be chosen for queries like this:
109631    **
109632    **   CREATE TABLE t1(a, b);
109633    **   CREATE TABLE t2(c, d);
109634    **   SELECT * FROM t2, t1 WHERE t2.rowid = t1.a;
109635    **
109636    ** The best strategy is to iterate through table t1 first. However it
109637    ** is not possible to determine this with a simple greedy algorithm.
109638    ** Since the cost of a linear scan through table t2 is the same
109639    ** as the cost of a linear scan through table t1, a simple greedy
109640    ** algorithm may choose to use t2 for the outer loop, which is a much
109641    ** costlier approach.
109642    */
109643    nUnconstrained = 0;
109644    notIndexed = 0;
109645
109646    /* The optimal scan check only occurs if there are two or more tables
109647    ** available to be reordered */
109648    if( iFrom==nTabList-1 ){
109649      ckOptimal = 0;  /* Common case of just one table in the FROM clause */
109650    }else{
109651      ckOptimal = -1;
109652      for(j=iFrom, sWBI.pSrc=&pTabList->a[j]; j<nTabList; j++, sWBI.pSrc++){
109653        m = getMask(pMaskSet, sWBI.pSrc->iCursor);
109654        if( (m & sWBI.notValid)==0 ){
109655          if( j==iFrom ) iFrom++;
109656          continue;
109657        }
109658        if( j>iFrom && (sWBI.pSrc->jointype & (JT_LEFT|JT_CROSS))!=0 ) break;
109659        if( ++ckOptimal ) break;
109660        if( (sWBI.pSrc->jointype & JT_LEFT)!=0 ) break;
109661      }
109662    }
109663    assert( ckOptimal==0 || ckOptimal==1 );
109664
109665    for(isOptimal=ckOptimal; isOptimal>=0 && bestJ<0; isOptimal--){
109666      for(j=iFrom, sWBI.pSrc=&pTabList->a[j]; j<nTabList; j++, sWBI.pSrc++){
109667        if( j>iFrom && (sWBI.pSrc->jointype & (JT_LEFT|JT_CROSS))!=0 ){
109668          /* This break and one like it in the ckOptimal computation loop
109669          ** above prevent table reordering across LEFT and CROSS JOINs.
109670          ** The LEFT JOIN case is necessary for correctness.  The prohibition
109671          ** against reordering across a CROSS JOIN is an SQLite feature that
109672          ** allows the developer to control table reordering */
109673          break;
109674        }
109675        m = getMask(pMaskSet, sWBI.pSrc->iCursor);
109676        if( (m & sWBI.notValid)==0 ){
109677          assert( j>iFrom );
109678          continue;
109679        }
109680        sWBI.notReady = (isOptimal ? m : sWBI.notValid);
109681        if( sWBI.pSrc->pIndex==0 ) nUnconstrained++;
109682
109683        WHERETRACE(("   === trying table %d (%s) with isOptimal=%d ===\n",
109684                    j, sWBI.pSrc->pTab->zName, isOptimal));
109685        assert( sWBI.pSrc->pTab );
109686#ifndef SQLITE_OMIT_VIRTUALTABLE
109687        if( IsVirtual(sWBI.pSrc->pTab) ){
109688          sWBI.ppIdxInfo = &pWInfo->a[j].pIdxInfo;
109689          bestVirtualIndex(&sWBI);
109690        }else
109691#endif
109692        {
109693          bestBtreeIndex(&sWBI);
109694        }
109695        assert( isOptimal || (sWBI.cost.used&sWBI.notValid)==0 );
109696
109697        /* If an INDEXED BY clause is present, then the plan must use that
109698        ** index if it uses any index at all */
109699        assert( sWBI.pSrc->pIndex==0
109700                  || (sWBI.cost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0
109701                  || sWBI.cost.plan.u.pIdx==sWBI.pSrc->pIndex );
109702
109703        if( isOptimal && (sWBI.cost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ){
109704          notIndexed |= m;
109705        }
109706        if( isOptimal ){
109707          pWInfo->a[j].rOptCost = sWBI.cost.rCost;
109708        }else if( ckOptimal ){
109709          /* If two or more tables have nearly the same outer loop cost, but
109710          ** very different inner loop (optimal) cost, we want to choose
109711          ** for the outer loop that table which benefits the least from
109712          ** being in the inner loop.  The following code scales the
109713          ** outer loop cost estimate to accomplish that. */
109714          WHERETRACE(("   scaling cost from %.1f to %.1f\n",
109715                      sWBI.cost.rCost,
109716                      sWBI.cost.rCost/pWInfo->a[j].rOptCost));
109717          sWBI.cost.rCost /= pWInfo->a[j].rOptCost;
109718        }
109719
109720        /* Conditions under which this table becomes the best so far:
109721        **
109722        **   (1) The table must not depend on other tables that have not
109723        **       yet run.  (In other words, it must not depend on tables
109724        **       in inner loops.)
109725        **
109726        **   (2) (This rule was removed on 2012-11-09.  The scaling of the
109727        **       cost using the optimal scan cost made this rule obsolete.)
109728        **
109729        **   (3) All tables have an INDEXED BY clause or this table lacks an
109730        **       INDEXED BY clause or this table uses the specific
109731        **       index specified by its INDEXED BY clause.  This rule ensures
109732        **       that a best-so-far is always selected even if an impossible
109733        **       combination of INDEXED BY clauses are given.  The error
109734        **       will be detected and relayed back to the application later.
109735        **       The NEVER() comes about because rule (2) above prevents
109736        **       An indexable full-table-scan from reaching rule (3).
109737        **
109738        **   (4) The plan cost must be lower than prior plans, where "cost"
109739        **       is defined by the compareCost() function above.
109740        */
109741        if( (sWBI.cost.used&sWBI.notValid)==0                    /* (1) */
109742            && (nUnconstrained==0 || sWBI.pSrc->pIndex==0        /* (3) */
109743                || NEVER((sWBI.cost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0))
109744            && (bestJ<0 || compareCost(&sWBI.cost, &bestPlan))   /* (4) */
109745        ){
109746          WHERETRACE(("   === table %d (%s) is best so far\n"
109747                      "       cost=%.1f, nRow=%.1f, nOBSat=%d, wsFlags=%08x\n",
109748                      j, sWBI.pSrc->pTab->zName,
109749                      sWBI.cost.rCost, sWBI.cost.plan.nRow,
109750                      sWBI.cost.plan.nOBSat, sWBI.cost.plan.wsFlags));
109751          bestPlan = sWBI.cost;
109752          bestJ = j;
109753        }
109754
109755        /* In a join like "w JOIN x LEFT JOIN y JOIN z"  make sure that
109756        ** table y (and not table z) is always the next inner loop inside
109757        ** of table x. */
109758        if( (sWBI.pSrc->jointype & JT_LEFT)!=0 ) break;
109759      }
109760    }
109761    assert( bestJ>=0 );
109762    assert( sWBI.notValid & getMask(pMaskSet, pTabList->a[bestJ].iCursor) );
109763    assert( bestJ==iFrom || (pTabList->a[iFrom].jointype & JT_LEFT)==0 );
109764    testcase( bestJ>iFrom && (pTabList->a[iFrom].jointype & JT_CROSS)!=0 );
109765    testcase( bestJ>iFrom && bestJ<nTabList-1
109766                          && (pTabList->a[bestJ+1].jointype & JT_LEFT)!=0 );
109767    WHERETRACE(("*** Optimizer selects table %d (%s) for loop %d with:\n"
109768                "    cost=%.1f, nRow=%.1f, nOBSat=%d, wsFlags=0x%08x\n",
109769                bestJ, pTabList->a[bestJ].pTab->zName,
109770                pLevel-pWInfo->a, bestPlan.rCost, bestPlan.plan.nRow,
109771                bestPlan.plan.nOBSat, bestPlan.plan.wsFlags));
109772    if( (bestPlan.plan.wsFlags & WHERE_DISTINCT)!=0 ){
109773      assert( pWInfo->eDistinct==0 );
109774      pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
109775    }
109776    andFlags &= bestPlan.plan.wsFlags;
109777    pLevel->plan = bestPlan.plan;
109778    pLevel->iTabCur = pTabList->a[bestJ].iCursor;
109779    testcase( bestPlan.plan.wsFlags & WHERE_INDEXED );
109780    testcase( bestPlan.plan.wsFlags & WHERE_TEMP_INDEX );
109781    if( bestPlan.plan.wsFlags & (WHERE_INDEXED|WHERE_TEMP_INDEX) ){
109782      if( (wctrlFlags & WHERE_ONETABLE_ONLY)
109783       && (bestPlan.plan.wsFlags & WHERE_TEMP_INDEX)==0
109784      ){
109785        pLevel->iIdxCur = iIdxCur;
109786      }else{
109787        pLevel->iIdxCur = pParse->nTab++;
109788      }
109789    }else{
109790      pLevel->iIdxCur = -1;
109791    }
109792    sWBI.notValid &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);
109793    pLevel->iFrom = (u8)bestJ;
109794    if( bestPlan.plan.nRow>=(double)1 ){
109795      pParse->nQueryLoop *= bestPlan.plan.nRow;
109796    }
109797
109798    /* Check that if the table scanned by this loop iteration had an
109799    ** INDEXED BY clause attached to it, that the named index is being
109800    ** used for the scan. If not, then query compilation has failed.
109801    ** Return an error.
109802    */
109803    pIdx = pTabList->a[bestJ].pIndex;
109804    if( pIdx ){
109805      if( (bestPlan.plan.wsFlags & WHERE_INDEXED)==0 ){
109806        sqlite3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName);
109807        goto whereBeginError;
109808      }else{
109809        /* If an INDEXED BY clause is used, the bestIndex() function is
109810        ** guaranteed to find the index specified in the INDEXED BY clause
109811        ** if it find an index at all. */
109812        assert( bestPlan.plan.u.pIdx==pIdx );
109813      }
109814    }
109815  }
109816  WHERETRACE(("*** Optimizer Finished ***\n"));
109817  if( pParse->nErr || db->mallocFailed ){
109818    goto whereBeginError;
109819  }
109820  if( nTabList ){
109821    pLevel--;
109822    pWInfo->nOBSat = pLevel->plan.nOBSat;
109823  }else{
109824    pWInfo->nOBSat = 0;
109825  }
109826
109827  /* If the total query only selects a single row, then the ORDER BY
109828  ** clause is irrelevant.
109829  */
109830  if( (andFlags & WHERE_UNIQUE)!=0 && pOrderBy ){
109831    assert( nTabList==0 || (pLevel->plan.wsFlags & WHERE_ALL_UNIQUE)!=0 );
109832    pWInfo->nOBSat = pOrderBy->nExpr;
109833  }
109834
109835  /* If the caller is an UPDATE or DELETE statement that is requesting
109836  ** to use a one-pass algorithm, determine if this is appropriate.
109837  ** The one-pass algorithm only works if the WHERE clause constraints
109838  ** the statement to update a single row.
109839  */
109840  assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
109841  if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
109842    pWInfo->okOnePass = 1;
109843    pWInfo->a[0].plan.wsFlags &= ~WHERE_IDX_ONLY;
109844  }
109845
109846  /* Open all tables in the pTabList and any indices selected for
109847  ** searching those tables.
109848  */
109849  sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
109850  notReady = ~(Bitmask)0;
109851  pWInfo->nRowOut = (double)1;
109852  for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
109853    Table *pTab;     /* Table to open */
109854    int iDb;         /* Index of database containing table/index */
109855    struct SrcList_item *pTabItem;
109856
109857    pTabItem = &pTabList->a[pLevel->iFrom];
109858    pTab = pTabItem->pTab;
109859    pWInfo->nRowOut *= pLevel->plan.nRow;
109860    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
109861    if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
109862      /* Do nothing */
109863    }else
109864#ifndef SQLITE_OMIT_VIRTUALTABLE
109865    if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
109866      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
109867      int iCur = pTabItem->iCursor;
109868      sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
109869    }else if( IsVirtual(pTab) ){
109870      /* noop */
109871    }else
109872#endif
109873    if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
109874         && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
109875      int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
109876      sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
109877      testcase( pTab->nCol==BMS-1 );
109878      testcase( pTab->nCol==BMS );
109879      if( !pWInfo->okOnePass && pTab->nCol<BMS ){
109880        Bitmask b = pTabItem->colUsed;
109881        int n = 0;
109882        for(; b; b=b>>1, n++){}
109883        sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
109884                            SQLITE_INT_TO_PTR(n), P4_INT32);
109885        assert( n<=pTab->nCol );
109886      }
109887    }else{
109888      sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
109889    }
109890#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
109891    if( (pLevel->plan.wsFlags & WHERE_TEMP_INDEX)!=0 ){
109892      constructAutomaticIndex(pParse, sWBI.pWC, pTabItem, notReady, pLevel);
109893    }else
109894#endif
109895    if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
109896      Index *pIx = pLevel->plan.u.pIdx;
109897      KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
109898      int iIndexCur = pLevel->iIdxCur;
109899      assert( pIx->pSchema==pTab->pSchema );
109900      assert( iIndexCur>=0 );
109901      sqlite3VdbeAddOp4(v, OP_OpenRead, iIndexCur, pIx->tnum, iDb,
109902                        (char*)pKey, P4_KEYINFO_HANDOFF);
109903      VdbeComment((v, "%s", pIx->zName));
109904    }
109905    sqlite3CodeVerifySchema(pParse, iDb);
109906    notReady &= ~getMask(sWBI.pWC->pMaskSet, pTabItem->iCursor);
109907  }
109908  pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
109909  if( db->mallocFailed ) goto whereBeginError;
109910
109911  /* Generate the code to do the search.  Each iteration of the for
109912  ** loop below generates code for a single nested loop of the VM
109913  ** program.
109914  */
109915  notReady = ~(Bitmask)0;
109916  for(ii=0; ii<nTabList; ii++){
109917    pLevel = &pWInfo->a[ii];
109918    explainOneScan(pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags);
109919    notReady = codeOneLoopStart(pWInfo, ii, wctrlFlags, notReady);
109920    pWInfo->iContinue = pLevel->addrCont;
109921  }
109922
109923#ifdef SQLITE_TEST  /* For testing and debugging use only */
109924  /* Record in the query plan information about the current table
109925  ** and the index used to access it (if any).  If the table itself
109926  ** is not used, its name is just '{}'.  If no index is used
109927  ** the index is listed as "{}".  If the primary key is used the
109928  ** index name is '*'.
109929  */
109930  for(ii=0; ii<nTabList; ii++){
109931    char *z;
109932    int n;
109933    int w;
109934    struct SrcList_item *pTabItem;
109935
109936    pLevel = &pWInfo->a[ii];
109937    w = pLevel->plan.wsFlags;
109938    pTabItem = &pTabList->a[pLevel->iFrom];
109939    z = pTabItem->zAlias;
109940    if( z==0 ) z = pTabItem->pTab->zName;
109941    n = sqlite3Strlen30(z);
109942    if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
109943      if( (w & WHERE_IDX_ONLY)!=0 && (w & WHERE_COVER_SCAN)==0 ){
109944        memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
109945        nQPlan += 2;
109946      }else{
109947        memcpy(&sqlite3_query_plan[nQPlan], z, n);
109948        nQPlan += n;
109949      }
109950      sqlite3_query_plan[nQPlan++] = ' ';
109951    }
109952    testcase( w & WHERE_ROWID_EQ );
109953    testcase( w & WHERE_ROWID_RANGE );
109954    if( w & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
109955      memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
109956      nQPlan += 2;
109957    }else if( (w & WHERE_INDEXED)!=0 && (w & WHERE_COVER_SCAN)==0 ){
109958      n = sqlite3Strlen30(pLevel->plan.u.pIdx->zName);
109959      if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
109960        memcpy(&sqlite3_query_plan[nQPlan], pLevel->plan.u.pIdx->zName, n);
109961        nQPlan += n;
109962        sqlite3_query_plan[nQPlan++] = ' ';
109963      }
109964    }else{
109965      memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
109966      nQPlan += 3;
109967    }
109968  }
109969  while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
109970    sqlite3_query_plan[--nQPlan] = 0;
109971  }
109972  sqlite3_query_plan[nQPlan] = 0;
109973  nQPlan = 0;
109974#endif /* SQLITE_TEST // Testing and debugging use only */
109975
109976  /* Record the continuation address in the WhereInfo structure.  Then
109977  ** clean up and return.
109978  */
109979  return pWInfo;
109980
109981  /* Jump here if malloc fails */
109982whereBeginError:
109983  if( pWInfo ){
109984    pParse->nQueryLoop = pWInfo->savedNQueryLoop;
109985    whereInfoFree(db, pWInfo);
109986  }
109987  return 0;
109988}
109989
109990/*
109991** Generate the end of the WHERE loop.  See comments on
109992** sqlite3WhereBegin() for additional information.
109993*/
109994SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
109995  Parse *pParse = pWInfo->pParse;
109996  Vdbe *v = pParse->pVdbe;
109997  int i;
109998  WhereLevel *pLevel;
109999  SrcList *pTabList = pWInfo->pTabList;
110000  sqlite3 *db = pParse->db;
110001
110002  /* Generate loop termination code.
110003  */
110004  sqlite3ExprCacheClear(pParse);
110005  for(i=pWInfo->nLevel-1; i>=0; i--){
110006    pLevel = &pWInfo->a[i];
110007    sqlite3VdbeResolveLabel(v, pLevel->addrCont);
110008    if( pLevel->op!=OP_Noop ){
110009      sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
110010      sqlite3VdbeChangeP5(v, pLevel->p5);
110011    }
110012    if( pLevel->plan.wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
110013      struct InLoop *pIn;
110014      int j;
110015      sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
110016      for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
110017        sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
110018        sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
110019        sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
110020      }
110021      sqlite3DbFree(db, pLevel->u.in.aInLoop);
110022    }
110023    sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
110024    if( pLevel->iLeftJoin ){
110025      int addr;
110026      addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
110027      assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
110028           || (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 );
110029      if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
110030        sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
110031      }
110032      if( pLevel->iIdxCur>=0 ){
110033        sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
110034      }
110035      if( pLevel->op==OP_Return ){
110036        sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
110037      }else{
110038        sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
110039      }
110040      sqlite3VdbeJumpHere(v, addr);
110041    }
110042  }
110043
110044  /* The "break" point is here, just past the end of the outer loop.
110045  ** Set it.
110046  */
110047  sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
110048
110049  /* Close all of the cursors that were opened by sqlite3WhereBegin.
110050  */
110051  assert( pWInfo->nLevel==1 || pWInfo->nLevel==pTabList->nSrc );
110052  for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
110053    Index *pIdx = 0;
110054    struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
110055    Table *pTab = pTabItem->pTab;
110056    assert( pTab!=0 );
110057    if( (pTab->tabFlags & TF_Ephemeral)==0
110058     && pTab->pSelect==0
110059     && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
110060    ){
110061      int ws = pLevel->plan.wsFlags;
110062      if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
110063        sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
110064      }
110065      if( (ws & WHERE_INDEXED)!=0 && (ws & WHERE_TEMP_INDEX)==0 ){
110066        sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
110067      }
110068    }
110069
110070    /* If this scan uses an index, make code substitutions to read data
110071    ** from the index in preference to the table. Sometimes, this means
110072    ** the table need never be read from. This is a performance boost,
110073    ** as the vdbe level waits until the table is read before actually
110074    ** seeking the table cursor to the record corresponding to the current
110075    ** position in the index.
110076    **
110077    ** Calls to the code generator in between sqlite3WhereBegin and
110078    ** sqlite3WhereEnd will have created code that references the table
110079    ** directly.  This loop scans all that code looking for opcodes
110080    ** that reference the table and converts them into opcodes that
110081    ** reference the index.
110082    */
110083    if( pLevel->plan.wsFlags & WHERE_INDEXED ){
110084      pIdx = pLevel->plan.u.pIdx;
110085    }else if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
110086      pIdx = pLevel->u.pCovidx;
110087    }
110088    if( pIdx && !db->mallocFailed){
110089      int k, j, last;
110090      VdbeOp *pOp;
110091
110092      pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
110093      last = sqlite3VdbeCurrentAddr(v);
110094      for(k=pWInfo->iTop; k<last; k++, pOp++){
110095        if( pOp->p1!=pLevel->iTabCur ) continue;
110096        if( pOp->opcode==OP_Column ){
110097          for(j=0; j<pIdx->nColumn; j++){
110098            if( pOp->p2==pIdx->aiColumn[j] ){
110099              pOp->p2 = j;
110100              pOp->p1 = pLevel->iIdxCur;
110101              break;
110102            }
110103          }
110104          assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
110105               || j<pIdx->nColumn );
110106        }else if( pOp->opcode==OP_Rowid ){
110107          pOp->p1 = pLevel->iIdxCur;
110108          pOp->opcode = OP_IdxRowid;
110109        }
110110      }
110111    }
110112  }
110113
110114  /* Final cleanup
110115  */
110116  pParse->nQueryLoop = pWInfo->savedNQueryLoop;
110117  whereInfoFree(db, pWInfo);
110118  return;
110119}
110120
110121/************** End of where.c ***********************************************/
110122/************** Begin file parse.c *******************************************/
110123/* Driver template for the LEMON parser generator.
110124** The author disclaims copyright to this source code.
110125**
110126** This version of "lempar.c" is modified, slightly, for use by SQLite.
110127** The only modifications are the addition of a couple of NEVER()
110128** macros to disable tests that are needed in the case of a general
110129** LALR(1) grammar but which are always false in the
110130** specific grammar used by SQLite.
110131*/
110132/* First off, code is included that follows the "include" declaration
110133** in the input grammar file. */
110134/* #include <stdio.h> */
110135
110136
110137/*
110138** Disable all error recovery processing in the parser push-down
110139** automaton.
110140*/
110141#define YYNOERRORRECOVERY 1
110142
110143/*
110144** Make yytestcase() the same as testcase()
110145*/
110146#define yytestcase(X) testcase(X)
110147
110148/*
110149** An instance of this structure holds information about the
110150** LIMIT clause of a SELECT statement.
110151*/
110152struct LimitVal {
110153  Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
110154  Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
110155};
110156
110157/*
110158** An instance of this structure is used to store the LIKE,
110159** GLOB, NOT LIKE, and NOT GLOB operators.
110160*/
110161struct LikeOp {
110162  Token eOperator;  /* "like" or "glob" or "regexp" */
110163  int bNot;         /* True if the NOT keyword is present */
110164};
110165
110166/*
110167** An instance of the following structure describes the event of a
110168** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
110169** TK_DELETE, or TK_INSTEAD.  If the event is of the form
110170**
110171**      UPDATE ON (a,b,c)
110172**
110173** Then the "b" IdList records the list "a,b,c".
110174*/
110175struct TrigEvent { int a; IdList * b; };
110176
110177/*
110178** An instance of this structure holds the ATTACH key and the key type.
110179*/
110180struct AttachKey { int type;  Token key; };
110181
110182/*
110183** One or more VALUES claues
110184*/
110185struct ValueList {
110186  ExprList *pList;
110187  Select *pSelect;
110188};
110189
110190
110191  /* This is a utility routine used to set the ExprSpan.zStart and
110192  ** ExprSpan.zEnd values of pOut so that the span covers the complete
110193  ** range of text beginning with pStart and going to the end of pEnd.
110194  */
110195  static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
110196    pOut->zStart = pStart->z;
110197    pOut->zEnd = &pEnd->z[pEnd->n];
110198  }
110199
110200  /* Construct a new Expr object from a single identifier.  Use the
110201  ** new Expr to populate pOut.  Set the span of pOut to be the identifier
110202  ** that created the expression.
110203  */
110204  static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
110205    pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
110206    pOut->zStart = pValue->z;
110207    pOut->zEnd = &pValue->z[pValue->n];
110208  }
110209
110210  /* This routine constructs a binary expression node out of two ExprSpan
110211  ** objects and uses the result to populate a new ExprSpan object.
110212  */
110213  static void spanBinaryExpr(
110214    ExprSpan *pOut,     /* Write the result here */
110215    Parse *pParse,      /* The parsing context.  Errors accumulate here */
110216    int op,             /* The binary operation */
110217    ExprSpan *pLeft,    /* The left operand */
110218    ExprSpan *pRight    /* The right operand */
110219  ){
110220    pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
110221    pOut->zStart = pLeft->zStart;
110222    pOut->zEnd = pRight->zEnd;
110223  }
110224
110225  /* Construct an expression node for a unary postfix operator
110226  */
110227  static void spanUnaryPostfix(
110228    ExprSpan *pOut,        /* Write the new expression node here */
110229    Parse *pParse,         /* Parsing context to record errors */
110230    int op,                /* The operator */
110231    ExprSpan *pOperand,    /* The operand */
110232    Token *pPostOp         /* The operand token for setting the span */
110233  ){
110234    pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
110235    pOut->zStart = pOperand->zStart;
110236    pOut->zEnd = &pPostOp->z[pPostOp->n];
110237  }
110238
110239  /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
110240  ** unary TK_ISNULL or TK_NOTNULL expression. */
110241  static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
110242    sqlite3 *db = pParse->db;
110243    if( db->mallocFailed==0 && pY->op==TK_NULL ){
110244      pA->op = (u8)op;
110245      sqlite3ExprDelete(db, pA->pRight);
110246      pA->pRight = 0;
110247    }
110248  }
110249
110250  /* Construct an expression node for a unary prefix operator
110251  */
110252  static void spanUnaryPrefix(
110253    ExprSpan *pOut,        /* Write the new expression node here */
110254    Parse *pParse,         /* Parsing context to record errors */
110255    int op,                /* The operator */
110256    ExprSpan *pOperand,    /* The operand */
110257    Token *pPreOp         /* The operand token for setting the span */
110258  ){
110259    pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
110260    pOut->zStart = pPreOp->z;
110261    pOut->zEnd = pOperand->zEnd;
110262  }
110263/* Next is all token values, in a form suitable for use by makeheaders.
110264** This section will be null unless lemon is run with the -m switch.
110265*/
110266/*
110267** These constants (all generated automatically by the parser generator)
110268** specify the various kinds of tokens (terminals) that the parser
110269** understands.
110270**
110271** Each symbol here is a terminal symbol in the grammar.
110272*/
110273/* Make sure the INTERFACE macro is defined.
110274*/
110275#ifndef INTERFACE
110276# define INTERFACE 1
110277#endif
110278/* The next thing included is series of defines which control
110279** various aspects of the generated parser.
110280**    YYCODETYPE         is the data type used for storing terminal
110281**                       and nonterminal numbers.  "unsigned char" is
110282**                       used if there are fewer than 250 terminals
110283**                       and nonterminals.  "int" is used otherwise.
110284**    YYNOCODE           is a number of type YYCODETYPE which corresponds
110285**                       to no legal terminal or nonterminal number.  This
110286**                       number is used to fill in empty slots of the hash
110287**                       table.
110288**    YYFALLBACK         If defined, this indicates that one or more tokens
110289**                       have fall-back values which should be used if the
110290**                       original value of the token will not parse.
110291**    YYACTIONTYPE       is the data type used for storing terminal
110292**                       and nonterminal numbers.  "unsigned char" is
110293**                       used if there are fewer than 250 rules and
110294**                       states combined.  "int" is used otherwise.
110295**    sqlite3ParserTOKENTYPE     is the data type used for minor tokens given
110296**                       directly to the parser from the tokenizer.
110297**    YYMINORTYPE        is the data type used for all minor tokens.
110298**                       This is typically a union of many types, one of
110299**                       which is sqlite3ParserTOKENTYPE.  The entry in the union
110300**                       for base tokens is called "yy0".
110301**    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
110302**                       zero the stack is dynamically sized using realloc()
110303**    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
110304**    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
110305**    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
110306**    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
110307**    YYNSTATE           the combined number of states.
110308**    YYNRULE            the number of rules in the grammar
110309**    YYERRORSYMBOL      is the code number of the error symbol.  If not
110310**                       defined, then do no error processing.
110311*/
110312#define YYCODETYPE unsigned char
110313#define YYNOCODE 251
110314#define YYACTIONTYPE unsigned short int
110315#define YYWILDCARD 67
110316#define sqlite3ParserTOKENTYPE Token
110317typedef union {
110318  int yyinit;
110319  sqlite3ParserTOKENTYPE yy0;
110320  struct LimitVal yy64;
110321  Expr* yy122;
110322  Select* yy159;
110323  IdList* yy180;
110324  struct {int value; int mask;} yy207;
110325  u8 yy258;
110326  u16 yy305;
110327  struct LikeOp yy318;
110328  TriggerStep* yy327;
110329  ExprSpan yy342;
110330  SrcList* yy347;
110331  int yy392;
110332  struct TrigEvent yy410;
110333  ExprList* yy442;
110334  struct ValueList yy487;
110335} YYMINORTYPE;
110336#ifndef YYSTACKDEPTH
110337#define YYSTACKDEPTH 100
110338#endif
110339#define sqlite3ParserARG_SDECL Parse *pParse;
110340#define sqlite3ParserARG_PDECL ,Parse *pParse
110341#define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
110342#define sqlite3ParserARG_STORE yypParser->pParse = pParse
110343#define YYNSTATE 627
110344#define YYNRULE 327
110345#define YYFALLBACK 1
110346#define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)
110347#define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)
110348#define YY_ERROR_ACTION   (YYNSTATE+YYNRULE)
110349
110350/* The yyzerominor constant is used to initialize instances of
110351** YYMINORTYPE objects to zero. */
110352static const YYMINORTYPE yyzerominor = { 0 };
110353
110354/* Define the yytestcase() macro to be a no-op if is not already defined
110355** otherwise.
110356**
110357** Applications can choose to define yytestcase() in the %include section
110358** to a macro that can assist in verifying code coverage.  For production
110359** code the yytestcase() macro should be turned off.  But it is useful
110360** for testing.
110361*/
110362#ifndef yytestcase
110363# define yytestcase(X)
110364#endif
110365
110366
110367/* Next are the tables used to determine what action to take based on the
110368** current state and lookahead token.  These tables are used to implement
110369** functions that take a state number and lookahead value and return an
110370** action integer.
110371**
110372** Suppose the action integer is N.  Then the action is determined as
110373** follows
110374**
110375**   0 <= N < YYNSTATE                  Shift N.  That is, push the lookahead
110376**                                      token onto the stack and goto state N.
110377**
110378**   YYNSTATE <= N < YYNSTATE+YYNRULE   Reduce by rule N-YYNSTATE.
110379**
110380**   N == YYNSTATE+YYNRULE              A syntax error has occurred.
110381**
110382**   N == YYNSTATE+YYNRULE+1            The parser accepts its input.
110383**
110384**   N == YYNSTATE+YYNRULE+2            No such action.  Denotes unused
110385**                                      slots in the yy_action[] table.
110386**
110387** The action table is constructed as a single large table named yy_action[].
110388** Given state S and lookahead X, the action is computed as
110389**
110390**      yy_action[ yy_shift_ofst[S] + X ]
110391**
110392** If the index value yy_shift_ofst[S]+X is out of range or if the value
110393** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
110394** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
110395** and that yy_default[S] should be used instead.
110396**
110397** The formula above is for computing the action when the lookahead is
110398** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
110399** a reduce action) then the yy_reduce_ofst[] array is used in place of
110400** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
110401** YY_SHIFT_USE_DFLT.
110402**
110403** The following are the tables generated in this section:
110404**
110405**  yy_action[]        A single table containing all actions.
110406**  yy_lookahead[]     A table containing the lookahead for each entry in
110407**                     yy_action.  Used to detect hash collisions.
110408**  yy_shift_ofst[]    For each state, the offset into yy_action for
110409**                     shifting terminals.
110410**  yy_reduce_ofst[]   For each state, the offset into yy_action for
110411**                     shifting non-terminals after a reduce.
110412**  yy_default[]       Default action for each state.
110413*/
110414#define YY_ACTTAB_COUNT (1564)
110415static const YYACTIONTYPE yy_action[] = {
110416 /*     0 */   309,  955,  184,  417,    2,  171,  624,  594,   56,   56,
110417 /*    10 */    56,   56,   49,   54,   54,   54,   54,   53,   53,   52,
110418 /*    20 */    52,   52,   51,  233,  620,  619,  298,  620,  619,  234,
110419 /*    30 */   587,  581,   56,   56,   56,   56,   19,   54,   54,   54,
110420 /*    40 */    54,   53,   53,   52,   52,   52,   51,  233,  605,   57,
110421 /*    50 */    58,   48,  579,  578,  580,  580,   55,   55,   56,   56,
110422 /*    60 */    56,   56,  541,   54,   54,   54,   54,   53,   53,   52,
110423 /*    70 */    52,   52,   51,  233,  309,  594,  325,  196,  195,  194,
110424 /*    80 */    33,   54,   54,   54,   54,   53,   53,   52,   52,   52,
110425 /*    90 */    51,  233,  617,  616,  165,  617,  616,  380,  377,  376,
110426 /*   100 */   407,  532,  576,  576,  587,  581,  303,  422,  375,   59,
110427 /*   110 */    53,   53,   52,   52,   52,   51,  233,   50,   47,  146,
110428 /*   120 */   574,  545,   65,   57,   58,   48,  579,  578,  580,  580,
110429 /*   130 */    55,   55,   56,   56,   56,   56,  213,   54,   54,   54,
110430 /*   140 */    54,   53,   53,   52,   52,   52,   51,  233,  309,  223,
110431 /*   150 */   539,  420,  170,  176,  138,  280,  383,  275,  382,  168,
110432 /*   160 */   489,  551,  409,  668,  620,  619,  271,  438,  409,  438,
110433 /*   170 */   550,  604,   67,  482,  507,  618,  599,  412,  587,  581,
110434 /*   180 */   600,  483,  618,  412,  618,  598,   91,  439,  440,  439,
110435 /*   190 */   335,  598,   73,  669,  222,  266,  480,   57,   58,   48,
110436 /*   200 */   579,  578,  580,  580,   55,   55,   56,   56,   56,   56,
110437 /*   210 */   670,   54,   54,   54,   54,   53,   53,   52,   52,   52,
110438 /*   220 */    51,  233,  309,  279,  232,  231,    1,  132,  200,  385,
110439 /*   230 */   620,  619,  617,  616,  278,  435,  289,  563,  175,  262,
110440 /*   240 */   409,  264,  437,  497,  436,  166,  441,  568,  336,  568,
110441 /*   250 */   201,  537,  587,  581,  599,  412,  165,  594,  600,  380,
110442 /*   260 */   377,  376,  597,  598,   92,  523,  618,  569,  569,  592,
110443 /*   270 */   375,   57,   58,   48,  579,  578,  580,  580,   55,   55,
110444 /*   280 */    56,   56,   56,   56,  597,   54,   54,   54,   54,   53,
110445 /*   290 */    53,   52,   52,   52,   51,  233,  309,  463,  617,  616,
110446 /*   300 */   590,  590,  590,  174,  272,  396,  409,  272,  409,  548,
110447 /*   310 */   397,  620,  619,   68,  326,  620,  619,  620,  619,  618,
110448 /*   320 */   546,  412,  618,  412,  471,  594,  587,  581,  472,  598,
110449 /*   330 */    92,  598,   92,   52,   52,   52,   51,  233,  513,  512,
110450 /*   340 */   206,  322,  363,  464,  221,   57,   58,   48,  579,  578,
110451 /*   350 */   580,  580,   55,   55,   56,   56,   56,   56,  529,   54,
110452 /*   360 */    54,   54,   54,   53,   53,   52,   52,   52,   51,  233,
110453 /*   370 */   309,  396,  409,  396,  597,  372,  386,  530,  347,  617,
110454 /*   380 */   616,  575,  202,  617,  616,  617,  616,  412,  620,  619,
110455 /*   390 */   145,  255,  346,  254,  577,  598,   74,  351,   45,  489,
110456 /*   400 */   587,  581,  235,  189,  464,  544,  167,  296,  187,  469,
110457 /*   410 */   479,   67,   62,   39,  618,  546,  597,  345,  573,   57,
110458 /*   420 */    58,   48,  579,  578,  580,  580,   55,   55,   56,   56,
110459 /*   430 */    56,   56,    6,   54,   54,   54,   54,   53,   53,   52,
110460 /*   440 */    52,   52,   51,  233,  309,  562,  558,  407,  528,  576,
110461 /*   450 */   576,  344,  255,  346,  254,  182,  617,  616,  503,  504,
110462 /*   460 */   314,  409,  557,  235,  166,  271,  409,  352,  564,  181,
110463 /*   470 */   407,  546,  576,  576,  587,  581,  412,  537,  556,  561,
110464 /*   480 */   517,  412,  618,  249,  598,   16,    7,   36,  467,  598,
110465 /*   490 */    92,  516,  618,   57,   58,   48,  579,  578,  580,  580,
110466 /*   500 */    55,   55,   56,   56,   56,   56,  541,   54,   54,   54,
110467 /*   510 */    54,   53,   53,   52,   52,   52,   51,  233,  309,  327,
110468 /*   520 */   572,  571,  525,  558,  560,  394,  871,  246,  409,  248,
110469 /*   530 */   171,  392,  594,  219,  407,  409,  576,  576,  502,  557,
110470 /*   540 */   364,  145,  510,  412,  407,  229,  576,  576,  587,  581,
110471 /*   550 */   412,  598,   92,  381,  269,  556,  166,  400,  598,   69,
110472 /*   560 */   501,  419,  945,  199,  945,  198,  546,   57,   58,   48,
110473 /*   570 */   579,  578,  580,  580,   55,   55,   56,   56,   56,   56,
110474 /*   580 */   568,   54,   54,   54,   54,   53,   53,   52,   52,   52,
110475 /*   590 */    51,  233,  309,  317,  419,  944,  508,  944,  308,  597,
110476 /*   600 */   594,  565,  490,  212,  173,  247,  423,  615,  614,  613,
110477 /*   610 */   323,  197,  143,  405,  572,  571,  489,   66,   50,   47,
110478 /*   620 */   146,  594,  587,  581,  232,  231,  559,  427,   67,  555,
110479 /*   630 */    15,  618,  186,  543,  303,  421,   35,  206,  432,  423,
110480 /*   640 */   552,   57,   58,   48,  579,  578,  580,  580,   55,   55,
110481 /*   650 */    56,   56,   56,   56,  205,   54,   54,   54,   54,   53,
110482 /*   660 */    53,   52,   52,   52,   51,  233,  309,  569,  569,  260,
110483 /*   670 */   268,  597,   12,  373,  568,  166,  409,  313,  409,  420,
110484 /*   680 */   409,  473,  473,  365,  618,   50,   47,  146,  597,  594,
110485 /*   690 */   468,  412,  166,  412,  351,  412,  587,  581,   32,  598,
110486 /*   700 */    94,  598,   97,  598,   95,  627,  625,  329,  142,   50,
110487 /*   710 */    47,  146,  333,  349,  358,   57,   58,   48,  579,  578,
110488 /*   720 */   580,  580,   55,   55,   56,   56,   56,   56,  409,   54,
110489 /*   730 */    54,   54,   54,   53,   53,   52,   52,   52,   51,  233,
110490 /*   740 */   309,  409,  388,  412,  409,   22,  565,  404,  212,  362,
110491 /*   750 */   389,  598,  104,  359,  409,  156,  412,  409,  603,  412,
110492 /*   760 */   537,  331,  569,  569,  598,  103,  493,  598,  105,  412,
110493 /*   770 */   587,  581,  412,  260,  549,  618,   11,  598,  106,  521,
110494 /*   780 */   598,  133,  169,  457,  456,  170,   35,  601,  618,   57,
110495 /*   790 */    58,   48,  579,  578,  580,  580,   55,   55,   56,   56,
110496 /*   800 */    56,   56,  409,   54,   54,   54,   54,   53,   53,   52,
110497 /*   810 */    52,   52,   51,  233,  309,  409,  259,  412,  409,   50,
110498 /*   820 */    47,  146,  357,  318,  355,  598,  134,  527,  352,  337,
110499 /*   830 */   412,  409,  356,  412,  357,  409,  357,  618,  598,   98,
110500 /*   840 */   129,  598,  102,  618,  587,  581,  412,   21,  235,  618,
110501 /*   850 */   412,  618,  211,  143,  598,  101,   30,  167,  598,   93,
110502 /*   860 */   350,  535,  203,   57,   58,   48,  579,  578,  580,  580,
110503 /*   870 */    55,   55,   56,   56,   56,   56,  409,   54,   54,   54,
110504 /*   880 */    54,   53,   53,   52,   52,   52,   51,  233,  309,  409,
110505 /*   890 */   526,  412,  409,  425,  215,  305,  597,  551,  141,  598,
110506 /*   900 */   100,   40,  409,   38,  412,  409,  550,  412,  409,  228,
110507 /*   910 */   220,  314,  598,   77,  500,  598,   96,  412,  587,  581,
110508 /*   920 */   412,  338,  253,  412,  218,  598,  137,  379,  598,  136,
110509 /*   930 */    28,  598,  135,  270,  715,  210,  481,   57,   58,   48,
110510 /*   940 */   579,  578,  580,  580,   55,   55,   56,   56,   56,   56,
110511 /*   950 */   409,   54,   54,   54,   54,   53,   53,   52,   52,   52,
110512 /*   960 */    51,  233,  309,  409,  272,  412,  409,  315,  147,  597,
110513 /*   970 */   272,  626,    2,  598,   76,  209,  409,  127,  412,  618,
110514 /*   980 */   126,  412,  409,  621,  235,  618,  598,   90,  374,  598,
110515 /*   990 */    89,  412,  587,  581,   27,  260,  350,  412,  618,  598,
110516 /*  1000 */    75,  321,  541,  541,  125,  598,   88,  320,  278,  597,
110517 /*  1010 */   618,   57,   46,   48,  579,  578,  580,  580,   55,   55,
110518 /*  1020 */    56,   56,   56,   56,  409,   54,   54,   54,   54,   53,
110519 /*  1030 */    53,   52,   52,   52,   51,  233,  309,  409,  450,  412,
110520 /*  1040 */   164,  284,  282,  272,  609,  424,  304,  598,   87,  370,
110521 /*  1050 */   409,  477,  412,  409,  608,  409,  607,  602,  618,  618,
110522 /*  1060 */   598,   99,  586,  585,  122,  412,  587,  581,  412,  618,
110523 /*  1070 */   412,  618,  618,  598,   86,  366,  598,   17,  598,   85,
110524 /*  1080 */   319,  185,  519,  518,  583,  582,   58,   48,  579,  578,
110525 /*  1090 */   580,  580,   55,   55,   56,   56,   56,   56,  409,   54,
110526 /*  1100 */    54,   54,   54,   53,   53,   52,   52,   52,   51,  233,
110527 /*  1110 */   309,  584,  409,  412,  409,  260,  260,  260,  408,  591,
110528 /*  1120 */   474,  598,   84,  170,  409,  466,  518,  412,  121,  412,
110529 /*  1130 */   618,  618,  618,  618,  618,  598,   83,  598,   72,  412,
110530 /*  1140 */   587,  581,   51,  233,  625,  329,  470,  598,   71,  257,
110531 /*  1150 */   159,  120,   14,  462,  157,  158,  117,  260,  448,  447,
110532 /*  1160 */   446,   48,  579,  578,  580,  580,   55,   55,   56,   56,
110533 /*  1170 */    56,   56,  618,   54,   54,   54,   54,   53,   53,   52,
110534 /*  1180 */    52,   52,   51,  233,   44,  403,  260,    3,  409,  459,
110535 /*  1190 */   260,  413,  619,  118,  398,   10,   25,   24,  554,  348,
110536 /*  1200 */   217,  618,  406,  412,  409,  618,    4,   44,  403,  618,
110537 /*  1210 */     3,  598,   82,  618,  413,  619,  455,  542,  115,  412,
110538 /*  1220 */   538,  401,  536,  274,  506,  406,  251,  598,   81,  216,
110539 /*  1230 */   273,  563,  618,  243,  453,  618,  154,  618,  618,  618,
110540 /*  1240 */   449,  416,  623,  110,  401,  618,  409,  236,   64,  123,
110541 /*  1250 */   487,   41,   42,  531,  563,  204,  409,  267,   43,  411,
110542 /*  1260 */   410,  412,  265,  592,  108,  618,  107,  434,  332,  598,
110543 /*  1270 */    80,  412,  618,  263,   41,   42,  443,  618,  409,  598,
110544 /*  1280 */    70,   43,  411,  410,  433,  261,  592,  149,  618,  597,
110545 /*  1290 */   256,  237,  188,  412,  590,  590,  590,  589,  588,   13,
110546 /*  1300 */   618,  598,   18,  328,  235,  618,   44,  403,  360,    3,
110547 /*  1310 */   418,  461,  339,  413,  619,  227,  124,  590,  590,  590,
110548 /*  1320 */   589,  588,   13,  618,  406,  409,  618,  409,  139,   34,
110549 /*  1330 */   403,  387,    3,  148,  622,  312,  413,  619,  311,  330,
110550 /*  1340 */   412,  460,  412,  401,  180,  353,  412,  406,  598,   79,
110551 /*  1350 */   598,   78,  250,  563,  598,    9,  618,  612,  611,  610,
110552 /*  1360 */   618,    8,  452,  442,  242,  415,  401,  618,  239,  235,
110553 /*  1370 */   179,  238,  428,   41,   42,  288,  563,  618,  618,  618,
110554 /*  1380 */    43,  411,  410,  618,  144,  592,  618,  618,  177,   61,
110555 /*  1390 */   618,  596,  391,  620,  619,  287,   41,   42,  414,  618,
110556 /*  1400 */   293,   30,  393,   43,  411,  410,  292,  618,  592,   31,
110557 /*  1410 */   618,  395,  291,   60,  230,   37,  590,  590,  590,  589,
110558 /*  1420 */   588,   13,  214,  553,  183,  290,  172,  301,  300,  299,
110559 /*  1430 */   178,  297,  595,  563,  451,   29,  285,  390,  540,  590,
110560 /*  1440 */   590,  590,  589,  588,   13,  283,  520,  534,  150,  533,
110561 /*  1450 */   241,  281,  384,  192,  191,  324,  515,  514,  276,  240,
110562 /*  1460 */   510,  523,  307,  511,  128,  592,  509,  225,  226,  486,
110563 /*  1470 */   485,  224,  152,  491,  464,  306,  484,  163,  153,  371,
110564 /*  1480 */   478,  151,  162,  258,  369,  161,  367,  208,  475,  476,
110565 /*  1490 */    26,  160,  465,  140,  361,  131,  590,  590,  590,  116,
110566 /*  1500 */   119,  454,  343,  155,  114,  342,  113,  112,  445,  111,
110567 /*  1510 */   130,  109,  431,  316,  426,  430,   23,  429,   20,  606,
110568 /*  1520 */   190,  507,  255,  341,  244,   63,  294,  593,  310,  570,
110569 /*  1530 */   277,  402,  354,  235,  567,  496,  495,  492,  494,  302,
110570 /*  1540 */   458,  378,  286,  245,  566,    5,  252,  547,  193,  444,
110571 /*  1550 */   233,  340,  207,  524,  368,  505,  334,  522,  499,  399,
110572 /*  1560 */   295,  498,  956,  488,
110573};
110574static const YYCODETYPE yy_lookahead[] = {
110575 /*     0 */    19,  142,  143,  144,  145,   24,    1,   26,   77,   78,
110576 /*    10 */    79,   80,   81,   82,   83,   84,   85,   86,   87,   88,
110577 /*    20 */    89,   90,   91,   92,   26,   27,   15,   26,   27,  197,
110578 /*    30 */    49,   50,   77,   78,   79,   80,  204,   82,   83,   84,
110579 /*    40 */    85,   86,   87,   88,   89,   90,   91,   92,   23,   68,
110580 /*    50 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
110581 /*    60 */    79,   80,  166,   82,   83,   84,   85,   86,   87,   88,
110582 /*    70 */    89,   90,   91,   92,   19,   94,   19,  105,  106,  107,
110583 /*    80 */    25,   82,   83,   84,   85,   86,   87,   88,   89,   90,
110584 /*    90 */    91,   92,   94,   95,   96,   94,   95,   99,  100,  101,
110585 /*   100 */   112,  205,  114,  115,   49,   50,   22,   23,  110,   54,
110586 /*   110 */    86,   87,   88,   89,   90,   91,   92,  221,  222,  223,
110587 /*   120 */    23,  120,   25,   68,   69,   70,   71,   72,   73,   74,
110588 /*   130 */    75,   76,   77,   78,   79,   80,   22,   82,   83,   84,
110589 /*   140 */    85,   86,   87,   88,   89,   90,   91,   92,   19,   92,
110590 /*   150 */    23,   67,   25,   96,   97,   98,   99,  100,  101,  102,
110591 /*   160 */   150,   32,  150,  118,   26,   27,  109,  150,  150,  150,
110592 /*   170 */    41,  161,  162,  180,  181,  165,  113,  165,   49,   50,
110593 /*   180 */   117,  188,  165,  165,  165,  173,  174,  170,  171,  170,
110594 /*   190 */   171,  173,  174,  118,  184,   16,  186,   68,   69,   70,
110595 /*   200 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
110596 /*   210 */   118,   82,   83,   84,   85,   86,   87,   88,   89,   90,
110597 /*   220 */    91,   92,   19,   98,   86,   87,   22,   24,  160,   88,
110598 /*   230 */    26,   27,   94,   95,  109,   97,  224,   66,  118,   60,
110599 /*   240 */   150,   62,  104,   23,  106,   25,  229,  230,  229,  230,
110600 /*   250 */   160,  150,   49,   50,  113,  165,   96,   26,  117,   99,
110601 /*   260 */   100,  101,  194,  173,  174,   94,  165,  129,  130,   98,
110602 /*   270 */   110,   68,   69,   70,   71,   72,   73,   74,   75,   76,
110603 /*   280 */    77,   78,   79,   80,  194,   82,   83,   84,   85,   86,
110604 /*   290 */    87,   88,   89,   90,   91,   92,   19,   11,   94,   95,
110605 /*   300 */   129,  130,  131,  118,  150,  215,  150,  150,  150,   25,
110606 /*   310 */   220,   26,   27,   22,  213,   26,   27,   26,   27,  165,
110607 /*   320 */    25,  165,  165,  165,   30,   94,   49,   50,   34,  173,
110608 /*   330 */   174,  173,  174,   88,   89,   90,   91,   92,    7,    8,
110609 /*   340 */   160,  187,   48,   57,  187,   68,   69,   70,   71,   72,
110610 /*   350 */    73,   74,   75,   76,   77,   78,   79,   80,   23,   82,
110611 /*   360 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
110612 /*   370 */    19,  215,  150,  215,  194,   19,  220,   88,  220,   94,
110613 /*   380 */    95,   23,  160,   94,   95,   94,   95,  165,   26,   27,
110614 /*   390 */    95,  105,  106,  107,  113,  173,  174,  217,   22,  150,
110615 /*   400 */    49,   50,  116,  119,   57,  120,   50,  158,   22,   21,
110616 /*   410 */   161,  162,  232,  136,  165,  120,  194,  237,   23,   68,
110617 /*   420 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
110618 /*   430 */    79,   80,   22,   82,   83,   84,   85,   86,   87,   88,
110619 /*   440 */    89,   90,   91,   92,   19,   23,   12,  112,   23,  114,
110620 /*   450 */   115,   63,  105,  106,  107,   23,   94,   95,   97,   98,
110621 /*   460 */   104,  150,   28,  116,   25,  109,  150,  150,   23,   23,
110622 /*   470 */   112,   25,  114,  115,   49,   50,  165,  150,   44,   11,
110623 /*   480 */    46,  165,  165,   16,  173,  174,   76,  136,  100,  173,
110624 /*   490 */   174,   57,  165,   68,   69,   70,   71,   72,   73,   74,
110625 /*   500 */    75,   76,   77,   78,   79,   80,  166,   82,   83,   84,
110626 /*   510 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  169,
110627 /*   520 */   170,  171,   23,   12,   23,  214,  138,   60,  150,   62,
110628 /*   530 */    24,  215,   26,  216,  112,  150,  114,  115,   36,   28,
110629 /*   540 */   213,   95,  103,  165,  112,  205,  114,  115,   49,   50,
110630 /*   550 */   165,  173,  174,   51,   23,   44,   25,   46,  173,  174,
110631 /*   560 */    58,   22,   23,   22,   25,  160,  120,   68,   69,   70,
110632 /*   570 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
110633 /*   580 */   230,   82,   83,   84,   85,   86,   87,   88,   89,   90,
110634 /*   590 */    91,   92,   19,  215,   22,   23,   23,   25,  163,  194,
110635 /*   600 */    94,  166,  167,  168,   25,  138,   67,    7,    8,    9,
110636 /*   610 */   108,  206,  207,  169,  170,  171,  150,   22,  221,  222,
110637 /*   620 */   223,   26,   49,   50,   86,   87,   23,  161,  162,   23,
110638 /*   630 */    22,  165,   24,  120,   22,   23,   25,  160,  241,   67,
110639 /*   640 */   176,   68,   69,   70,   71,   72,   73,   74,   75,   76,
110640 /*   650 */    77,   78,   79,   80,  160,   82,   83,   84,   85,   86,
110641 /*   660 */    87,   88,   89,   90,   91,   92,   19,  129,  130,  150,
110642 /*   670 */    23,  194,   35,   23,  230,   25,  150,  155,  150,   67,
110643 /*   680 */   150,  105,  106,  107,  165,  221,  222,  223,  194,   94,
110644 /*   690 */    23,  165,   25,  165,  217,  165,   49,   50,   25,  173,
110645 /*   700 */   174,  173,  174,  173,  174,    0,    1,    2,  118,  221,
110646 /*   710 */   222,  223,  193,  219,  237,   68,   69,   70,   71,   72,
110647 /*   720 */    73,   74,   75,   76,   77,   78,   79,   80,  150,   82,
110648 /*   730 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
110649 /*   740 */    19,  150,   19,  165,  150,   24,  166,  167,  168,  227,
110650 /*   750 */    27,  173,  174,  231,  150,   25,  165,  150,  172,  165,
110651 /*   760 */   150,  242,  129,  130,  173,  174,  180,  173,  174,  165,
110652 /*   770 */    49,   50,  165,  150,  176,  165,   35,  173,  174,  165,
110653 /*   780 */   173,  174,   35,   23,   23,   25,   25,  173,  165,   68,
110654 /*   790 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
110655 /*   800 */    79,   80,  150,   82,   83,   84,   85,   86,   87,   88,
110656 /*   810 */    89,   90,   91,   92,   19,  150,  193,  165,  150,  221,
110657 /*   820 */   222,  223,  150,  213,   19,  173,  174,   23,  150,   97,
110658 /*   830 */   165,  150,   27,  165,  150,  150,  150,  165,  173,  174,
110659 /*   840 */    22,  173,  174,  165,   49,   50,  165,   52,  116,  165,
110660 /*   850 */   165,  165,  206,  207,  173,  174,  126,   50,  173,  174,
110661 /*   860 */   128,   27,  160,   68,   69,   70,   71,   72,   73,   74,
110662 /*   870 */    75,   76,   77,   78,   79,   80,  150,   82,   83,   84,
110663 /*   880 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  150,
110664 /*   890 */    23,  165,  150,   23,  216,   25,  194,   32,   39,  173,
110665 /*   900 */   174,  135,  150,  137,  165,  150,   41,  165,  150,   52,
110666 /*   910 */   238,  104,  173,  174,   29,  173,  174,  165,   49,   50,
110667 /*   920 */   165,  219,  238,  165,  238,  173,  174,   52,  173,  174,
110668 /*   930 */    22,  173,  174,   23,   23,  160,   25,   68,   69,   70,
110669 /*   940 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
110670 /*   950 */   150,   82,   83,   84,   85,   86,   87,   88,   89,   90,
110671 /*   960 */    91,   92,   19,  150,  150,  165,  150,  245,  246,  194,
110672 /*   970 */   150,  144,  145,  173,  174,  160,  150,   22,  165,  165,
110673 /*   980 */    22,  165,  150,  150,  116,  165,  173,  174,   52,  173,
110674 /*   990 */   174,  165,   49,   50,   22,  150,  128,  165,  165,  173,
110675 /*  1000 */   174,  187,  166,  166,   22,  173,  174,  187,  109,  194,
110676 /*  1010 */   165,   68,   69,   70,   71,   72,   73,   74,   75,   76,
110677 /*  1020 */    77,   78,   79,   80,  150,   82,   83,   84,   85,   86,
110678 /*  1030 */    87,   88,   89,   90,   91,   92,   19,  150,  193,  165,
110679 /*  1040 */   102,  205,  205,  150,  150,  247,  248,  173,  174,   19,
110680 /*  1050 */   150,   20,  165,  150,  150,  150,  150,  150,  165,  165,
110681 /*  1060 */   173,  174,   49,   50,  104,  165,   49,   50,  165,  165,
110682 /*  1070 */   165,  165,  165,  173,  174,   43,  173,  174,  173,  174,
110683 /*  1080 */   187,   24,  190,  191,   71,   72,   69,   70,   71,   72,
110684 /*  1090 */    73,   74,   75,   76,   77,   78,   79,   80,  150,   82,
110685 /*  1100 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
110686 /*  1110 */    19,   98,  150,  165,  150,  150,  150,  150,  150,  150,
110687 /*  1120 */    59,  173,  174,   25,  150,  190,  191,  165,   53,  165,
110688 /*  1130 */   165,  165,  165,  165,  165,  173,  174,  173,  174,  165,
110689 /*  1140 */    49,   50,   91,   92,    1,    2,   53,  173,  174,  138,
110690 /*  1150 */   104,   22,    5,    1,   35,  118,  127,  150,  193,  193,
110691 /*  1160 */   193,   70,   71,   72,   73,   74,   75,   76,   77,   78,
110692 /*  1170 */    79,   80,  165,   82,   83,   84,   85,   86,   87,   88,
110693 /*  1180 */    89,   90,   91,   92,   19,   20,  150,   22,  150,   27,
110694 /*  1190 */   150,   26,   27,  108,  150,   22,   76,   76,  150,   25,
110695 /*  1200 */   193,  165,   37,  165,  150,  165,   22,   19,   20,  165,
110696 /*  1210 */    22,  173,  174,  165,   26,   27,   23,  150,  119,  165,
110697 /*  1220 */   150,   56,  150,  150,  150,   37,   16,  173,  174,  193,
110698 /*  1230 */   150,   66,  165,  193,    1,  165,  121,  165,  165,  165,
110699 /*  1240 */    20,  146,  147,  119,   56,  165,  150,  152,   16,  154,
110700 /*  1250 */   150,   86,   87,   88,   66,  160,  150,  150,   93,   94,
110701 /*  1260 */    95,  165,  150,   98,  108,  165,  127,   23,   65,  173,
110702 /*  1270 */   174,  165,  165,  150,   86,   87,  128,  165,  150,  173,
110703 /*  1280 */   174,   93,   94,   95,   23,  150,   98,   15,  165,  194,
110704 /*  1290 */   150,  140,   22,  165,  129,  130,  131,  132,  133,  134,
110705 /*  1300 */   165,  173,  174,    3,  116,  165,   19,   20,  150,   22,
110706 /*  1310 */     4,  150,  217,   26,   27,  179,  179,  129,  130,  131,
110707 /*  1320 */   132,  133,  134,  165,   37,  150,  165,  150,  164,   19,
110708 /*  1330 */    20,  150,   22,  246,  149,  249,   26,   27,  249,  244,
110709 /*  1340 */   165,  150,  165,   56,    6,  150,  165,   37,  173,  174,
110710 /*  1350 */   173,  174,  150,   66,  173,  174,  165,  149,  149,   13,
110711 /*  1360 */   165,   25,  150,  150,  150,  149,   56,  165,  150,  116,
110712 /*  1370 */   151,  150,  150,   86,   87,  150,   66,  165,  165,  165,
110713 /*  1380 */    93,   94,   95,  165,  150,   98,  165,  165,  151,   22,
110714 /*  1390 */   165,  194,  150,   26,   27,  150,   86,   87,  159,  165,
110715 /*  1400 */   199,  126,  123,   93,   94,   95,  200,  165,   98,  124,
110716 /*  1410 */   165,  122,  201,  125,  225,  135,  129,  130,  131,  132,
110717 /*  1420 */   133,  134,    5,  157,  157,  202,  118,   10,   11,   12,
110718 /*  1430 */    13,   14,  203,   66,   17,  104,  210,  121,  211,  129,
110719 /*  1440 */   130,  131,  132,  133,  134,  210,  175,  211,   31,  211,
110720 /*  1450 */    33,  210,  104,   86,   87,   47,  175,  183,  175,   42,
110721 /*  1460 */   103,   94,  178,  177,   22,   98,  175,   92,  228,  175,
110722 /*  1470 */   175,  228,   55,  183,   57,  178,  175,  156,   61,   18,
110723 /*  1480 */   157,   64,  156,  235,  157,  156,   45,  157,  236,  157,
110724 /*  1490 */   135,  156,  189,   68,  157,  218,  129,  130,  131,   22,
110725 /*  1500 */   189,  199,  157,  156,  192,   18,  192,  192,  199,  192,
110726 /*  1510 */   218,  189,   40,  157,   38,  157,  240,  157,  240,  153,
110727 /*  1520 */   196,  181,  105,  106,  107,  243,  198,  166,  111,  230,
110728 /*  1530 */   176,  226,  239,  116,  230,  176,  166,  166,  176,  148,
110729 /*  1540 */   199,  177,  209,  209,  166,  196,  239,  208,  185,  199,
110730 /*  1550 */    92,  209,  233,  173,  234,  182,  139,  173,  182,  191,
110731 /*  1560 */   195,  182,  250,  186,
110732};
110733#define YY_SHIFT_USE_DFLT (-70)
110734#define YY_SHIFT_COUNT (416)
110735#define YY_SHIFT_MIN   (-69)
110736#define YY_SHIFT_MAX   (1487)
110737static const short yy_shift_ofst[] = {
110738 /*     0 */  1143, 1188, 1417, 1188, 1287, 1287,  138,  138,   -2,  -19,
110739 /*    10 */  1287, 1287, 1287, 1287,  347,  362,  129,  129,  795, 1165,
110740 /*    20 */  1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
110741 /*    30 */  1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
110742 /*    40 */  1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1310, 1287,
110743 /*    50 */  1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
110744 /*    60 */  1287, 1287,  286,  362,  362,  538,  538,  231, 1253,   55,
110745 /*    70 */   721,  647,  573,  499,  425,  351,  277,  203,  869,  869,
110746 /*    80 */   869,  869,  869,  869,  869,  869,  869,  869,  869,  869,
110747 /*    90 */   869,  869,  869,  943,  869, 1017, 1091, 1091,  -69,  -45,
110748 /*   100 */   -45,  -45,  -45,  -45,   -1,   24,  245,  362,  362,  362,
110749 /*   110 */   362,  362,  362,  362,  362,  362,  362,  362,  362,  362,
110750 /*   120 */   362,  362,  362,  388,  356,  362,  362,  362,  362,  362,
110751 /*   130 */   732,  868,  231, 1051, 1458,  -70,  -70,  -70, 1367,   57,
110752 /*   140 */   434,  434,  289,  291,  285,    1,  204,  572,  539,  362,
110753 /*   150 */   362,  362,  362,  362,  362,  362,  362,  362,  362,  362,
110754 /*   160 */   362,  362,  362,  362,  362,  362,  362,  362,  362,  362,
110755 /*   170 */   362,  362,  362,  362,  362,  362,  362,  362,  362,  362,
110756 /*   180 */   362,  506,  506,  506,  705, 1253, 1253, 1253,  -70,  -70,
110757 /*   190 */   -70,  171,  171,  160,  502,  502,  502,  446,  432,  511,
110758 /*   200 */   422,  358,  335,  -12,  -12,  -12,  -12,  576,  294,  -12,
110759 /*   210 */   -12,  295,  595,  141,  600,  730,  723,  723,  805,  730,
110760 /*   220 */   805,  439,  911,  231,  865,  231,  865,  807,  865,  723,
110761 /*   230 */   766,  633,  633,  231,  284,   63,  608, 1476, 1308, 1308,
110762 /*   240 */  1472, 1472, 1308, 1477, 1425, 1275, 1487, 1487, 1487, 1487,
110763 /*   250 */  1308, 1461, 1275, 1477, 1425, 1425, 1308, 1461, 1355, 1441,
110764 /*   260 */  1308, 1308, 1461, 1308, 1461, 1308, 1461, 1442, 1348, 1348,
110765 /*   270 */  1348, 1408, 1375, 1375, 1442, 1348, 1357, 1348, 1408, 1348,
110766 /*   280 */  1348, 1316, 1331, 1316, 1331, 1316, 1331, 1308, 1308, 1280,
110767 /*   290 */  1288, 1289, 1285, 1279, 1275, 1253, 1336, 1346, 1346, 1338,
110768 /*   300 */  1338, 1338, 1338,  -70,  -70,  -70,  -70,  -70,  -70, 1013,
110769 /*   310 */   467,  612,   84,  179,  -28,  870,  410,  761,  760,  667,
110770 /*   320 */   650,  531,  220,  361,  331,  125,  127,   97, 1306, 1300,
110771 /*   330 */  1270, 1151, 1272, 1203, 1232, 1261, 1244, 1148, 1174, 1139,
110772 /*   340 */  1156, 1124, 1220, 1115, 1210, 1233, 1099, 1193, 1184, 1174,
110773 /*   350 */  1173, 1029, 1121, 1120, 1085, 1162, 1119, 1037, 1152, 1147,
110774 /*   360 */  1129, 1046, 1011, 1093, 1098, 1075, 1061, 1032,  960, 1057,
110775 /*   370 */  1031, 1030,  899,  938,  982,  936,  972,  958,  910,  955,
110776 /*   380 */   875,  885,  908,  857,  859,  867,  804,  590,  834,  747,
110777 /*   390 */   818,  513,  611,  741,  673,  637,  611,  606,  603,  579,
110778 /*   400 */   501,  541,  468,  386,  445,  395,  376,  281,  185,  120,
110779 /*   410 */    92,   75,   45,  114,   25,   11,    5,
110780};
110781#define YY_REDUCE_USE_DFLT (-169)
110782#define YY_REDUCE_COUNT (308)
110783#define YY_REDUCE_MIN   (-168)
110784#define YY_REDUCE_MAX   (1391)
110785static const short yy_reduce_ofst[] = {
110786 /*     0 */  -141,   90, 1095,  222,  158,  156,   19,   17,   10, -104,
110787 /*    10 */   378,  316,  311,   12,  180,  249,  598,  464,  397, 1181,
110788 /*    20 */  1177, 1175, 1128, 1106, 1096, 1054, 1038,  974,  964,  962,
110789 /*    30 */   948,  905,  903,  900,  887,  874,  832,  826,  816,  813,
110790 /*    40 */   800,  758,  755,  752,  742,  739,  726,  685,  681,  668,
110791 /*    50 */   665,  652,  607,  604,  594,  591,  578,  530,  528,  526,
110792 /*    60 */   385,   18,  477,  466,  519,  444,  350,  435,  405,  488,
110793 /*    70 */   488,  488,  488,  488,  488,  488,  488,  488,  488,  488,
110794 /*    80 */   488,  488,  488,  488,  488,  488,  488,  488,  488,  488,
110795 /*    90 */   488,  488,  488,  488,  488,  488,  488,  488,  488,  488,
110796 /*   100 */   488,  488,  488,  488,  488,  488,  488, 1040,  678, 1036,
110797 /*   110 */  1007,  967,  966,  965,  845,  686,  610,  684,  317,  672,
110798 /*   120 */   893,  327,  623,  522,   -7,  820,  814,  157,  154,  101,
110799 /*   130 */   702,  494,  580,  488,  488,  488,  488,  488,  614,  586,
110800 /*   140 */   935,  892,  968, 1245, 1242, 1234, 1225,  798,  798, 1222,
110801 /*   150 */  1221, 1218, 1214, 1213, 1212, 1202, 1195, 1191, 1161, 1158,
110802 /*   160 */  1140, 1135, 1123, 1112, 1107, 1100, 1080, 1074, 1073, 1072,
110803 /*   170 */  1070, 1067, 1048, 1044,  969,  968,  907,  906,  904,  894,
110804 /*   180 */   833,  837,  836,  340,  827,  815,  775,   68,  722,  646,
110805 /*   190 */  -168, 1384, 1380, 1377, 1379, 1376, 1373, 1339, 1365, 1368,
110806 /*   200 */  1365, 1365, 1365, 1365, 1365, 1365, 1365, 1320, 1319, 1365,
110807 /*   210 */  1365, 1339, 1378, 1349, 1391, 1350, 1342, 1334, 1307, 1341,
110808 /*   220 */  1293, 1364, 1363, 1371, 1362, 1370, 1359, 1340, 1354, 1333,
110809 /*   230 */  1305, 1304, 1299, 1361, 1328, 1324, 1366, 1282, 1360, 1358,
110810 /*   240 */  1278, 1276, 1356, 1292, 1322, 1309, 1317, 1315, 1314, 1312,
110811 /*   250 */  1345, 1347, 1302, 1277, 1311, 1303, 1337, 1335, 1252, 1248,
110812 /*   260 */  1332, 1330, 1329, 1327, 1326, 1323, 1321, 1297, 1301, 1295,
110813 /*   270 */  1294, 1290, 1243, 1240, 1284, 1291, 1286, 1283, 1274, 1281,
110814 /*   280 */  1271, 1238, 1241, 1236, 1235, 1227, 1226, 1267, 1266, 1189,
110815 /*   290 */  1229, 1223, 1211, 1206, 1201, 1197, 1239, 1237, 1219, 1216,
110816 /*   300 */  1209, 1208, 1185, 1089, 1086, 1087, 1137, 1136, 1164,
110817};
110818static const YYACTIONTYPE yy_default[] = {
110819 /*     0 */   632,  866,  954,  954,  866,  866,  954,  954,  954,  756,
110820 /*    10 */   954,  954,  954,  864,  954,  954,  784,  784,  928,  954,
110821 /*    20 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
110822 /*    30 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
110823 /*    40 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
110824 /*    50 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
110825 /*    60 */   954,  954,  954,  954,  954,  954,  954,  671,  760,  790,
110826 /*    70 */   954,  954,  954,  954,  954,  954,  954,  954,  927,  929,
110827 /*    80 */   798,  797,  907,  771,  795,  788,  792,  867,  860,  861,
110828 /*    90 */   859,  863,  868,  954,  791,  827,  844,  826,  838,  843,
110829 /*   100 */   850,  842,  839,  829,  828,  830,  831,  954,  954,  954,
110830 /*   110 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
110831 /*   120 */   954,  954,  954,  658,  725,  954,  954,  954,  954,  954,
110832 /*   130 */   954,  954,  954,  832,  833,  847,  846,  845,  954,  663,
110833 /*   140 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
110834 /*   150 */   934,  932,  954,  879,  954,  954,  954,  954,  954,  954,
110835 /*   160 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
110836 /*   170 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
110837 /*   180 */   638,  756,  756,  756,  632,  954,  954,  954,  946,  760,
110838 /*   190 */   750,  954,  954,  954,  954,  954,  954,  954,  954,  954,
110839 /*   200 */   954,  954,  954,  800,  739,  917,  919,  954,  900,  737,
110840 /*   210 */   660,  758,  673,  748,  640,  794,  773,  773,  912,  794,
110841 /*   220 */   912,  696,  719,  954,  784,  954,  784,  693,  784,  773,
110842 /*   230 */   862,  954,  954,  954,  757,  748,  954,  939,  764,  764,
110843 /*   240 */   931,  931,  764,  806,  729,  794,  736,  736,  736,  736,
110844 /*   250 */   764,  655,  794,  806,  729,  729,  764,  655,  906,  904,
110845 /*   260 */   764,  764,  655,  764,  655,  764,  655,  872,  727,  727,
110846 /*   270 */   727,  711,  876,  876,  872,  727,  696,  727,  711,  727,
110847 /*   280 */   727,  777,  772,  777,  772,  777,  772,  764,  764,  954,
110848 /*   290 */   789,  778,  787,  785,  794,  954,  714,  648,  648,  637,
110849 /*   300 */   637,  637,  637,  951,  951,  946,  698,  698,  681,  954,
110850 /*   310 */   954,  954,  954,  954,  954,  954,  881,  954,  954,  954,
110851 /*   320 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  633,
110852 /*   330 */   941,  954,  954,  938,  954,  954,  954,  954,  799,  954,
110853 /*   340 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  916,
110854 /*   350 */   954,  954,  954,  954,  954,  954,  954,  910,  954,  954,
110855 /*   360 */   954,  954,  954,  954,  903,  902,  954,  954,  954,  954,
110856 /*   370 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
110857 /*   380 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
110858 /*   390 */   954,  954,  786,  954,  779,  954,  865,  954,  954,  954,
110859 /*   400 */   954,  954,  954,  954,  954,  954,  954,  742,  815,  954,
110860 /*   410 */   814,  818,  813,  665,  954,  646,  954,  629,  634,  950,
110861 /*   420 */   953,  952,  949,  948,  947,  942,  940,  937,  936,  935,
110862 /*   430 */   933,  930,  926,  885,  883,  890,  889,  888,  887,  886,
110863 /*   440 */   884,  882,  880,  801,  796,  793,  925,  878,  738,  735,
110864 /*   450 */   734,  654,  943,  909,  918,  805,  804,  807,  915,  914,
110865 /*   460 */   913,  911,  908,  895,  803,  802,  730,  870,  869,  657,
110866 /*   470 */   899,  898,  897,  901,  905,  896,  766,  656,  653,  662,
110867 /*   480 */   717,  718,  726,  724,  723,  722,  721,  720,  716,  664,
110868 /*   490 */   672,  710,  695,  694,  875,  877,  874,  873,  703,  702,
110869 /*   500 */   708,  707,  706,  705,  704,  701,  700,  699,  692,  691,
110870 /*   510 */   697,  690,  713,  712,  709,  689,  733,  732,  731,  728,
110871 /*   520 */   688,  687,  686,  818,  685,  684,  824,  823,  811,  854,
110872 /*   530 */   753,  752,  751,  763,  762,  775,  774,  809,  808,  776,
110873 /*   540 */   761,  755,  754,  770,  769,  768,  767,  759,  749,  781,
110874 /*   550 */   783,  782,  780,  856,  765,  853,  924,  923,  922,  921,
110875 /*   560 */   920,  858,  857,  825,  822,  676,  677,  893,  892,  894,
110876 /*   570 */   891,  679,  678,  675,  674,  855,  744,  743,  851,  848,
110877 /*   580 */   840,  836,  852,  849,  841,  837,  835,  834,  820,  819,
110878 /*   590 */   817,  816,  812,  821,  667,  745,  741,  740,  810,  747,
110879 /*   600 */   746,  683,  682,  680,  661,  659,  652,  650,  649,  651,
110880 /*   610 */   647,  645,  644,  643,  642,  641,  670,  669,  668,  666,
110881 /*   620 */   665,  639,  636,  635,  631,  630,  628,
110882};
110883
110884/* The next table maps tokens into fallback tokens.  If a construct
110885** like the following:
110886**
110887**      %fallback ID X Y Z.
110888**
110889** appears in the grammar, then ID becomes a fallback token for X, Y,
110890** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
110891** but it does not parse, the type of the token is changed to ID and
110892** the parse is retried before an error is thrown.
110893*/
110894#ifdef YYFALLBACK
110895static const YYCODETYPE yyFallback[] = {
110896    0,  /*          $ => nothing */
110897    0,  /*       SEMI => nothing */
110898   26,  /*    EXPLAIN => ID */
110899   26,  /*      QUERY => ID */
110900   26,  /*       PLAN => ID */
110901   26,  /*      BEGIN => ID */
110902    0,  /* TRANSACTION => nothing */
110903   26,  /*   DEFERRED => ID */
110904   26,  /*  IMMEDIATE => ID */
110905   26,  /*  EXCLUSIVE => ID */
110906    0,  /*     COMMIT => nothing */
110907   26,  /*        END => ID */
110908   26,  /*   ROLLBACK => ID */
110909   26,  /*  SAVEPOINT => ID */
110910   26,  /*    RELEASE => ID */
110911    0,  /*         TO => nothing */
110912    0,  /*      TABLE => nothing */
110913    0,  /*     CREATE => nothing */
110914   26,  /*         IF => ID */
110915    0,  /*        NOT => nothing */
110916    0,  /*     EXISTS => nothing */
110917   26,  /*       TEMP => ID */
110918    0,  /*         LP => nothing */
110919    0,  /*         RP => nothing */
110920    0,  /*         AS => nothing */
110921    0,  /*      COMMA => nothing */
110922    0,  /*         ID => nothing */
110923    0,  /*    INDEXED => nothing */
110924   26,  /*      ABORT => ID */
110925   26,  /*     ACTION => ID */
110926   26,  /*      AFTER => ID */
110927   26,  /*    ANALYZE => ID */
110928   26,  /*        ASC => ID */
110929   26,  /*     ATTACH => ID */
110930   26,  /*     BEFORE => ID */
110931   26,  /*         BY => ID */
110932   26,  /*    CASCADE => ID */
110933   26,  /*       CAST => ID */
110934   26,  /*   COLUMNKW => ID */
110935   26,  /*   CONFLICT => ID */
110936   26,  /*   DATABASE => ID */
110937   26,  /*       DESC => ID */
110938   26,  /*     DETACH => ID */
110939   26,  /*       EACH => ID */
110940   26,  /*       FAIL => ID */
110941   26,  /*        FOR => ID */
110942   26,  /*     IGNORE => ID */
110943   26,  /*  INITIALLY => ID */
110944   26,  /*    INSTEAD => ID */
110945   26,  /*    LIKE_KW => ID */
110946   26,  /*      MATCH => ID */
110947   26,  /*         NO => ID */
110948   26,  /*        KEY => ID */
110949   26,  /*         OF => ID */
110950   26,  /*     OFFSET => ID */
110951   26,  /*     PRAGMA => ID */
110952   26,  /*      RAISE => ID */
110953   26,  /*    REPLACE => ID */
110954   26,  /*   RESTRICT => ID */
110955   26,  /*        ROW => ID */
110956   26,  /*    TRIGGER => ID */
110957   26,  /*     VACUUM => ID */
110958   26,  /*       VIEW => ID */
110959   26,  /*    VIRTUAL => ID */
110960   26,  /*    REINDEX => ID */
110961   26,  /*     RENAME => ID */
110962   26,  /*   CTIME_KW => ID */
110963};
110964#endif /* YYFALLBACK */
110965
110966/* The following structure represents a single element of the
110967** parser's stack.  Information stored includes:
110968**
110969**   +  The state number for the parser at this level of the stack.
110970**
110971**   +  The value of the token stored at this level of the stack.
110972**      (In other words, the "major" token.)
110973**
110974**   +  The semantic value stored at this level of the stack.  This is
110975**      the information used by the action routines in the grammar.
110976**      It is sometimes called the "minor" token.
110977*/
110978struct yyStackEntry {
110979  YYACTIONTYPE stateno;  /* The state-number */
110980  YYCODETYPE major;      /* The major token value.  This is the code
110981                         ** number for the token at this stack level */
110982  YYMINORTYPE minor;     /* The user-supplied minor token value.  This
110983                         ** is the value of the token  */
110984};
110985typedef struct yyStackEntry yyStackEntry;
110986
110987/* The state of the parser is completely contained in an instance of
110988** the following structure */
110989struct yyParser {
110990  int yyidx;                    /* Index of top element in stack */
110991#ifdef YYTRACKMAXSTACKDEPTH
110992  int yyidxMax;                 /* Maximum value of yyidx */
110993#endif
110994  int yyerrcnt;                 /* Shifts left before out of the error */
110995  sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
110996#if YYSTACKDEPTH<=0
110997  int yystksz;                  /* Current side of the stack */
110998  yyStackEntry *yystack;        /* The parser's stack */
110999#else
111000  yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
111001#endif
111002};
111003typedef struct yyParser yyParser;
111004
111005#ifndef NDEBUG
111006/* #include <stdio.h> */
111007static FILE *yyTraceFILE = 0;
111008static char *yyTracePrompt = 0;
111009#endif /* NDEBUG */
111010
111011#ifndef NDEBUG
111012/*
111013** Turn parser tracing on by giving a stream to which to write the trace
111014** and a prompt to preface each trace message.  Tracing is turned off
111015** by making either argument NULL
111016**
111017** Inputs:
111018** <ul>
111019** <li> A FILE* to which trace output should be written.
111020**      If NULL, then tracing is turned off.
111021** <li> A prefix string written at the beginning of every
111022**      line of trace output.  If NULL, then tracing is
111023**      turned off.
111024** </ul>
111025**
111026** Outputs:
111027** None.
111028*/
111029SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
111030  yyTraceFILE = TraceFILE;
111031  yyTracePrompt = zTracePrompt;
111032  if( yyTraceFILE==0 ) yyTracePrompt = 0;
111033  else if( yyTracePrompt==0 ) yyTraceFILE = 0;
111034}
111035#endif /* NDEBUG */
111036
111037#ifndef NDEBUG
111038/* For tracing shifts, the names of all terminals and nonterminals
111039** are required.  The following table supplies these names */
111040static const char *const yyTokenName[] = {
111041  "$",             "SEMI",          "EXPLAIN",       "QUERY",
111042  "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",
111043  "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",
111044  "ROLLBACK",      "SAVEPOINT",     "RELEASE",       "TO",
111045  "TABLE",         "CREATE",        "IF",            "NOT",
111046  "EXISTS",        "TEMP",          "LP",            "RP",
111047  "AS",            "COMMA",         "ID",            "INDEXED",
111048  "ABORT",         "ACTION",        "AFTER",         "ANALYZE",
111049  "ASC",           "ATTACH",        "BEFORE",        "BY",
111050  "CASCADE",       "CAST",          "COLUMNKW",      "CONFLICT",
111051  "DATABASE",      "DESC",          "DETACH",        "EACH",
111052  "FAIL",          "FOR",           "IGNORE",        "INITIALLY",
111053  "INSTEAD",       "LIKE_KW",       "MATCH",         "NO",
111054  "KEY",           "OF",            "OFFSET",        "PRAGMA",
111055  "RAISE",         "REPLACE",       "RESTRICT",      "ROW",
111056  "TRIGGER",       "VACUUM",        "VIEW",          "VIRTUAL",
111057  "REINDEX",       "RENAME",        "CTIME_KW",      "ANY",
111058  "OR",            "AND",           "IS",            "BETWEEN",
111059  "IN",            "ISNULL",        "NOTNULL",       "NE",
111060  "EQ",            "GT",            "LE",            "LT",
111061  "GE",            "ESCAPE",        "BITAND",        "BITOR",
111062  "LSHIFT",        "RSHIFT",        "PLUS",          "MINUS",
111063  "STAR",          "SLASH",         "REM",           "CONCAT",
111064  "COLLATE",       "BITNOT",        "STRING",        "JOIN_KW",
111065  "CONSTRAINT",    "DEFAULT",       "NULL",          "PRIMARY",
111066  "UNIQUE",        "CHECK",         "REFERENCES",    "AUTOINCR",
111067  "ON",            "INSERT",        "DELETE",        "UPDATE",
111068  "SET",           "DEFERRABLE",    "FOREIGN",       "DROP",
111069  "UNION",         "ALL",           "EXCEPT",        "INTERSECT",
111070  "SELECT",        "DISTINCT",      "DOT",           "FROM",
111071  "JOIN",          "USING",         "ORDER",         "GROUP",
111072  "HAVING",        "LIMIT",         "WHERE",         "INTO",
111073  "VALUES",        "INTEGER",       "FLOAT",         "BLOB",
111074  "REGISTER",      "VARIABLE",      "CASE",          "WHEN",
111075  "THEN",          "ELSE",          "INDEX",         "ALTER",
111076  "ADD",           "error",         "input",         "cmdlist",
111077  "ecmd",          "explain",       "cmdx",          "cmd",
111078  "transtype",     "trans_opt",     "nm",            "savepoint_opt",
111079  "create_table",  "create_table_args",  "createkw",      "temp",
111080  "ifnotexists",   "dbnm",          "columnlist",    "conslist_opt",
111081  "select",        "column",        "columnid",      "type",
111082  "carglist",      "id",            "ids",           "typetoken",
111083  "typename",      "signed",        "plus_num",      "minus_num",
111084  "ccons",         "term",          "expr",          "onconf",
111085  "sortorder",     "autoinc",       "idxlist_opt",   "refargs",
111086  "defer_subclause",  "refarg",        "refact",        "init_deferred_pred_opt",
111087  "conslist",      "tconscomma",    "tcons",         "idxlist",
111088  "defer_subclause_opt",  "orconf",        "resolvetype",   "raisetype",
111089  "ifexists",      "fullname",      "oneselect",     "multiselect_op",
111090  "distinct",      "selcollist",    "from",          "where_opt",
111091  "groupby_opt",   "having_opt",    "orderby_opt",   "limit_opt",
111092  "sclp",          "as",            "seltablist",    "stl_prefix",
111093  "joinop",        "indexed_opt",   "on_opt",        "using_opt",
111094  "joinop2",       "inscollist",    "sortlist",      "nexprlist",
111095  "setlist",       "insert_cmd",    "inscollist_opt",  "valuelist",
111096  "exprlist",      "likeop",        "between_op",    "in_op",
111097  "case_operand",  "case_exprlist",  "case_else",     "uniqueflag",
111098  "collate",       "nmnum",         "number",        "trigger_decl",
111099  "trigger_cmd_list",  "trigger_time",  "trigger_event",  "foreach_clause",
111100  "when_clause",   "trigger_cmd",   "trnm",          "tridxby",
111101  "database_kw_opt",  "key_opt",       "add_column_fullname",  "kwcolumn_opt",
111102  "create_vtab",   "vtabarglist",   "vtabarg",       "vtabargtoken",
111103  "lp",            "anylist",
111104};
111105#endif /* NDEBUG */
111106
111107#ifndef NDEBUG
111108/* For tracing reduce actions, the names of all rules are required.
111109*/
111110static const char *const yyRuleName[] = {
111111 /*   0 */ "input ::= cmdlist",
111112 /*   1 */ "cmdlist ::= cmdlist ecmd",
111113 /*   2 */ "cmdlist ::= ecmd",
111114 /*   3 */ "ecmd ::= SEMI",
111115 /*   4 */ "ecmd ::= explain cmdx SEMI",
111116 /*   5 */ "explain ::=",
111117 /*   6 */ "explain ::= EXPLAIN",
111118 /*   7 */ "explain ::= EXPLAIN QUERY PLAN",
111119 /*   8 */ "cmdx ::= cmd",
111120 /*   9 */ "cmd ::= BEGIN transtype trans_opt",
111121 /*  10 */ "trans_opt ::=",
111122 /*  11 */ "trans_opt ::= TRANSACTION",
111123 /*  12 */ "trans_opt ::= TRANSACTION nm",
111124 /*  13 */ "transtype ::=",
111125 /*  14 */ "transtype ::= DEFERRED",
111126 /*  15 */ "transtype ::= IMMEDIATE",
111127 /*  16 */ "transtype ::= EXCLUSIVE",
111128 /*  17 */ "cmd ::= COMMIT trans_opt",
111129 /*  18 */ "cmd ::= END trans_opt",
111130 /*  19 */ "cmd ::= ROLLBACK trans_opt",
111131 /*  20 */ "savepoint_opt ::= SAVEPOINT",
111132 /*  21 */ "savepoint_opt ::=",
111133 /*  22 */ "cmd ::= SAVEPOINT nm",
111134 /*  23 */ "cmd ::= RELEASE savepoint_opt nm",
111135 /*  24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
111136 /*  25 */ "cmd ::= create_table create_table_args",
111137 /*  26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
111138 /*  27 */ "createkw ::= CREATE",
111139 /*  28 */ "ifnotexists ::=",
111140 /*  29 */ "ifnotexists ::= IF NOT EXISTS",
111141 /*  30 */ "temp ::= TEMP",
111142 /*  31 */ "temp ::=",
111143 /*  32 */ "create_table_args ::= LP columnlist conslist_opt RP",
111144 /*  33 */ "create_table_args ::= AS select",
111145 /*  34 */ "columnlist ::= columnlist COMMA column",
111146 /*  35 */ "columnlist ::= column",
111147 /*  36 */ "column ::= columnid type carglist",
111148 /*  37 */ "columnid ::= nm",
111149 /*  38 */ "id ::= ID",
111150 /*  39 */ "id ::= INDEXED",
111151 /*  40 */ "ids ::= ID|STRING",
111152 /*  41 */ "nm ::= id",
111153 /*  42 */ "nm ::= STRING",
111154 /*  43 */ "nm ::= JOIN_KW",
111155 /*  44 */ "type ::=",
111156 /*  45 */ "type ::= typetoken",
111157 /*  46 */ "typetoken ::= typename",
111158 /*  47 */ "typetoken ::= typename LP signed RP",
111159 /*  48 */ "typetoken ::= typename LP signed COMMA signed RP",
111160 /*  49 */ "typename ::= ids",
111161 /*  50 */ "typename ::= typename ids",
111162 /*  51 */ "signed ::= plus_num",
111163 /*  52 */ "signed ::= minus_num",
111164 /*  53 */ "carglist ::= carglist ccons",
111165 /*  54 */ "carglist ::=",
111166 /*  55 */ "ccons ::= CONSTRAINT nm",
111167 /*  56 */ "ccons ::= DEFAULT term",
111168 /*  57 */ "ccons ::= DEFAULT LP expr RP",
111169 /*  58 */ "ccons ::= DEFAULT PLUS term",
111170 /*  59 */ "ccons ::= DEFAULT MINUS term",
111171 /*  60 */ "ccons ::= DEFAULT id",
111172 /*  61 */ "ccons ::= NULL onconf",
111173 /*  62 */ "ccons ::= NOT NULL onconf",
111174 /*  63 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
111175 /*  64 */ "ccons ::= UNIQUE onconf",
111176 /*  65 */ "ccons ::= CHECK LP expr RP",
111177 /*  66 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
111178 /*  67 */ "ccons ::= defer_subclause",
111179 /*  68 */ "ccons ::= COLLATE ids",
111180 /*  69 */ "autoinc ::=",
111181 /*  70 */ "autoinc ::= AUTOINCR",
111182 /*  71 */ "refargs ::=",
111183 /*  72 */ "refargs ::= refargs refarg",
111184 /*  73 */ "refarg ::= MATCH nm",
111185 /*  74 */ "refarg ::= ON INSERT refact",
111186 /*  75 */ "refarg ::= ON DELETE refact",
111187 /*  76 */ "refarg ::= ON UPDATE refact",
111188 /*  77 */ "refact ::= SET NULL",
111189 /*  78 */ "refact ::= SET DEFAULT",
111190 /*  79 */ "refact ::= CASCADE",
111191 /*  80 */ "refact ::= RESTRICT",
111192 /*  81 */ "refact ::= NO ACTION",
111193 /*  82 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
111194 /*  83 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
111195 /*  84 */ "init_deferred_pred_opt ::=",
111196 /*  85 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
111197 /*  86 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
111198 /*  87 */ "conslist_opt ::=",
111199 /*  88 */ "conslist_opt ::= COMMA conslist",
111200 /*  89 */ "conslist ::= conslist tconscomma tcons",
111201 /*  90 */ "conslist ::= tcons",
111202 /*  91 */ "tconscomma ::= COMMA",
111203 /*  92 */ "tconscomma ::=",
111204 /*  93 */ "tcons ::= CONSTRAINT nm",
111205 /*  94 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
111206 /*  95 */ "tcons ::= UNIQUE LP idxlist RP onconf",
111207 /*  96 */ "tcons ::= CHECK LP expr RP onconf",
111208 /*  97 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
111209 /*  98 */ "defer_subclause_opt ::=",
111210 /*  99 */ "defer_subclause_opt ::= defer_subclause",
111211 /* 100 */ "onconf ::=",
111212 /* 101 */ "onconf ::= ON CONFLICT resolvetype",
111213 /* 102 */ "orconf ::=",
111214 /* 103 */ "orconf ::= OR resolvetype",
111215 /* 104 */ "resolvetype ::= raisetype",
111216 /* 105 */ "resolvetype ::= IGNORE",
111217 /* 106 */ "resolvetype ::= REPLACE",
111218 /* 107 */ "cmd ::= DROP TABLE ifexists fullname",
111219 /* 108 */ "ifexists ::= IF EXISTS",
111220 /* 109 */ "ifexists ::=",
111221 /* 110 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
111222 /* 111 */ "cmd ::= DROP VIEW ifexists fullname",
111223 /* 112 */ "cmd ::= select",
111224 /* 113 */ "select ::= oneselect",
111225 /* 114 */ "select ::= select multiselect_op oneselect",
111226 /* 115 */ "multiselect_op ::= UNION",
111227 /* 116 */ "multiselect_op ::= UNION ALL",
111228 /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
111229 /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
111230 /* 119 */ "distinct ::= DISTINCT",
111231 /* 120 */ "distinct ::= ALL",
111232 /* 121 */ "distinct ::=",
111233 /* 122 */ "sclp ::= selcollist COMMA",
111234 /* 123 */ "sclp ::=",
111235 /* 124 */ "selcollist ::= sclp expr as",
111236 /* 125 */ "selcollist ::= sclp STAR",
111237 /* 126 */ "selcollist ::= sclp nm DOT STAR",
111238 /* 127 */ "as ::= AS nm",
111239 /* 128 */ "as ::= ids",
111240 /* 129 */ "as ::=",
111241 /* 130 */ "from ::=",
111242 /* 131 */ "from ::= FROM seltablist",
111243 /* 132 */ "stl_prefix ::= seltablist joinop",
111244 /* 133 */ "stl_prefix ::=",
111245 /* 134 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
111246 /* 135 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
111247 /* 136 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
111248 /* 137 */ "dbnm ::=",
111249 /* 138 */ "dbnm ::= DOT nm",
111250 /* 139 */ "fullname ::= nm dbnm",
111251 /* 140 */ "joinop ::= COMMA|JOIN",
111252 /* 141 */ "joinop ::= JOIN_KW JOIN",
111253 /* 142 */ "joinop ::= JOIN_KW nm JOIN",
111254 /* 143 */ "joinop ::= JOIN_KW nm nm JOIN",
111255 /* 144 */ "on_opt ::= ON expr",
111256 /* 145 */ "on_opt ::=",
111257 /* 146 */ "indexed_opt ::=",
111258 /* 147 */ "indexed_opt ::= INDEXED BY nm",
111259 /* 148 */ "indexed_opt ::= NOT INDEXED",
111260 /* 149 */ "using_opt ::= USING LP inscollist RP",
111261 /* 150 */ "using_opt ::=",
111262 /* 151 */ "orderby_opt ::=",
111263 /* 152 */ "orderby_opt ::= ORDER BY sortlist",
111264 /* 153 */ "sortlist ::= sortlist COMMA expr sortorder",
111265 /* 154 */ "sortlist ::= expr sortorder",
111266 /* 155 */ "sortorder ::= ASC",
111267 /* 156 */ "sortorder ::= DESC",
111268 /* 157 */ "sortorder ::=",
111269 /* 158 */ "groupby_opt ::=",
111270 /* 159 */ "groupby_opt ::= GROUP BY nexprlist",
111271 /* 160 */ "having_opt ::=",
111272 /* 161 */ "having_opt ::= HAVING expr",
111273 /* 162 */ "limit_opt ::=",
111274 /* 163 */ "limit_opt ::= LIMIT expr",
111275 /* 164 */ "limit_opt ::= LIMIT expr OFFSET expr",
111276 /* 165 */ "limit_opt ::= LIMIT expr COMMA expr",
111277 /* 166 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt",
111278 /* 167 */ "where_opt ::=",
111279 /* 168 */ "where_opt ::= WHERE expr",
111280 /* 169 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt",
111281 /* 170 */ "setlist ::= setlist COMMA nm EQ expr",
111282 /* 171 */ "setlist ::= nm EQ expr",
111283 /* 172 */ "cmd ::= insert_cmd INTO fullname inscollist_opt valuelist",
111284 /* 173 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
111285 /* 174 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
111286 /* 175 */ "insert_cmd ::= INSERT orconf",
111287 /* 176 */ "insert_cmd ::= REPLACE",
111288 /* 177 */ "valuelist ::= VALUES LP nexprlist RP",
111289 /* 178 */ "valuelist ::= valuelist COMMA LP exprlist RP",
111290 /* 179 */ "inscollist_opt ::=",
111291 /* 180 */ "inscollist_opt ::= LP inscollist RP",
111292 /* 181 */ "inscollist ::= inscollist COMMA nm",
111293 /* 182 */ "inscollist ::= nm",
111294 /* 183 */ "expr ::= term",
111295 /* 184 */ "expr ::= LP expr RP",
111296 /* 185 */ "term ::= NULL",
111297 /* 186 */ "expr ::= id",
111298 /* 187 */ "expr ::= JOIN_KW",
111299 /* 188 */ "expr ::= nm DOT nm",
111300 /* 189 */ "expr ::= nm DOT nm DOT nm",
111301 /* 190 */ "term ::= INTEGER|FLOAT|BLOB",
111302 /* 191 */ "term ::= STRING",
111303 /* 192 */ "expr ::= REGISTER",
111304 /* 193 */ "expr ::= VARIABLE",
111305 /* 194 */ "expr ::= expr COLLATE ids",
111306 /* 195 */ "expr ::= CAST LP expr AS typetoken RP",
111307 /* 196 */ "expr ::= ID LP distinct exprlist RP",
111308 /* 197 */ "expr ::= ID LP STAR RP",
111309 /* 198 */ "term ::= CTIME_KW",
111310 /* 199 */ "expr ::= expr AND expr",
111311 /* 200 */ "expr ::= expr OR expr",
111312 /* 201 */ "expr ::= expr LT|GT|GE|LE expr",
111313 /* 202 */ "expr ::= expr EQ|NE expr",
111314 /* 203 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
111315 /* 204 */ "expr ::= expr PLUS|MINUS expr",
111316 /* 205 */ "expr ::= expr STAR|SLASH|REM expr",
111317 /* 206 */ "expr ::= expr CONCAT expr",
111318 /* 207 */ "likeop ::= LIKE_KW",
111319 /* 208 */ "likeop ::= NOT LIKE_KW",
111320 /* 209 */ "likeop ::= MATCH",
111321 /* 210 */ "likeop ::= NOT MATCH",
111322 /* 211 */ "expr ::= expr likeop expr",
111323 /* 212 */ "expr ::= expr likeop expr ESCAPE expr",
111324 /* 213 */ "expr ::= expr ISNULL|NOTNULL",
111325 /* 214 */ "expr ::= expr NOT NULL",
111326 /* 215 */ "expr ::= expr IS expr",
111327 /* 216 */ "expr ::= expr IS NOT expr",
111328 /* 217 */ "expr ::= NOT expr",
111329 /* 218 */ "expr ::= BITNOT expr",
111330 /* 219 */ "expr ::= MINUS expr",
111331 /* 220 */ "expr ::= PLUS expr",
111332 /* 221 */ "between_op ::= BETWEEN",
111333 /* 222 */ "between_op ::= NOT BETWEEN",
111334 /* 223 */ "expr ::= expr between_op expr AND expr",
111335 /* 224 */ "in_op ::= IN",
111336 /* 225 */ "in_op ::= NOT IN",
111337 /* 226 */ "expr ::= expr in_op LP exprlist RP",
111338 /* 227 */ "expr ::= LP select RP",
111339 /* 228 */ "expr ::= expr in_op LP select RP",
111340 /* 229 */ "expr ::= expr in_op nm dbnm",
111341 /* 230 */ "expr ::= EXISTS LP select RP",
111342 /* 231 */ "expr ::= CASE case_operand case_exprlist case_else END",
111343 /* 232 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
111344 /* 233 */ "case_exprlist ::= WHEN expr THEN expr",
111345 /* 234 */ "case_else ::= ELSE expr",
111346 /* 235 */ "case_else ::=",
111347 /* 236 */ "case_operand ::= expr",
111348 /* 237 */ "case_operand ::=",
111349 /* 238 */ "exprlist ::= nexprlist",
111350 /* 239 */ "exprlist ::=",
111351 /* 240 */ "nexprlist ::= nexprlist COMMA expr",
111352 /* 241 */ "nexprlist ::= expr",
111353 /* 242 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
111354 /* 243 */ "uniqueflag ::= UNIQUE",
111355 /* 244 */ "uniqueflag ::=",
111356 /* 245 */ "idxlist_opt ::=",
111357 /* 246 */ "idxlist_opt ::= LP idxlist RP",
111358 /* 247 */ "idxlist ::= idxlist COMMA nm collate sortorder",
111359 /* 248 */ "idxlist ::= nm collate sortorder",
111360 /* 249 */ "collate ::=",
111361 /* 250 */ "collate ::= COLLATE ids",
111362 /* 251 */ "cmd ::= DROP INDEX ifexists fullname",
111363 /* 252 */ "cmd ::= VACUUM",
111364 /* 253 */ "cmd ::= VACUUM nm",
111365 /* 254 */ "cmd ::= PRAGMA nm dbnm",
111366 /* 255 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
111367 /* 256 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
111368 /* 257 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
111369 /* 258 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
111370 /* 259 */ "nmnum ::= plus_num",
111371 /* 260 */ "nmnum ::= nm",
111372 /* 261 */ "nmnum ::= ON",
111373 /* 262 */ "nmnum ::= DELETE",
111374 /* 263 */ "nmnum ::= DEFAULT",
111375 /* 264 */ "plus_num ::= PLUS number",
111376 /* 265 */ "plus_num ::= number",
111377 /* 266 */ "minus_num ::= MINUS number",
111378 /* 267 */ "number ::= INTEGER|FLOAT",
111379 /* 268 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
111380 /* 269 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
111381 /* 270 */ "trigger_time ::= BEFORE",
111382 /* 271 */ "trigger_time ::= AFTER",
111383 /* 272 */ "trigger_time ::= INSTEAD OF",
111384 /* 273 */ "trigger_time ::=",
111385 /* 274 */ "trigger_event ::= DELETE|INSERT",
111386 /* 275 */ "trigger_event ::= UPDATE",
111387 /* 276 */ "trigger_event ::= UPDATE OF inscollist",
111388 /* 277 */ "foreach_clause ::=",
111389 /* 278 */ "foreach_clause ::= FOR EACH ROW",
111390 /* 279 */ "when_clause ::=",
111391 /* 280 */ "when_clause ::= WHEN expr",
111392 /* 281 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
111393 /* 282 */ "trigger_cmd_list ::= trigger_cmd SEMI",
111394 /* 283 */ "trnm ::= nm",
111395 /* 284 */ "trnm ::= nm DOT nm",
111396 /* 285 */ "tridxby ::=",
111397 /* 286 */ "tridxby ::= INDEXED BY nm",
111398 /* 287 */ "tridxby ::= NOT INDEXED",
111399 /* 288 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
111400 /* 289 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt valuelist",
111401 /* 290 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
111402 /* 291 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
111403 /* 292 */ "trigger_cmd ::= select",
111404 /* 293 */ "expr ::= RAISE LP IGNORE RP",
111405 /* 294 */ "expr ::= RAISE LP raisetype COMMA nm RP",
111406 /* 295 */ "raisetype ::= ROLLBACK",
111407 /* 296 */ "raisetype ::= ABORT",
111408 /* 297 */ "raisetype ::= FAIL",
111409 /* 298 */ "cmd ::= DROP TRIGGER ifexists fullname",
111410 /* 299 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
111411 /* 300 */ "cmd ::= DETACH database_kw_opt expr",
111412 /* 301 */ "key_opt ::=",
111413 /* 302 */ "key_opt ::= KEY expr",
111414 /* 303 */ "database_kw_opt ::= DATABASE",
111415 /* 304 */ "database_kw_opt ::=",
111416 /* 305 */ "cmd ::= REINDEX",
111417 /* 306 */ "cmd ::= REINDEX nm dbnm",
111418 /* 307 */ "cmd ::= ANALYZE",
111419 /* 308 */ "cmd ::= ANALYZE nm dbnm",
111420 /* 309 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
111421 /* 310 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
111422 /* 311 */ "add_column_fullname ::= fullname",
111423 /* 312 */ "kwcolumn_opt ::=",
111424 /* 313 */ "kwcolumn_opt ::= COLUMNKW",
111425 /* 314 */ "cmd ::= create_vtab",
111426 /* 315 */ "cmd ::= create_vtab LP vtabarglist RP",
111427 /* 316 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
111428 /* 317 */ "vtabarglist ::= vtabarg",
111429 /* 318 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
111430 /* 319 */ "vtabarg ::=",
111431 /* 320 */ "vtabarg ::= vtabarg vtabargtoken",
111432 /* 321 */ "vtabargtoken ::= ANY",
111433 /* 322 */ "vtabargtoken ::= lp anylist RP",
111434 /* 323 */ "lp ::= LP",
111435 /* 324 */ "anylist ::=",
111436 /* 325 */ "anylist ::= anylist LP anylist RP",
111437 /* 326 */ "anylist ::= anylist ANY",
111438};
111439#endif /* NDEBUG */
111440
111441
111442#if YYSTACKDEPTH<=0
111443/*
111444** Try to increase the size of the parser stack.
111445*/
111446static void yyGrowStack(yyParser *p){
111447  int newSize;
111448  yyStackEntry *pNew;
111449
111450  newSize = p->yystksz*2 + 100;
111451  pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
111452  if( pNew ){
111453    p->yystack = pNew;
111454    p->yystksz = newSize;
111455#ifndef NDEBUG
111456    if( yyTraceFILE ){
111457      fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
111458              yyTracePrompt, p->yystksz);
111459    }
111460#endif
111461  }
111462}
111463#endif
111464
111465/*
111466** This function allocates a new parser.
111467** The only argument is a pointer to a function which works like
111468** malloc.
111469**
111470** Inputs:
111471** A pointer to the function used to allocate memory.
111472**
111473** Outputs:
111474** A pointer to a parser.  This pointer is used in subsequent calls
111475** to sqlite3Parser and sqlite3ParserFree.
111476*/
111477SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
111478  yyParser *pParser;
111479  pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
111480  if( pParser ){
111481    pParser->yyidx = -1;
111482#ifdef YYTRACKMAXSTACKDEPTH
111483    pParser->yyidxMax = 0;
111484#endif
111485#if YYSTACKDEPTH<=0
111486    pParser->yystack = NULL;
111487    pParser->yystksz = 0;
111488    yyGrowStack(pParser);
111489#endif
111490  }
111491  return pParser;
111492}
111493
111494/* The following function deletes the value associated with a
111495** symbol.  The symbol can be either a terminal or nonterminal.
111496** "yymajor" is the symbol code, and "yypminor" is a pointer to
111497** the value.
111498*/
111499static void yy_destructor(
111500  yyParser *yypParser,    /* The parser */
111501  YYCODETYPE yymajor,     /* Type code for object to destroy */
111502  YYMINORTYPE *yypminor   /* The object to be destroyed */
111503){
111504  sqlite3ParserARG_FETCH;
111505  switch( yymajor ){
111506    /* Here is inserted the actions which take place when a
111507    ** terminal or non-terminal is destroyed.  This can happen
111508    ** when the symbol is popped from the stack during a
111509    ** reduce or during error processing or when a parser is
111510    ** being destroyed before it is finished parsing.
111511    **
111512    ** Note: during a reduce, the only symbols destroyed are those
111513    ** which appear on the RHS of the rule, but which are not used
111514    ** inside the C code.
111515    */
111516    case 160: /* select */
111517    case 194: /* oneselect */
111518{
111519sqlite3SelectDelete(pParse->db, (yypminor->yy159));
111520}
111521      break;
111522    case 173: /* term */
111523    case 174: /* expr */
111524{
111525sqlite3ExprDelete(pParse->db, (yypminor->yy342).pExpr);
111526}
111527      break;
111528    case 178: /* idxlist_opt */
111529    case 187: /* idxlist */
111530    case 197: /* selcollist */
111531    case 200: /* groupby_opt */
111532    case 202: /* orderby_opt */
111533    case 204: /* sclp */
111534    case 214: /* sortlist */
111535    case 215: /* nexprlist */
111536    case 216: /* setlist */
111537    case 220: /* exprlist */
111538    case 225: /* case_exprlist */
111539{
111540sqlite3ExprListDelete(pParse->db, (yypminor->yy442));
111541}
111542      break;
111543    case 193: /* fullname */
111544    case 198: /* from */
111545    case 206: /* seltablist */
111546    case 207: /* stl_prefix */
111547{
111548sqlite3SrcListDelete(pParse->db, (yypminor->yy347));
111549}
111550      break;
111551    case 199: /* where_opt */
111552    case 201: /* having_opt */
111553    case 210: /* on_opt */
111554    case 224: /* case_operand */
111555    case 226: /* case_else */
111556    case 236: /* when_clause */
111557    case 241: /* key_opt */
111558{
111559sqlite3ExprDelete(pParse->db, (yypminor->yy122));
111560}
111561      break;
111562    case 211: /* using_opt */
111563    case 213: /* inscollist */
111564    case 218: /* inscollist_opt */
111565{
111566sqlite3IdListDelete(pParse->db, (yypminor->yy180));
111567}
111568      break;
111569    case 219: /* valuelist */
111570{
111571
111572  sqlite3ExprListDelete(pParse->db, (yypminor->yy487).pList);
111573  sqlite3SelectDelete(pParse->db, (yypminor->yy487).pSelect);
111574
111575}
111576      break;
111577    case 232: /* trigger_cmd_list */
111578    case 237: /* trigger_cmd */
111579{
111580sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy327));
111581}
111582      break;
111583    case 234: /* trigger_event */
111584{
111585sqlite3IdListDelete(pParse->db, (yypminor->yy410).b);
111586}
111587      break;
111588    default:  break;   /* If no destructor action specified: do nothing */
111589  }
111590}
111591
111592/*
111593** Pop the parser's stack once.
111594**
111595** If there is a destructor routine associated with the token which
111596** is popped from the stack, then call it.
111597**
111598** Return the major token number for the symbol popped.
111599*/
111600static int yy_pop_parser_stack(yyParser *pParser){
111601  YYCODETYPE yymajor;
111602  yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
111603
111604  /* There is no mechanism by which the parser stack can be popped below
111605  ** empty in SQLite.  */
111606  if( NEVER(pParser->yyidx<0) ) return 0;
111607#ifndef NDEBUG
111608  if( yyTraceFILE && pParser->yyidx>=0 ){
111609    fprintf(yyTraceFILE,"%sPopping %s\n",
111610      yyTracePrompt,
111611      yyTokenName[yytos->major]);
111612  }
111613#endif
111614  yymajor = yytos->major;
111615  yy_destructor(pParser, yymajor, &yytos->minor);
111616  pParser->yyidx--;
111617  return yymajor;
111618}
111619
111620/*
111621** Deallocate and destroy a parser.  Destructors are all called for
111622** all stack elements before shutting the parser down.
111623**
111624** Inputs:
111625** <ul>
111626** <li>  A pointer to the parser.  This should be a pointer
111627**       obtained from sqlite3ParserAlloc.
111628** <li>  A pointer to a function used to reclaim memory obtained
111629**       from malloc.
111630** </ul>
111631*/
111632SQLITE_PRIVATE void sqlite3ParserFree(
111633  void *p,                    /* The parser to be deleted */
111634  void (*freeProc)(void*)     /* Function used to reclaim memory */
111635){
111636  yyParser *pParser = (yyParser*)p;
111637  /* In SQLite, we never try to destroy a parser that was not successfully
111638  ** created in the first place. */
111639  if( NEVER(pParser==0) ) return;
111640  while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
111641#if YYSTACKDEPTH<=0
111642  free(pParser->yystack);
111643#endif
111644  (*freeProc)((void*)pParser);
111645}
111646
111647/*
111648** Return the peak depth of the stack for a parser.
111649*/
111650#ifdef YYTRACKMAXSTACKDEPTH
111651SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
111652  yyParser *pParser = (yyParser*)p;
111653  return pParser->yyidxMax;
111654}
111655#endif
111656
111657/*
111658** Find the appropriate action for a parser given the terminal
111659** look-ahead token iLookAhead.
111660**
111661** If the look-ahead token is YYNOCODE, then check to see if the action is
111662** independent of the look-ahead.  If it is, return the action, otherwise
111663** return YY_NO_ACTION.
111664*/
111665static int yy_find_shift_action(
111666  yyParser *pParser,        /* The parser */
111667  YYCODETYPE iLookAhead     /* The look-ahead token */
111668){
111669  int i;
111670  int stateno = pParser->yystack[pParser->yyidx].stateno;
111671
111672  if( stateno>YY_SHIFT_COUNT
111673   || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
111674    return yy_default[stateno];
111675  }
111676  assert( iLookAhead!=YYNOCODE );
111677  i += iLookAhead;
111678  if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
111679    if( iLookAhead>0 ){
111680#ifdef YYFALLBACK
111681      YYCODETYPE iFallback;            /* Fallback token */
111682      if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
111683             && (iFallback = yyFallback[iLookAhead])!=0 ){
111684#ifndef NDEBUG
111685        if( yyTraceFILE ){
111686          fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
111687             yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
111688        }
111689#endif
111690        return yy_find_shift_action(pParser, iFallback);
111691      }
111692#endif
111693#ifdef YYWILDCARD
111694      {
111695        int j = i - iLookAhead + YYWILDCARD;
111696        if(
111697#if YY_SHIFT_MIN+YYWILDCARD<0
111698          j>=0 &&
111699#endif
111700#if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
111701          j<YY_ACTTAB_COUNT &&
111702#endif
111703          yy_lookahead[j]==YYWILDCARD
111704        ){
111705#ifndef NDEBUG
111706          if( yyTraceFILE ){
111707            fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
111708               yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
111709          }
111710#endif /* NDEBUG */
111711          return yy_action[j];
111712        }
111713      }
111714#endif /* YYWILDCARD */
111715    }
111716    return yy_default[stateno];
111717  }else{
111718    return yy_action[i];
111719  }
111720}
111721
111722/*
111723** Find the appropriate action for a parser given the non-terminal
111724** look-ahead token iLookAhead.
111725**
111726** If the look-ahead token is YYNOCODE, then check to see if the action is
111727** independent of the look-ahead.  If it is, return the action, otherwise
111728** return YY_NO_ACTION.
111729*/
111730static int yy_find_reduce_action(
111731  int stateno,              /* Current state number */
111732  YYCODETYPE iLookAhead     /* The look-ahead token */
111733){
111734  int i;
111735#ifdef YYERRORSYMBOL
111736  if( stateno>YY_REDUCE_COUNT ){
111737    return yy_default[stateno];
111738  }
111739#else
111740  assert( stateno<=YY_REDUCE_COUNT );
111741#endif
111742  i = yy_reduce_ofst[stateno];
111743  assert( i!=YY_REDUCE_USE_DFLT );
111744  assert( iLookAhead!=YYNOCODE );
111745  i += iLookAhead;
111746#ifdef YYERRORSYMBOL
111747  if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
111748    return yy_default[stateno];
111749  }
111750#else
111751  assert( i>=0 && i<YY_ACTTAB_COUNT );
111752  assert( yy_lookahead[i]==iLookAhead );
111753#endif
111754  return yy_action[i];
111755}
111756
111757/*
111758** The following routine is called if the stack overflows.
111759*/
111760static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
111761   sqlite3ParserARG_FETCH;
111762   yypParser->yyidx--;
111763#ifndef NDEBUG
111764   if( yyTraceFILE ){
111765     fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
111766   }
111767#endif
111768   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
111769   /* Here code is inserted which will execute if the parser
111770   ** stack every overflows */
111771
111772  UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
111773  sqlite3ErrorMsg(pParse, "parser stack overflow");
111774   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
111775}
111776
111777/*
111778** Perform a shift action.
111779*/
111780static void yy_shift(
111781  yyParser *yypParser,          /* The parser to be shifted */
111782  int yyNewState,               /* The new state to shift in */
111783  int yyMajor,                  /* The major token to shift in */
111784  YYMINORTYPE *yypMinor         /* Pointer to the minor token to shift in */
111785){
111786  yyStackEntry *yytos;
111787  yypParser->yyidx++;
111788#ifdef YYTRACKMAXSTACKDEPTH
111789  if( yypParser->yyidx>yypParser->yyidxMax ){
111790    yypParser->yyidxMax = yypParser->yyidx;
111791  }
111792#endif
111793#if YYSTACKDEPTH>0
111794  if( yypParser->yyidx>=YYSTACKDEPTH ){
111795    yyStackOverflow(yypParser, yypMinor);
111796    return;
111797  }
111798#else
111799  if( yypParser->yyidx>=yypParser->yystksz ){
111800    yyGrowStack(yypParser);
111801    if( yypParser->yyidx>=yypParser->yystksz ){
111802      yyStackOverflow(yypParser, yypMinor);
111803      return;
111804    }
111805  }
111806#endif
111807  yytos = &yypParser->yystack[yypParser->yyidx];
111808  yytos->stateno = (YYACTIONTYPE)yyNewState;
111809  yytos->major = (YYCODETYPE)yyMajor;
111810  yytos->minor = *yypMinor;
111811#ifndef NDEBUG
111812  if( yyTraceFILE && yypParser->yyidx>0 ){
111813    int i;
111814    fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
111815    fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
111816    for(i=1; i<=yypParser->yyidx; i++)
111817      fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
111818    fprintf(yyTraceFILE,"\n");
111819  }
111820#endif
111821}
111822
111823/* The following table contains information about every rule that
111824** is used during the reduce.
111825*/
111826static const struct {
111827  YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
111828  unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
111829} yyRuleInfo[] = {
111830  { 142, 1 },
111831  { 143, 2 },
111832  { 143, 1 },
111833  { 144, 1 },
111834  { 144, 3 },
111835  { 145, 0 },
111836  { 145, 1 },
111837  { 145, 3 },
111838  { 146, 1 },
111839  { 147, 3 },
111840  { 149, 0 },
111841  { 149, 1 },
111842  { 149, 2 },
111843  { 148, 0 },
111844  { 148, 1 },
111845  { 148, 1 },
111846  { 148, 1 },
111847  { 147, 2 },
111848  { 147, 2 },
111849  { 147, 2 },
111850  { 151, 1 },
111851  { 151, 0 },
111852  { 147, 2 },
111853  { 147, 3 },
111854  { 147, 5 },
111855  { 147, 2 },
111856  { 152, 6 },
111857  { 154, 1 },
111858  { 156, 0 },
111859  { 156, 3 },
111860  { 155, 1 },
111861  { 155, 0 },
111862  { 153, 4 },
111863  { 153, 2 },
111864  { 158, 3 },
111865  { 158, 1 },
111866  { 161, 3 },
111867  { 162, 1 },
111868  { 165, 1 },
111869  { 165, 1 },
111870  { 166, 1 },
111871  { 150, 1 },
111872  { 150, 1 },
111873  { 150, 1 },
111874  { 163, 0 },
111875  { 163, 1 },
111876  { 167, 1 },
111877  { 167, 4 },
111878  { 167, 6 },
111879  { 168, 1 },
111880  { 168, 2 },
111881  { 169, 1 },
111882  { 169, 1 },
111883  { 164, 2 },
111884  { 164, 0 },
111885  { 172, 2 },
111886  { 172, 2 },
111887  { 172, 4 },
111888  { 172, 3 },
111889  { 172, 3 },
111890  { 172, 2 },
111891  { 172, 2 },
111892  { 172, 3 },
111893  { 172, 5 },
111894  { 172, 2 },
111895  { 172, 4 },
111896  { 172, 4 },
111897  { 172, 1 },
111898  { 172, 2 },
111899  { 177, 0 },
111900  { 177, 1 },
111901  { 179, 0 },
111902  { 179, 2 },
111903  { 181, 2 },
111904  { 181, 3 },
111905  { 181, 3 },
111906  { 181, 3 },
111907  { 182, 2 },
111908  { 182, 2 },
111909  { 182, 1 },
111910  { 182, 1 },
111911  { 182, 2 },
111912  { 180, 3 },
111913  { 180, 2 },
111914  { 183, 0 },
111915  { 183, 2 },
111916  { 183, 2 },
111917  { 159, 0 },
111918  { 159, 2 },
111919  { 184, 3 },
111920  { 184, 1 },
111921  { 185, 1 },
111922  { 185, 0 },
111923  { 186, 2 },
111924  { 186, 7 },
111925  { 186, 5 },
111926  { 186, 5 },
111927  { 186, 10 },
111928  { 188, 0 },
111929  { 188, 1 },
111930  { 175, 0 },
111931  { 175, 3 },
111932  { 189, 0 },
111933  { 189, 2 },
111934  { 190, 1 },
111935  { 190, 1 },
111936  { 190, 1 },
111937  { 147, 4 },
111938  { 192, 2 },
111939  { 192, 0 },
111940  { 147, 8 },
111941  { 147, 4 },
111942  { 147, 1 },
111943  { 160, 1 },
111944  { 160, 3 },
111945  { 195, 1 },
111946  { 195, 2 },
111947  { 195, 1 },
111948  { 194, 9 },
111949  { 196, 1 },
111950  { 196, 1 },
111951  { 196, 0 },
111952  { 204, 2 },
111953  { 204, 0 },
111954  { 197, 3 },
111955  { 197, 2 },
111956  { 197, 4 },
111957  { 205, 2 },
111958  { 205, 1 },
111959  { 205, 0 },
111960  { 198, 0 },
111961  { 198, 2 },
111962  { 207, 2 },
111963  { 207, 0 },
111964  { 206, 7 },
111965  { 206, 7 },
111966  { 206, 7 },
111967  { 157, 0 },
111968  { 157, 2 },
111969  { 193, 2 },
111970  { 208, 1 },
111971  { 208, 2 },
111972  { 208, 3 },
111973  { 208, 4 },
111974  { 210, 2 },
111975  { 210, 0 },
111976  { 209, 0 },
111977  { 209, 3 },
111978  { 209, 2 },
111979  { 211, 4 },
111980  { 211, 0 },
111981  { 202, 0 },
111982  { 202, 3 },
111983  { 214, 4 },
111984  { 214, 2 },
111985  { 176, 1 },
111986  { 176, 1 },
111987  { 176, 0 },
111988  { 200, 0 },
111989  { 200, 3 },
111990  { 201, 0 },
111991  { 201, 2 },
111992  { 203, 0 },
111993  { 203, 2 },
111994  { 203, 4 },
111995  { 203, 4 },
111996  { 147, 5 },
111997  { 199, 0 },
111998  { 199, 2 },
111999  { 147, 7 },
112000  { 216, 5 },
112001  { 216, 3 },
112002  { 147, 5 },
112003  { 147, 5 },
112004  { 147, 6 },
112005  { 217, 2 },
112006  { 217, 1 },
112007  { 219, 4 },
112008  { 219, 5 },
112009  { 218, 0 },
112010  { 218, 3 },
112011  { 213, 3 },
112012  { 213, 1 },
112013  { 174, 1 },
112014  { 174, 3 },
112015  { 173, 1 },
112016  { 174, 1 },
112017  { 174, 1 },
112018  { 174, 3 },
112019  { 174, 5 },
112020  { 173, 1 },
112021  { 173, 1 },
112022  { 174, 1 },
112023  { 174, 1 },
112024  { 174, 3 },
112025  { 174, 6 },
112026  { 174, 5 },
112027  { 174, 4 },
112028  { 173, 1 },
112029  { 174, 3 },
112030  { 174, 3 },
112031  { 174, 3 },
112032  { 174, 3 },
112033  { 174, 3 },
112034  { 174, 3 },
112035  { 174, 3 },
112036  { 174, 3 },
112037  { 221, 1 },
112038  { 221, 2 },
112039  { 221, 1 },
112040  { 221, 2 },
112041  { 174, 3 },
112042  { 174, 5 },
112043  { 174, 2 },
112044  { 174, 3 },
112045  { 174, 3 },
112046  { 174, 4 },
112047  { 174, 2 },
112048  { 174, 2 },
112049  { 174, 2 },
112050  { 174, 2 },
112051  { 222, 1 },
112052  { 222, 2 },
112053  { 174, 5 },
112054  { 223, 1 },
112055  { 223, 2 },
112056  { 174, 5 },
112057  { 174, 3 },
112058  { 174, 5 },
112059  { 174, 4 },
112060  { 174, 4 },
112061  { 174, 5 },
112062  { 225, 5 },
112063  { 225, 4 },
112064  { 226, 2 },
112065  { 226, 0 },
112066  { 224, 1 },
112067  { 224, 0 },
112068  { 220, 1 },
112069  { 220, 0 },
112070  { 215, 3 },
112071  { 215, 1 },
112072  { 147, 11 },
112073  { 227, 1 },
112074  { 227, 0 },
112075  { 178, 0 },
112076  { 178, 3 },
112077  { 187, 5 },
112078  { 187, 3 },
112079  { 228, 0 },
112080  { 228, 2 },
112081  { 147, 4 },
112082  { 147, 1 },
112083  { 147, 2 },
112084  { 147, 3 },
112085  { 147, 5 },
112086  { 147, 6 },
112087  { 147, 5 },
112088  { 147, 6 },
112089  { 229, 1 },
112090  { 229, 1 },
112091  { 229, 1 },
112092  { 229, 1 },
112093  { 229, 1 },
112094  { 170, 2 },
112095  { 170, 1 },
112096  { 171, 2 },
112097  { 230, 1 },
112098  { 147, 5 },
112099  { 231, 11 },
112100  { 233, 1 },
112101  { 233, 1 },
112102  { 233, 2 },
112103  { 233, 0 },
112104  { 234, 1 },
112105  { 234, 1 },
112106  { 234, 3 },
112107  { 235, 0 },
112108  { 235, 3 },
112109  { 236, 0 },
112110  { 236, 2 },
112111  { 232, 3 },
112112  { 232, 2 },
112113  { 238, 1 },
112114  { 238, 3 },
112115  { 239, 0 },
112116  { 239, 3 },
112117  { 239, 2 },
112118  { 237, 7 },
112119  { 237, 5 },
112120  { 237, 5 },
112121  { 237, 5 },
112122  { 237, 1 },
112123  { 174, 4 },
112124  { 174, 6 },
112125  { 191, 1 },
112126  { 191, 1 },
112127  { 191, 1 },
112128  { 147, 4 },
112129  { 147, 6 },
112130  { 147, 3 },
112131  { 241, 0 },
112132  { 241, 2 },
112133  { 240, 1 },
112134  { 240, 0 },
112135  { 147, 1 },
112136  { 147, 3 },
112137  { 147, 1 },
112138  { 147, 3 },
112139  { 147, 6 },
112140  { 147, 6 },
112141  { 242, 1 },
112142  { 243, 0 },
112143  { 243, 1 },
112144  { 147, 1 },
112145  { 147, 4 },
112146  { 244, 8 },
112147  { 245, 1 },
112148  { 245, 3 },
112149  { 246, 0 },
112150  { 246, 2 },
112151  { 247, 1 },
112152  { 247, 3 },
112153  { 248, 1 },
112154  { 249, 0 },
112155  { 249, 4 },
112156  { 249, 2 },
112157};
112158
112159static void yy_accept(yyParser*);  /* Forward Declaration */
112160
112161/*
112162** Perform a reduce action and the shift that must immediately
112163** follow the reduce.
112164*/
112165static void yy_reduce(
112166  yyParser *yypParser,         /* The parser */
112167  int yyruleno                 /* Number of the rule by which to reduce */
112168){
112169  int yygoto;                     /* The next state */
112170  int yyact;                      /* The next action */
112171  YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
112172  yyStackEntry *yymsp;            /* The top of the parser's stack */
112173  int yysize;                     /* Amount to pop the stack */
112174  sqlite3ParserARG_FETCH;
112175  yymsp = &yypParser->yystack[yypParser->yyidx];
112176#ifndef NDEBUG
112177  if( yyTraceFILE && yyruleno>=0
112178        && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
112179    fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
112180      yyRuleName[yyruleno]);
112181  }
112182#endif /* NDEBUG */
112183
112184  /* Silence complaints from purify about yygotominor being uninitialized
112185  ** in some cases when it is copied into the stack after the following
112186  ** switch.  yygotominor is uninitialized when a rule reduces that does
112187  ** not set the value of its left-hand side nonterminal.  Leaving the
112188  ** value of the nonterminal uninitialized is utterly harmless as long
112189  ** as the value is never used.  So really the only thing this code
112190  ** accomplishes is to quieten purify.
112191  **
112192  ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
112193  ** without this code, their parser segfaults.  I'm not sure what there
112194  ** parser is doing to make this happen.  This is the second bug report
112195  ** from wireshark this week.  Clearly they are stressing Lemon in ways
112196  ** that it has not been previously stressed...  (SQLite ticket #2172)
112197  */
112198  /*memset(&yygotominor, 0, sizeof(yygotominor));*/
112199  yygotominor = yyzerominor;
112200
112201
112202  switch( yyruleno ){
112203  /* Beginning here are the reduction cases.  A typical example
112204  ** follows:
112205  **   case 0:
112206  **  #line <lineno> <grammarfile>
112207  **     { ... }           // User supplied code
112208  **  #line <lineno> <thisfile>
112209  **     break;
112210  */
112211      case 5: /* explain ::= */
112212{ sqlite3BeginParse(pParse, 0); }
112213        break;
112214      case 6: /* explain ::= EXPLAIN */
112215{ sqlite3BeginParse(pParse, 1); }
112216        break;
112217      case 7: /* explain ::= EXPLAIN QUERY PLAN */
112218{ sqlite3BeginParse(pParse, 2); }
112219        break;
112220      case 8: /* cmdx ::= cmd */
112221{ sqlite3FinishCoding(pParse); }
112222        break;
112223      case 9: /* cmd ::= BEGIN transtype trans_opt */
112224{sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy392);}
112225        break;
112226      case 13: /* transtype ::= */
112227{yygotominor.yy392 = TK_DEFERRED;}
112228        break;
112229      case 14: /* transtype ::= DEFERRED */
112230      case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
112231      case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
112232      case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
112233      case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
112234{yygotominor.yy392 = yymsp[0].major;}
112235        break;
112236      case 17: /* cmd ::= COMMIT trans_opt */
112237      case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
112238{sqlite3CommitTransaction(pParse);}
112239        break;
112240      case 19: /* cmd ::= ROLLBACK trans_opt */
112241{sqlite3RollbackTransaction(pParse);}
112242        break;
112243      case 22: /* cmd ::= SAVEPOINT nm */
112244{
112245  sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
112246}
112247        break;
112248      case 23: /* cmd ::= RELEASE savepoint_opt nm */
112249{
112250  sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
112251}
112252        break;
112253      case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
112254{
112255  sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
112256}
112257        break;
112258      case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
112259{
112260   sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy392,0,0,yymsp[-2].minor.yy392);
112261}
112262        break;
112263      case 27: /* createkw ::= CREATE */
112264{
112265  pParse->db->lookaside.bEnabled = 0;
112266  yygotominor.yy0 = yymsp[0].minor.yy0;
112267}
112268        break;
112269      case 28: /* ifnotexists ::= */
112270      case 31: /* temp ::= */ yytestcase(yyruleno==31);
112271      case 69: /* autoinc ::= */ yytestcase(yyruleno==69);
112272      case 82: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==82);
112273      case 84: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==84);
112274      case 86: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==86);
112275      case 98: /* defer_subclause_opt ::= */ yytestcase(yyruleno==98);
112276      case 109: /* ifexists ::= */ yytestcase(yyruleno==109);
112277      case 221: /* between_op ::= BETWEEN */ yytestcase(yyruleno==221);
112278      case 224: /* in_op ::= IN */ yytestcase(yyruleno==224);
112279{yygotominor.yy392 = 0;}
112280        break;
112281      case 29: /* ifnotexists ::= IF NOT EXISTS */
112282      case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
112283      case 70: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==70);
112284      case 85: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==85);
112285      case 108: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==108);
112286      case 222: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==222);
112287      case 225: /* in_op ::= NOT IN */ yytestcase(yyruleno==225);
112288{yygotominor.yy392 = 1;}
112289        break;
112290      case 32: /* create_table_args ::= LP columnlist conslist_opt RP */
112291{
112292  sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
112293}
112294        break;
112295      case 33: /* create_table_args ::= AS select */
112296{
112297  sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy159);
112298  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy159);
112299}
112300        break;
112301      case 36: /* column ::= columnid type carglist */
112302{
112303  yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
112304  yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
112305}
112306        break;
112307      case 37: /* columnid ::= nm */
112308{
112309  sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
112310  yygotominor.yy0 = yymsp[0].minor.yy0;
112311  pParse->constraintName.n = 0;
112312}
112313        break;
112314      case 38: /* id ::= ID */
112315      case 39: /* id ::= INDEXED */ yytestcase(yyruleno==39);
112316      case 40: /* ids ::= ID|STRING */ yytestcase(yyruleno==40);
112317      case 41: /* nm ::= id */ yytestcase(yyruleno==41);
112318      case 42: /* nm ::= STRING */ yytestcase(yyruleno==42);
112319      case 43: /* nm ::= JOIN_KW */ yytestcase(yyruleno==43);
112320      case 46: /* typetoken ::= typename */ yytestcase(yyruleno==46);
112321      case 49: /* typename ::= ids */ yytestcase(yyruleno==49);
112322      case 127: /* as ::= AS nm */ yytestcase(yyruleno==127);
112323      case 128: /* as ::= ids */ yytestcase(yyruleno==128);
112324      case 138: /* dbnm ::= DOT nm */ yytestcase(yyruleno==138);
112325      case 147: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==147);
112326      case 250: /* collate ::= COLLATE ids */ yytestcase(yyruleno==250);
112327      case 259: /* nmnum ::= plus_num */ yytestcase(yyruleno==259);
112328      case 260: /* nmnum ::= nm */ yytestcase(yyruleno==260);
112329      case 261: /* nmnum ::= ON */ yytestcase(yyruleno==261);
112330      case 262: /* nmnum ::= DELETE */ yytestcase(yyruleno==262);
112331      case 263: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==263);
112332      case 264: /* plus_num ::= PLUS number */ yytestcase(yyruleno==264);
112333      case 265: /* plus_num ::= number */ yytestcase(yyruleno==265);
112334      case 266: /* minus_num ::= MINUS number */ yytestcase(yyruleno==266);
112335      case 267: /* number ::= INTEGER|FLOAT */ yytestcase(yyruleno==267);
112336      case 283: /* trnm ::= nm */ yytestcase(yyruleno==283);
112337{yygotominor.yy0 = yymsp[0].minor.yy0;}
112338        break;
112339      case 45: /* type ::= typetoken */
112340{sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
112341        break;
112342      case 47: /* typetoken ::= typename LP signed RP */
112343{
112344  yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
112345  yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
112346}
112347        break;
112348      case 48: /* typetoken ::= typename LP signed COMMA signed RP */
112349{
112350  yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
112351  yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
112352}
112353        break;
112354      case 50: /* typename ::= typename ids */
112355{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);}
112356        break;
112357      case 55: /* ccons ::= CONSTRAINT nm */
112358      case 93: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==93);
112359{pParse->constraintName = yymsp[0].minor.yy0;}
112360        break;
112361      case 56: /* ccons ::= DEFAULT term */
112362      case 58: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==58);
112363{sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy342);}
112364        break;
112365      case 57: /* ccons ::= DEFAULT LP expr RP */
112366{sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy342);}
112367        break;
112368      case 59: /* ccons ::= DEFAULT MINUS term */
112369{
112370  ExprSpan v;
112371  v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy342.pExpr, 0, 0);
112372  v.zStart = yymsp[-1].minor.yy0.z;
112373  v.zEnd = yymsp[0].minor.yy342.zEnd;
112374  sqlite3AddDefaultValue(pParse,&v);
112375}
112376        break;
112377      case 60: /* ccons ::= DEFAULT id */
112378{
112379  ExprSpan v;
112380  spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
112381  sqlite3AddDefaultValue(pParse,&v);
112382}
112383        break;
112384      case 62: /* ccons ::= NOT NULL onconf */
112385{sqlite3AddNotNull(pParse, yymsp[0].minor.yy392);}
112386        break;
112387      case 63: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
112388{sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy392,yymsp[0].minor.yy392,yymsp[-2].minor.yy392);}
112389        break;
112390      case 64: /* ccons ::= UNIQUE onconf */
112391{sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy392,0,0,0,0);}
112392        break;
112393      case 65: /* ccons ::= CHECK LP expr RP */
112394{sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy342.pExpr);}
112395        break;
112396      case 66: /* ccons ::= REFERENCES nm idxlist_opt refargs */
112397{sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy442,yymsp[0].minor.yy392);}
112398        break;
112399      case 67: /* ccons ::= defer_subclause */
112400{sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy392);}
112401        break;
112402      case 68: /* ccons ::= COLLATE ids */
112403{sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
112404        break;
112405      case 71: /* refargs ::= */
112406{ yygotominor.yy392 = OE_None*0x0101; /* EV: R-19803-45884 */}
112407        break;
112408      case 72: /* refargs ::= refargs refarg */
112409{ yygotominor.yy392 = (yymsp[-1].minor.yy392 & ~yymsp[0].minor.yy207.mask) | yymsp[0].minor.yy207.value; }
112410        break;
112411      case 73: /* refarg ::= MATCH nm */
112412      case 74: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==74);
112413{ yygotominor.yy207.value = 0;     yygotominor.yy207.mask = 0x000000; }
112414        break;
112415      case 75: /* refarg ::= ON DELETE refact */
112416{ yygotominor.yy207.value = yymsp[0].minor.yy392;     yygotominor.yy207.mask = 0x0000ff; }
112417        break;
112418      case 76: /* refarg ::= ON UPDATE refact */
112419{ yygotominor.yy207.value = yymsp[0].minor.yy392<<8;  yygotominor.yy207.mask = 0x00ff00; }
112420        break;
112421      case 77: /* refact ::= SET NULL */
112422{ yygotominor.yy392 = OE_SetNull;  /* EV: R-33326-45252 */}
112423        break;
112424      case 78: /* refact ::= SET DEFAULT */
112425{ yygotominor.yy392 = OE_SetDflt;  /* EV: R-33326-45252 */}
112426        break;
112427      case 79: /* refact ::= CASCADE */
112428{ yygotominor.yy392 = OE_Cascade;  /* EV: R-33326-45252 */}
112429        break;
112430      case 80: /* refact ::= RESTRICT */
112431{ yygotominor.yy392 = OE_Restrict; /* EV: R-33326-45252 */}
112432        break;
112433      case 81: /* refact ::= NO ACTION */
112434{ yygotominor.yy392 = OE_None;     /* EV: R-33326-45252 */}
112435        break;
112436      case 83: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
112437      case 99: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==99);
112438      case 101: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==101);
112439      case 104: /* resolvetype ::= raisetype */ yytestcase(yyruleno==104);
112440{yygotominor.yy392 = yymsp[0].minor.yy392;}
112441        break;
112442      case 87: /* conslist_opt ::= */
112443{yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
112444        break;
112445      case 88: /* conslist_opt ::= COMMA conslist */
112446{yygotominor.yy0 = yymsp[-1].minor.yy0;}
112447        break;
112448      case 91: /* tconscomma ::= COMMA */
112449{pParse->constraintName.n = 0;}
112450        break;
112451      case 94: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
112452{sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy442,yymsp[0].minor.yy392,yymsp[-2].minor.yy392,0);}
112453        break;
112454      case 95: /* tcons ::= UNIQUE LP idxlist RP onconf */
112455{sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy442,yymsp[0].minor.yy392,0,0,0,0);}
112456        break;
112457      case 96: /* tcons ::= CHECK LP expr RP onconf */
112458{sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy342.pExpr);}
112459        break;
112460      case 97: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
112461{
112462    sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy442, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy442, yymsp[-1].minor.yy392);
112463    sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy392);
112464}
112465        break;
112466      case 100: /* onconf ::= */
112467{yygotominor.yy392 = OE_Default;}
112468        break;
112469      case 102: /* orconf ::= */
112470{yygotominor.yy258 = OE_Default;}
112471        break;
112472      case 103: /* orconf ::= OR resolvetype */
112473{yygotominor.yy258 = (u8)yymsp[0].minor.yy392;}
112474        break;
112475      case 105: /* resolvetype ::= IGNORE */
112476{yygotominor.yy392 = OE_Ignore;}
112477        break;
112478      case 106: /* resolvetype ::= REPLACE */
112479{yygotominor.yy392 = OE_Replace;}
112480        break;
112481      case 107: /* cmd ::= DROP TABLE ifexists fullname */
112482{
112483  sqlite3DropTable(pParse, yymsp[0].minor.yy347, 0, yymsp[-1].minor.yy392);
112484}
112485        break;
112486      case 110: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
112487{
112488  sqlite3CreateView(pParse, &yymsp[-7].minor.yy0, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, yymsp[0].minor.yy159, yymsp[-6].minor.yy392, yymsp[-4].minor.yy392);
112489}
112490        break;
112491      case 111: /* cmd ::= DROP VIEW ifexists fullname */
112492{
112493  sqlite3DropTable(pParse, yymsp[0].minor.yy347, 1, yymsp[-1].minor.yy392);
112494}
112495        break;
112496      case 112: /* cmd ::= select */
112497{
112498  SelectDest dest = {SRT_Output, 0, 0, 0, 0};
112499  sqlite3Select(pParse, yymsp[0].minor.yy159, &dest);
112500  sqlite3ExplainBegin(pParse->pVdbe);
112501  sqlite3ExplainSelect(pParse->pVdbe, yymsp[0].minor.yy159);
112502  sqlite3ExplainFinish(pParse->pVdbe);
112503  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy159);
112504}
112505        break;
112506      case 113: /* select ::= oneselect */
112507{yygotominor.yy159 = yymsp[0].minor.yy159;}
112508        break;
112509      case 114: /* select ::= select multiselect_op oneselect */
112510{
112511  if( yymsp[0].minor.yy159 ){
112512    yymsp[0].minor.yy159->op = (u8)yymsp[-1].minor.yy392;
112513    yymsp[0].minor.yy159->pPrior = yymsp[-2].minor.yy159;
112514  }else{
112515    sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy159);
112516  }
112517  yygotominor.yy159 = yymsp[0].minor.yy159;
112518}
112519        break;
112520      case 116: /* multiselect_op ::= UNION ALL */
112521{yygotominor.yy392 = TK_ALL;}
112522        break;
112523      case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
112524{
112525  yygotominor.yy159 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy442,yymsp[-5].minor.yy347,yymsp[-4].minor.yy122,yymsp[-3].minor.yy442,yymsp[-2].minor.yy122,yymsp[-1].minor.yy442,yymsp[-7].minor.yy305,yymsp[0].minor.yy64.pLimit,yymsp[0].minor.yy64.pOffset);
112526}
112527        break;
112528      case 119: /* distinct ::= DISTINCT */
112529{yygotominor.yy305 = SF_Distinct;}
112530        break;
112531      case 120: /* distinct ::= ALL */
112532      case 121: /* distinct ::= */ yytestcase(yyruleno==121);
112533{yygotominor.yy305 = 0;}
112534        break;
112535      case 122: /* sclp ::= selcollist COMMA */
112536      case 246: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==246);
112537{yygotominor.yy442 = yymsp[-1].minor.yy442;}
112538        break;
112539      case 123: /* sclp ::= */
112540      case 151: /* orderby_opt ::= */ yytestcase(yyruleno==151);
112541      case 158: /* groupby_opt ::= */ yytestcase(yyruleno==158);
112542      case 239: /* exprlist ::= */ yytestcase(yyruleno==239);
112543      case 245: /* idxlist_opt ::= */ yytestcase(yyruleno==245);
112544{yygotominor.yy442 = 0;}
112545        break;
112546      case 124: /* selcollist ::= sclp expr as */
112547{
112548   yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy442, yymsp[-1].minor.yy342.pExpr);
112549   if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[0].minor.yy0, 1);
112550   sqlite3ExprListSetSpan(pParse,yygotominor.yy442,&yymsp[-1].minor.yy342);
112551}
112552        break;
112553      case 125: /* selcollist ::= sclp STAR */
112554{
112555  Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
112556  yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy442, p);
112557}
112558        break;
112559      case 126: /* selcollist ::= sclp nm DOT STAR */
112560{
112561  Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
112562  Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
112563  Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
112564  yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy442, pDot);
112565}
112566        break;
112567      case 129: /* as ::= */
112568{yygotominor.yy0.n = 0;}
112569        break;
112570      case 130: /* from ::= */
112571{yygotominor.yy347 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy347));}
112572        break;
112573      case 131: /* from ::= FROM seltablist */
112574{
112575  yygotominor.yy347 = yymsp[0].minor.yy347;
112576  sqlite3SrcListShiftJoinType(yygotominor.yy347);
112577}
112578        break;
112579      case 132: /* stl_prefix ::= seltablist joinop */
112580{
112581   yygotominor.yy347 = yymsp[-1].minor.yy347;
112582   if( ALWAYS(yygotominor.yy347 && yygotominor.yy347->nSrc>0) ) yygotominor.yy347->a[yygotominor.yy347->nSrc-1].jointype = (u8)yymsp[0].minor.yy392;
112583}
112584        break;
112585      case 133: /* stl_prefix ::= */
112586{yygotominor.yy347 = 0;}
112587        break;
112588      case 134: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
112589{
112590  yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
112591  sqlite3SrcListIndexedBy(pParse, yygotominor.yy347, &yymsp[-2].minor.yy0);
112592}
112593        break;
112594      case 135: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
112595{
112596    yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy159,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
112597  }
112598        break;
112599      case 136: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
112600{
112601    if( yymsp[-6].minor.yy347==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy122==0 && yymsp[0].minor.yy180==0 ){
112602      yygotominor.yy347 = yymsp[-4].minor.yy347;
112603    }else if( yymsp[-4].minor.yy347->nSrc==1 ){
112604      yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
112605      if( yygotominor.yy347 ){
112606        struct SrcList_item *pNew = &yygotominor.yy347->a[yygotominor.yy347->nSrc-1];
112607        struct SrcList_item *pOld = yymsp[-4].minor.yy347->a;
112608        pNew->zName = pOld->zName;
112609        pNew->zDatabase = pOld->zDatabase;
112610        pNew->pSelect = pOld->pSelect;
112611        pOld->zName = pOld->zDatabase = 0;
112612        pOld->pSelect = 0;
112613      }
112614      sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy347);
112615    }else{
112616      Select *pSubquery;
112617      sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy347);
112618      pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy347,0,0,0,0,SF_NestedFrom,0,0);
112619      yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
112620    }
112621  }
112622        break;
112623      case 137: /* dbnm ::= */
112624      case 146: /* indexed_opt ::= */ yytestcase(yyruleno==146);
112625{yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
112626        break;
112627      case 139: /* fullname ::= nm dbnm */
112628{yygotominor.yy347 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
112629        break;
112630      case 140: /* joinop ::= COMMA|JOIN */
112631{ yygotominor.yy392 = JT_INNER; }
112632        break;
112633      case 141: /* joinop ::= JOIN_KW JOIN */
112634{ yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
112635        break;
112636      case 142: /* joinop ::= JOIN_KW nm JOIN */
112637{ yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
112638        break;
112639      case 143: /* joinop ::= JOIN_KW nm nm JOIN */
112640{ yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
112641        break;
112642      case 144: /* on_opt ::= ON expr */
112643      case 161: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==161);
112644      case 168: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==168);
112645      case 234: /* case_else ::= ELSE expr */ yytestcase(yyruleno==234);
112646      case 236: /* case_operand ::= expr */ yytestcase(yyruleno==236);
112647{yygotominor.yy122 = yymsp[0].minor.yy342.pExpr;}
112648        break;
112649      case 145: /* on_opt ::= */
112650      case 160: /* having_opt ::= */ yytestcase(yyruleno==160);
112651      case 167: /* where_opt ::= */ yytestcase(yyruleno==167);
112652      case 235: /* case_else ::= */ yytestcase(yyruleno==235);
112653      case 237: /* case_operand ::= */ yytestcase(yyruleno==237);
112654{yygotominor.yy122 = 0;}
112655        break;
112656      case 148: /* indexed_opt ::= NOT INDEXED */
112657{yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
112658        break;
112659      case 149: /* using_opt ::= USING LP inscollist RP */
112660      case 180: /* inscollist_opt ::= LP inscollist RP */ yytestcase(yyruleno==180);
112661{yygotominor.yy180 = yymsp[-1].minor.yy180;}
112662        break;
112663      case 150: /* using_opt ::= */
112664      case 179: /* inscollist_opt ::= */ yytestcase(yyruleno==179);
112665{yygotominor.yy180 = 0;}
112666        break;
112667      case 152: /* orderby_opt ::= ORDER BY sortlist */
112668      case 159: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==159);
112669      case 238: /* exprlist ::= nexprlist */ yytestcase(yyruleno==238);
112670{yygotominor.yy442 = yymsp[0].minor.yy442;}
112671        break;
112672      case 153: /* sortlist ::= sortlist COMMA expr sortorder */
112673{
112674  yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy442,yymsp[-1].minor.yy342.pExpr);
112675  if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
112676}
112677        break;
112678      case 154: /* sortlist ::= expr sortorder */
112679{
112680  yygotominor.yy442 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy342.pExpr);
112681  if( yygotominor.yy442 && ALWAYS(yygotominor.yy442->a) ) yygotominor.yy442->a[0].sortOrder = (u8)yymsp[0].minor.yy392;
112682}
112683        break;
112684      case 155: /* sortorder ::= ASC */
112685      case 157: /* sortorder ::= */ yytestcase(yyruleno==157);
112686{yygotominor.yy392 = SQLITE_SO_ASC;}
112687        break;
112688      case 156: /* sortorder ::= DESC */
112689{yygotominor.yy392 = SQLITE_SO_DESC;}
112690        break;
112691      case 162: /* limit_opt ::= */
112692{yygotominor.yy64.pLimit = 0; yygotominor.yy64.pOffset = 0;}
112693        break;
112694      case 163: /* limit_opt ::= LIMIT expr */
112695{yygotominor.yy64.pLimit = yymsp[0].minor.yy342.pExpr; yygotominor.yy64.pOffset = 0;}
112696        break;
112697      case 164: /* limit_opt ::= LIMIT expr OFFSET expr */
112698{yygotominor.yy64.pLimit = yymsp[-2].minor.yy342.pExpr; yygotominor.yy64.pOffset = yymsp[0].minor.yy342.pExpr;}
112699        break;
112700      case 165: /* limit_opt ::= LIMIT expr COMMA expr */
112701{yygotominor.yy64.pOffset = yymsp[-2].minor.yy342.pExpr; yygotominor.yy64.pLimit = yymsp[0].minor.yy342.pExpr;}
112702        break;
112703      case 166: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
112704{
112705  sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy347, &yymsp[-1].minor.yy0);
112706  sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy347,yymsp[0].minor.yy122);
112707}
112708        break;
112709      case 169: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
112710{
112711  sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy347, &yymsp[-3].minor.yy0);
112712  sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy442,"set list");
112713  sqlite3Update(pParse,yymsp[-4].minor.yy347,yymsp[-1].minor.yy442,yymsp[0].minor.yy122,yymsp[-5].minor.yy258);
112714}
112715        break;
112716      case 170: /* setlist ::= setlist COMMA nm EQ expr */
112717{
112718  yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy442, yymsp[0].minor.yy342.pExpr);
112719  sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
112720}
112721        break;
112722      case 171: /* setlist ::= nm EQ expr */
112723{
112724  yygotominor.yy442 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy342.pExpr);
112725  sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
112726}
112727        break;
112728      case 172: /* cmd ::= insert_cmd INTO fullname inscollist_opt valuelist */
112729{sqlite3Insert(pParse, yymsp[-2].minor.yy347, yymsp[0].minor.yy487.pList, yymsp[0].minor.yy487.pSelect, yymsp[-1].minor.yy180, yymsp[-4].minor.yy258);}
112730        break;
112731      case 173: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
112732{sqlite3Insert(pParse, yymsp[-2].minor.yy347, 0, yymsp[0].minor.yy159, yymsp[-1].minor.yy180, yymsp[-4].minor.yy258);}
112733        break;
112734      case 174: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
112735{sqlite3Insert(pParse, yymsp[-3].minor.yy347, 0, 0, yymsp[-2].minor.yy180, yymsp[-5].minor.yy258);}
112736        break;
112737      case 175: /* insert_cmd ::= INSERT orconf */
112738{yygotominor.yy258 = yymsp[0].minor.yy258;}
112739        break;
112740      case 176: /* insert_cmd ::= REPLACE */
112741{yygotominor.yy258 = OE_Replace;}
112742        break;
112743      case 177: /* valuelist ::= VALUES LP nexprlist RP */
112744{
112745  yygotominor.yy487.pList = yymsp[-1].minor.yy442;
112746  yygotominor.yy487.pSelect = 0;
112747}
112748        break;
112749      case 178: /* valuelist ::= valuelist COMMA LP exprlist RP */
112750{
112751  Select *pRight = sqlite3SelectNew(pParse, yymsp[-1].minor.yy442, 0, 0, 0, 0, 0, 0, 0, 0);
112752  if( yymsp[-4].minor.yy487.pList ){
112753    yymsp[-4].minor.yy487.pSelect = sqlite3SelectNew(pParse, yymsp[-4].minor.yy487.pList, 0, 0, 0, 0, 0, 0, 0, 0);
112754    yymsp[-4].minor.yy487.pList = 0;
112755  }
112756  yygotominor.yy487.pList = 0;
112757  if( yymsp[-4].minor.yy487.pSelect==0 || pRight==0 ){
112758    sqlite3SelectDelete(pParse->db, pRight);
112759    sqlite3SelectDelete(pParse->db, yymsp[-4].minor.yy487.pSelect);
112760    yygotominor.yy487.pSelect = 0;
112761  }else{
112762    pRight->op = TK_ALL;
112763    pRight->pPrior = yymsp[-4].minor.yy487.pSelect;
112764    pRight->selFlags |= SF_Values;
112765    pRight->pPrior->selFlags |= SF_Values;
112766    yygotominor.yy487.pSelect = pRight;
112767  }
112768}
112769        break;
112770      case 181: /* inscollist ::= inscollist COMMA nm */
112771{yygotominor.yy180 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy180,&yymsp[0].minor.yy0);}
112772        break;
112773      case 182: /* inscollist ::= nm */
112774{yygotominor.yy180 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
112775        break;
112776      case 183: /* expr ::= term */
112777{yygotominor.yy342 = yymsp[0].minor.yy342;}
112778        break;
112779      case 184: /* expr ::= LP expr RP */
112780{yygotominor.yy342.pExpr = yymsp[-1].minor.yy342.pExpr; spanSet(&yygotominor.yy342,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
112781        break;
112782      case 185: /* term ::= NULL */
112783      case 190: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==190);
112784      case 191: /* term ::= STRING */ yytestcase(yyruleno==191);
112785{spanExpr(&yygotominor.yy342, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
112786        break;
112787      case 186: /* expr ::= id */
112788      case 187: /* expr ::= JOIN_KW */ yytestcase(yyruleno==187);
112789{spanExpr(&yygotominor.yy342, pParse, TK_ID, &yymsp[0].minor.yy0);}
112790        break;
112791      case 188: /* expr ::= nm DOT nm */
112792{
112793  Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
112794  Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
112795  yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
112796  spanSet(&yygotominor.yy342,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
112797}
112798        break;
112799      case 189: /* expr ::= nm DOT nm DOT nm */
112800{
112801  Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
112802  Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
112803  Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
112804  Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
112805  yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
112806  spanSet(&yygotominor.yy342,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
112807}
112808        break;
112809      case 192: /* expr ::= REGISTER */
112810{
112811  /* When doing a nested parse, one can include terms in an expression
112812  ** that look like this:   #1 #2 ...  These terms refer to registers
112813  ** in the virtual machine.  #N is the N-th register. */
112814  if( pParse->nested==0 ){
112815    sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
112816    yygotominor.yy342.pExpr = 0;
112817  }else{
112818    yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
112819    if( yygotominor.yy342.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy342.pExpr->iTable);
112820  }
112821  spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
112822}
112823        break;
112824      case 193: /* expr ::= VARIABLE */
112825{
112826  spanExpr(&yygotominor.yy342, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
112827  sqlite3ExprAssignVarNumber(pParse, yygotominor.yy342.pExpr);
112828  spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
112829}
112830        break;
112831      case 194: /* expr ::= expr COLLATE ids */
112832{
112833  yygotominor.yy342.pExpr = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy342.pExpr, &yymsp[0].minor.yy0);
112834  yygotominor.yy342.zStart = yymsp[-2].minor.yy342.zStart;
112835  yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
112836}
112837        break;
112838      case 195: /* expr ::= CAST LP expr AS typetoken RP */
112839{
112840  yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy342.pExpr, 0, &yymsp[-1].minor.yy0);
112841  spanSet(&yygotominor.yy342,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
112842}
112843        break;
112844      case 196: /* expr ::= ID LP distinct exprlist RP */
112845{
112846  if( yymsp[-1].minor.yy442 && yymsp[-1].minor.yy442->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
112847    sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
112848  }
112849  yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy442, &yymsp[-4].minor.yy0);
112850  spanSet(&yygotominor.yy342,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
112851  if( yymsp[-2].minor.yy305 && yygotominor.yy342.pExpr ){
112852    yygotominor.yy342.pExpr->flags |= EP_Distinct;
112853  }
112854}
112855        break;
112856      case 197: /* expr ::= ID LP STAR RP */
112857{
112858  yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
112859  spanSet(&yygotominor.yy342,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
112860}
112861        break;
112862      case 198: /* term ::= CTIME_KW */
112863{
112864  /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
112865  ** treated as functions that return constants */
112866  yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
112867  if( yygotominor.yy342.pExpr ){
112868    yygotominor.yy342.pExpr->op = TK_CONST_FUNC;
112869  }
112870  spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
112871}
112872        break;
112873      case 199: /* expr ::= expr AND expr */
112874      case 200: /* expr ::= expr OR expr */ yytestcase(yyruleno==200);
112875      case 201: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==201);
112876      case 202: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==202);
112877      case 203: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==203);
112878      case 204: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==204);
112879      case 205: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==205);
112880      case 206: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==206);
112881{spanBinaryExpr(&yygotominor.yy342,pParse,yymsp[-1].major,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy342);}
112882        break;
112883      case 207: /* likeop ::= LIKE_KW */
112884      case 209: /* likeop ::= MATCH */ yytestcase(yyruleno==209);
112885{yygotominor.yy318.eOperator = yymsp[0].minor.yy0; yygotominor.yy318.bNot = 0;}
112886        break;
112887      case 208: /* likeop ::= NOT LIKE_KW */
112888      case 210: /* likeop ::= NOT MATCH */ yytestcase(yyruleno==210);
112889{yygotominor.yy318.eOperator = yymsp[0].minor.yy0; yygotominor.yy318.bNot = 1;}
112890        break;
112891      case 211: /* expr ::= expr likeop expr */
112892{
112893  ExprList *pList;
112894  pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy342.pExpr);
112895  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy342.pExpr);
112896  yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy318.eOperator);
112897  if( yymsp[-1].minor.yy318.bNot ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
112898  yygotominor.yy342.zStart = yymsp[-2].minor.yy342.zStart;
112899  yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
112900  if( yygotominor.yy342.pExpr ) yygotominor.yy342.pExpr->flags |= EP_InfixFunc;
112901}
112902        break;
112903      case 212: /* expr ::= expr likeop expr ESCAPE expr */
112904{
112905  ExprList *pList;
112906  pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
112907  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy342.pExpr);
112908  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy342.pExpr);
112909  yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy318.eOperator);
112910  if( yymsp[-3].minor.yy318.bNot ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
112911  yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
112912  yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
112913  if( yygotominor.yy342.pExpr ) yygotominor.yy342.pExpr->flags |= EP_InfixFunc;
112914}
112915        break;
112916      case 213: /* expr ::= expr ISNULL|NOTNULL */
112917{spanUnaryPostfix(&yygotominor.yy342,pParse,yymsp[0].major,&yymsp[-1].minor.yy342,&yymsp[0].minor.yy0);}
112918        break;
112919      case 214: /* expr ::= expr NOT NULL */
112920{spanUnaryPostfix(&yygotominor.yy342,pParse,TK_NOTNULL,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy0);}
112921        break;
112922      case 215: /* expr ::= expr IS expr */
112923{
112924  spanBinaryExpr(&yygotominor.yy342,pParse,TK_IS,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy342);
112925  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy342.pExpr, yygotominor.yy342.pExpr, TK_ISNULL);
112926}
112927        break;
112928      case 216: /* expr ::= expr IS NOT expr */
112929{
112930  spanBinaryExpr(&yygotominor.yy342,pParse,TK_ISNOT,&yymsp[-3].minor.yy342,&yymsp[0].minor.yy342);
112931  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy342.pExpr, yygotominor.yy342.pExpr, TK_NOTNULL);
112932}
112933        break;
112934      case 217: /* expr ::= NOT expr */
112935      case 218: /* expr ::= BITNOT expr */ yytestcase(yyruleno==218);
112936{spanUnaryPrefix(&yygotominor.yy342,pParse,yymsp[-1].major,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
112937        break;
112938      case 219: /* expr ::= MINUS expr */
112939{spanUnaryPrefix(&yygotominor.yy342,pParse,TK_UMINUS,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
112940        break;
112941      case 220: /* expr ::= PLUS expr */
112942{spanUnaryPrefix(&yygotominor.yy342,pParse,TK_UPLUS,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
112943        break;
112944      case 223: /* expr ::= expr between_op expr AND expr */
112945{
112946  ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
112947  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy342.pExpr);
112948  yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy342.pExpr, 0, 0);
112949  if( yygotominor.yy342.pExpr ){
112950    yygotominor.yy342.pExpr->x.pList = pList;
112951  }else{
112952    sqlite3ExprListDelete(pParse->db, pList);
112953  }
112954  if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
112955  yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
112956  yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
112957}
112958        break;
112959      case 226: /* expr ::= expr in_op LP exprlist RP */
112960{
112961    if( yymsp[-1].minor.yy442==0 ){
112962      /* Expressions of the form
112963      **
112964      **      expr1 IN ()
112965      **      expr1 NOT IN ()
112966      **
112967      ** simplify to constants 0 (false) and 1 (true), respectively,
112968      ** regardless of the value of expr1.
112969      */
112970      yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy392]);
112971      sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy342.pExpr);
112972    }else{
112973      yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy342.pExpr, 0, 0);
112974      if( yygotominor.yy342.pExpr ){
112975        yygotominor.yy342.pExpr->x.pList = yymsp[-1].minor.yy442;
112976        sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
112977      }else{
112978        sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy442);
112979      }
112980      if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
112981    }
112982    yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
112983    yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
112984  }
112985        break;
112986      case 227: /* expr ::= LP select RP */
112987{
112988    yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
112989    if( yygotominor.yy342.pExpr ){
112990      yygotominor.yy342.pExpr->x.pSelect = yymsp[-1].minor.yy159;
112991      ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
112992      sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
112993    }else{
112994      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
112995    }
112996    yygotominor.yy342.zStart = yymsp[-2].minor.yy0.z;
112997    yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
112998  }
112999        break;
113000      case 228: /* expr ::= expr in_op LP select RP */
113001{
113002    yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy342.pExpr, 0, 0);
113003    if( yygotominor.yy342.pExpr ){
113004      yygotominor.yy342.pExpr->x.pSelect = yymsp[-1].minor.yy159;
113005      ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
113006      sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
113007    }else{
113008      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
113009    }
113010    if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
113011    yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
113012    yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
113013  }
113014        break;
113015      case 229: /* expr ::= expr in_op nm dbnm */
113016{
113017    SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
113018    yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy342.pExpr, 0, 0);
113019    if( yygotominor.yy342.pExpr ){
113020      yygotominor.yy342.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
113021      ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
113022      sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
113023    }else{
113024      sqlite3SrcListDelete(pParse->db, pSrc);
113025    }
113026    if( yymsp[-2].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
113027    yygotominor.yy342.zStart = yymsp[-3].minor.yy342.zStart;
113028    yygotominor.yy342.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];
113029  }
113030        break;
113031      case 230: /* expr ::= EXISTS LP select RP */
113032{
113033    Expr *p = yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
113034    if( p ){
113035      p->x.pSelect = yymsp[-1].minor.yy159;
113036      ExprSetProperty(p, EP_xIsSelect);
113037      sqlite3ExprSetHeight(pParse, p);
113038    }else{
113039      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
113040    }
113041    yygotominor.yy342.zStart = yymsp[-3].minor.yy0.z;
113042    yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
113043  }
113044        break;
113045      case 231: /* expr ::= CASE case_operand case_exprlist case_else END */
113046{
113047  yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy122, yymsp[-1].minor.yy122, 0);
113048  if( yygotominor.yy342.pExpr ){
113049    yygotominor.yy342.pExpr->x.pList = yymsp[-2].minor.yy442;
113050    sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
113051  }else{
113052    sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy442);
113053  }
113054  yygotominor.yy342.zStart = yymsp[-4].minor.yy0.z;
113055  yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
113056}
113057        break;
113058      case 232: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
113059{
113060  yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy442, yymsp[-2].minor.yy342.pExpr);
113061  yygotominor.yy442 = sqlite3ExprListAppend(pParse,yygotominor.yy442, yymsp[0].minor.yy342.pExpr);
113062}
113063        break;
113064      case 233: /* case_exprlist ::= WHEN expr THEN expr */
113065{
113066  yygotominor.yy442 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
113067  yygotominor.yy442 = sqlite3ExprListAppend(pParse,yygotominor.yy442, yymsp[0].minor.yy342.pExpr);
113068}
113069        break;
113070      case 240: /* nexprlist ::= nexprlist COMMA expr */
113071{yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy442,yymsp[0].minor.yy342.pExpr);}
113072        break;
113073      case 241: /* nexprlist ::= expr */
113074{yygotominor.yy442 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy342.pExpr);}
113075        break;
113076      case 242: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */
113077{
113078  sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0,
113079                     sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy0,0), yymsp[-1].minor.yy442, yymsp[-9].minor.yy392,
113080                      &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy392);
113081}
113082        break;
113083      case 243: /* uniqueflag ::= UNIQUE */
113084      case 296: /* raisetype ::= ABORT */ yytestcase(yyruleno==296);
113085{yygotominor.yy392 = OE_Abort;}
113086        break;
113087      case 244: /* uniqueflag ::= */
113088{yygotominor.yy392 = OE_None;}
113089        break;
113090      case 247: /* idxlist ::= idxlist COMMA nm collate sortorder */
113091{
113092  Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0);
113093  yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy442, p);
113094  sqlite3ExprListSetName(pParse,yygotominor.yy442,&yymsp[-2].minor.yy0,1);
113095  sqlite3ExprListCheckLength(pParse, yygotominor.yy442, "index");
113096  if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
113097}
113098        break;
113099      case 248: /* idxlist ::= nm collate sortorder */
113100{
113101  Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0);
113102  yygotominor.yy442 = sqlite3ExprListAppend(pParse,0, p);
113103  sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
113104  sqlite3ExprListCheckLength(pParse, yygotominor.yy442, "index");
113105  if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
113106}
113107        break;
113108      case 249: /* collate ::= */
113109{yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
113110        break;
113111      case 251: /* cmd ::= DROP INDEX ifexists fullname */
113112{sqlite3DropIndex(pParse, yymsp[0].minor.yy347, yymsp[-1].minor.yy392);}
113113        break;
113114      case 252: /* cmd ::= VACUUM */
113115      case 253: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==253);
113116{sqlite3Vacuum(pParse);}
113117        break;
113118      case 254: /* cmd ::= PRAGMA nm dbnm */
113119{sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
113120        break;
113121      case 255: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
113122{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
113123        break;
113124      case 256: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
113125{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
113126        break;
113127      case 257: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
113128{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
113129        break;
113130      case 258: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
113131{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
113132        break;
113133      case 268: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
113134{
113135  Token all;
113136  all.z = yymsp[-3].minor.yy0.z;
113137  all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
113138  sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy327, &all);
113139}
113140        break;
113141      case 269: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
113142{
113143  sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy392, yymsp[-4].minor.yy410.a, yymsp[-4].minor.yy410.b, yymsp[-2].minor.yy347, yymsp[0].minor.yy122, yymsp[-10].minor.yy392, yymsp[-8].minor.yy392);
113144  yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
113145}
113146        break;
113147      case 270: /* trigger_time ::= BEFORE */
113148      case 273: /* trigger_time ::= */ yytestcase(yyruleno==273);
113149{ yygotominor.yy392 = TK_BEFORE; }
113150        break;
113151      case 271: /* trigger_time ::= AFTER */
113152{ yygotominor.yy392 = TK_AFTER;  }
113153        break;
113154      case 272: /* trigger_time ::= INSTEAD OF */
113155{ yygotominor.yy392 = TK_INSTEAD;}
113156        break;
113157      case 274: /* trigger_event ::= DELETE|INSERT */
113158      case 275: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==275);
113159{yygotominor.yy410.a = yymsp[0].major; yygotominor.yy410.b = 0;}
113160        break;
113161      case 276: /* trigger_event ::= UPDATE OF inscollist */
113162{yygotominor.yy410.a = TK_UPDATE; yygotominor.yy410.b = yymsp[0].minor.yy180;}
113163        break;
113164      case 279: /* when_clause ::= */
113165      case 301: /* key_opt ::= */ yytestcase(yyruleno==301);
113166{ yygotominor.yy122 = 0; }
113167        break;
113168      case 280: /* when_clause ::= WHEN expr */
113169      case 302: /* key_opt ::= KEY expr */ yytestcase(yyruleno==302);
113170{ yygotominor.yy122 = yymsp[0].minor.yy342.pExpr; }
113171        break;
113172      case 281: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
113173{
113174  assert( yymsp[-2].minor.yy327!=0 );
113175  yymsp[-2].minor.yy327->pLast->pNext = yymsp[-1].minor.yy327;
113176  yymsp[-2].minor.yy327->pLast = yymsp[-1].minor.yy327;
113177  yygotominor.yy327 = yymsp[-2].minor.yy327;
113178}
113179        break;
113180      case 282: /* trigger_cmd_list ::= trigger_cmd SEMI */
113181{
113182  assert( yymsp[-1].minor.yy327!=0 );
113183  yymsp[-1].minor.yy327->pLast = yymsp[-1].minor.yy327;
113184  yygotominor.yy327 = yymsp[-1].minor.yy327;
113185}
113186        break;
113187      case 284: /* trnm ::= nm DOT nm */
113188{
113189  yygotominor.yy0 = yymsp[0].minor.yy0;
113190  sqlite3ErrorMsg(pParse,
113191        "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
113192        "statements within triggers");
113193}
113194        break;
113195      case 286: /* tridxby ::= INDEXED BY nm */
113196{
113197  sqlite3ErrorMsg(pParse,
113198        "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
113199        "within triggers");
113200}
113201        break;
113202      case 287: /* tridxby ::= NOT INDEXED */
113203{
113204  sqlite3ErrorMsg(pParse,
113205        "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
113206        "within triggers");
113207}
113208        break;
113209      case 288: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
113210{ yygotominor.yy327 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy442, yymsp[0].minor.yy122, yymsp[-5].minor.yy258); }
113211        break;
113212      case 289: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt valuelist */
113213{yygotominor.yy327 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy180, yymsp[0].minor.yy487.pList, yymsp[0].minor.yy487.pSelect, yymsp[-4].minor.yy258);}
113214        break;
113215      case 290: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
113216{yygotominor.yy327 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy180, 0, yymsp[0].minor.yy159, yymsp[-4].minor.yy258);}
113217        break;
113218      case 291: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
113219{yygotominor.yy327 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy122);}
113220        break;
113221      case 292: /* trigger_cmd ::= select */
113222{yygotominor.yy327 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy159); }
113223        break;
113224      case 293: /* expr ::= RAISE LP IGNORE RP */
113225{
113226  yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
113227  if( yygotominor.yy342.pExpr ){
113228    yygotominor.yy342.pExpr->affinity = OE_Ignore;
113229  }
113230  yygotominor.yy342.zStart = yymsp[-3].minor.yy0.z;
113231  yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
113232}
113233        break;
113234      case 294: /* expr ::= RAISE LP raisetype COMMA nm RP */
113235{
113236  yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
113237  if( yygotominor.yy342.pExpr ) {
113238    yygotominor.yy342.pExpr->affinity = (char)yymsp[-3].minor.yy392;
113239  }
113240  yygotominor.yy342.zStart = yymsp[-5].minor.yy0.z;
113241  yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
113242}
113243        break;
113244      case 295: /* raisetype ::= ROLLBACK */
113245{yygotominor.yy392 = OE_Rollback;}
113246        break;
113247      case 297: /* raisetype ::= FAIL */
113248{yygotominor.yy392 = OE_Fail;}
113249        break;
113250      case 298: /* cmd ::= DROP TRIGGER ifexists fullname */
113251{
113252  sqlite3DropTrigger(pParse,yymsp[0].minor.yy347,yymsp[-1].minor.yy392);
113253}
113254        break;
113255      case 299: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
113256{
113257  sqlite3Attach(pParse, yymsp[-3].minor.yy342.pExpr, yymsp[-1].minor.yy342.pExpr, yymsp[0].minor.yy122);
113258}
113259        break;
113260      case 300: /* cmd ::= DETACH database_kw_opt expr */
113261{
113262  sqlite3Detach(pParse, yymsp[0].minor.yy342.pExpr);
113263}
113264        break;
113265      case 305: /* cmd ::= REINDEX */
113266{sqlite3Reindex(pParse, 0, 0);}
113267        break;
113268      case 306: /* cmd ::= REINDEX nm dbnm */
113269{sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
113270        break;
113271      case 307: /* cmd ::= ANALYZE */
113272{sqlite3Analyze(pParse, 0, 0);}
113273        break;
113274      case 308: /* cmd ::= ANALYZE nm dbnm */
113275{sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
113276        break;
113277      case 309: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
113278{
113279  sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy347,&yymsp[0].minor.yy0);
113280}
113281        break;
113282      case 310: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
113283{
113284  sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
113285}
113286        break;
113287      case 311: /* add_column_fullname ::= fullname */
113288{
113289  pParse->db->lookaside.bEnabled = 0;
113290  sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy347);
113291}
113292        break;
113293      case 314: /* cmd ::= create_vtab */
113294{sqlite3VtabFinishParse(pParse,0);}
113295        break;
113296      case 315: /* cmd ::= create_vtab LP vtabarglist RP */
113297{sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
113298        break;
113299      case 316: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
113300{
113301    sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy392);
113302}
113303        break;
113304      case 319: /* vtabarg ::= */
113305{sqlite3VtabArgInit(pParse);}
113306        break;
113307      case 321: /* vtabargtoken ::= ANY */
113308      case 322: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==322);
113309      case 323: /* lp ::= LP */ yytestcase(yyruleno==323);
113310{sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
113311        break;
113312      default:
113313      /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
113314      /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
113315      /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
113316      /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
113317      /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
113318      /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
113319      /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
113320      /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
113321      /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
113322      /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
113323      /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
113324      /* (34) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==34);
113325      /* (35) columnlist ::= column */ yytestcase(yyruleno==35);
113326      /* (44) type ::= */ yytestcase(yyruleno==44);
113327      /* (51) signed ::= plus_num */ yytestcase(yyruleno==51);
113328      /* (52) signed ::= minus_num */ yytestcase(yyruleno==52);
113329      /* (53) carglist ::= carglist ccons */ yytestcase(yyruleno==53);
113330      /* (54) carglist ::= */ yytestcase(yyruleno==54);
113331      /* (61) ccons ::= NULL onconf */ yytestcase(yyruleno==61);
113332      /* (89) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==89);
113333      /* (90) conslist ::= tcons */ yytestcase(yyruleno==90);
113334      /* (92) tconscomma ::= */ yytestcase(yyruleno==92);
113335      /* (277) foreach_clause ::= */ yytestcase(yyruleno==277);
113336      /* (278) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==278);
113337      /* (285) tridxby ::= */ yytestcase(yyruleno==285);
113338      /* (303) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==303);
113339      /* (304) database_kw_opt ::= */ yytestcase(yyruleno==304);
113340      /* (312) kwcolumn_opt ::= */ yytestcase(yyruleno==312);
113341      /* (313) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==313);
113342      /* (317) vtabarglist ::= vtabarg */ yytestcase(yyruleno==317);
113343      /* (318) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==318);
113344      /* (320) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==320);
113345      /* (324) anylist ::= */ yytestcase(yyruleno==324);
113346      /* (325) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==325);
113347      /* (326) anylist ::= anylist ANY */ yytestcase(yyruleno==326);
113348        break;
113349  };
113350  assert( yyruleno>=0 && yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) );
113351  yygoto = yyRuleInfo[yyruleno].lhs;
113352  yysize = yyRuleInfo[yyruleno].nrhs;
113353  yypParser->yyidx -= yysize;
113354  yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
113355  if( yyact < YYNSTATE ){
113356#ifdef NDEBUG
113357    /* If we are not debugging and the reduce action popped at least
113358    ** one element off the stack, then we can push the new element back
113359    ** onto the stack here, and skip the stack overflow test in yy_shift().
113360    ** That gives a significant speed improvement. */
113361    if( yysize ){
113362      yypParser->yyidx++;
113363      yymsp -= yysize-1;
113364      yymsp->stateno = (YYACTIONTYPE)yyact;
113365      yymsp->major = (YYCODETYPE)yygoto;
113366      yymsp->minor = yygotominor;
113367    }else
113368#endif
113369    {
113370      yy_shift(yypParser,yyact,yygoto,&yygotominor);
113371    }
113372  }else{
113373    assert( yyact == YYNSTATE + YYNRULE + 1 );
113374    yy_accept(yypParser);
113375  }
113376}
113377
113378/*
113379** The following code executes when the parse fails
113380*/
113381#ifndef YYNOERRORRECOVERY
113382static void yy_parse_failed(
113383  yyParser *yypParser           /* The parser */
113384){
113385  sqlite3ParserARG_FETCH;
113386#ifndef NDEBUG
113387  if( yyTraceFILE ){
113388    fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
113389  }
113390#endif
113391  while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
113392  /* Here code is inserted which will be executed whenever the
113393  ** parser fails */
113394  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
113395}
113396#endif /* YYNOERRORRECOVERY */
113397
113398/*
113399** The following code executes when a syntax error first occurs.
113400*/
113401static void yy_syntax_error(
113402  yyParser *yypParser,           /* The parser */
113403  int yymajor,                   /* The major type of the error token */
113404  YYMINORTYPE yyminor            /* The minor type of the error token */
113405){
113406  sqlite3ParserARG_FETCH;
113407#define TOKEN (yyminor.yy0)
113408
113409  UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
113410  assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
113411  sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
113412  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
113413}
113414
113415/*
113416** The following is executed when the parser accepts
113417*/
113418static void yy_accept(
113419  yyParser *yypParser           /* The parser */
113420){
113421  sqlite3ParserARG_FETCH;
113422#ifndef NDEBUG
113423  if( yyTraceFILE ){
113424    fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
113425  }
113426#endif
113427  while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
113428  /* Here code is inserted which will be executed whenever the
113429  ** parser accepts */
113430  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
113431}
113432
113433/* The main parser program.
113434** The first argument is a pointer to a structure obtained from
113435** "sqlite3ParserAlloc" which describes the current state of the parser.
113436** The second argument is the major token number.  The third is
113437** the minor token.  The fourth optional argument is whatever the
113438** user wants (and specified in the grammar) and is available for
113439** use by the action routines.
113440**
113441** Inputs:
113442** <ul>
113443** <li> A pointer to the parser (an opaque structure.)
113444** <li> The major token number.
113445** <li> The minor token number.
113446** <li> An option argument of a grammar-specified type.
113447** </ul>
113448**
113449** Outputs:
113450** None.
113451*/
113452SQLITE_PRIVATE void sqlite3Parser(
113453  void *yyp,                   /* The parser */
113454  int yymajor,                 /* The major token code number */
113455  sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
113456  sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
113457){
113458  YYMINORTYPE yyminorunion;
113459  int yyact;            /* The parser action. */
113460#if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
113461  int yyendofinput;     /* True if we are at the end of input */
113462#endif
113463#ifdef YYERRORSYMBOL
113464  int yyerrorhit = 0;   /* True if yymajor has invoked an error */
113465#endif
113466  yyParser *yypParser;  /* The parser */
113467
113468  /* (re)initialize the parser, if necessary */
113469  yypParser = (yyParser*)yyp;
113470  if( yypParser->yyidx<0 ){
113471#if YYSTACKDEPTH<=0
113472    if( yypParser->yystksz <=0 ){
113473      /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
113474      yyminorunion = yyzerominor;
113475      yyStackOverflow(yypParser, &yyminorunion);
113476      return;
113477    }
113478#endif
113479    yypParser->yyidx = 0;
113480    yypParser->yyerrcnt = -1;
113481    yypParser->yystack[0].stateno = 0;
113482    yypParser->yystack[0].major = 0;
113483  }
113484  yyminorunion.yy0 = yyminor;
113485#if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
113486  yyendofinput = (yymajor==0);
113487#endif
113488  sqlite3ParserARG_STORE;
113489
113490#ifndef NDEBUG
113491  if( yyTraceFILE ){
113492    fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
113493  }
113494#endif
113495
113496  do{
113497    yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
113498    if( yyact<YYNSTATE ){
113499      yy_shift(yypParser,yyact,yymajor,&yyminorunion);
113500      yypParser->yyerrcnt--;
113501      yymajor = YYNOCODE;
113502    }else if( yyact < YYNSTATE + YYNRULE ){
113503      yy_reduce(yypParser,yyact-YYNSTATE);
113504    }else{
113505      assert( yyact == YY_ERROR_ACTION );
113506#ifdef YYERRORSYMBOL
113507      int yymx;
113508#endif
113509#ifndef NDEBUG
113510      if( yyTraceFILE ){
113511        fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
113512      }
113513#endif
113514#ifdef YYERRORSYMBOL
113515      /* A syntax error has occurred.
113516      ** The response to an error depends upon whether or not the
113517      ** grammar defines an error token "ERROR".
113518      **
113519      ** This is what we do if the grammar does define ERROR:
113520      **
113521      **  * Call the %syntax_error function.
113522      **
113523      **  * Begin popping the stack until we enter a state where
113524      **    it is legal to shift the error symbol, then shift
113525      **    the error symbol.
113526      **
113527      **  * Set the error count to three.
113528      **
113529      **  * Begin accepting and shifting new tokens.  No new error
113530      **    processing will occur until three tokens have been
113531      **    shifted successfully.
113532      **
113533      */
113534      if( yypParser->yyerrcnt<0 ){
113535        yy_syntax_error(yypParser,yymajor,yyminorunion);
113536      }
113537      yymx = yypParser->yystack[yypParser->yyidx].major;
113538      if( yymx==YYERRORSYMBOL || yyerrorhit ){
113539#ifndef NDEBUG
113540        if( yyTraceFILE ){
113541          fprintf(yyTraceFILE,"%sDiscard input token %s\n",
113542             yyTracePrompt,yyTokenName[yymajor]);
113543        }
113544#endif
113545        yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
113546        yymajor = YYNOCODE;
113547      }else{
113548         while(
113549          yypParser->yyidx >= 0 &&
113550          yymx != YYERRORSYMBOL &&
113551          (yyact = yy_find_reduce_action(
113552                        yypParser->yystack[yypParser->yyidx].stateno,
113553                        YYERRORSYMBOL)) >= YYNSTATE
113554        ){
113555          yy_pop_parser_stack(yypParser);
113556        }
113557        if( yypParser->yyidx < 0 || yymajor==0 ){
113558          yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
113559          yy_parse_failed(yypParser);
113560          yymajor = YYNOCODE;
113561        }else if( yymx!=YYERRORSYMBOL ){
113562          YYMINORTYPE u2;
113563          u2.YYERRSYMDT = 0;
113564          yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
113565        }
113566      }
113567      yypParser->yyerrcnt = 3;
113568      yyerrorhit = 1;
113569#elif defined(YYNOERRORRECOVERY)
113570      /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
113571      ** do any kind of error recovery.  Instead, simply invoke the syntax
113572      ** error routine and continue going as if nothing had happened.
113573      **
113574      ** Applications can set this macro (for example inside %include) if
113575      ** they intend to abandon the parse upon the first syntax error seen.
113576      */
113577      yy_syntax_error(yypParser,yymajor,yyminorunion);
113578      yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
113579      yymajor = YYNOCODE;
113580
113581#else  /* YYERRORSYMBOL is not defined */
113582      /* This is what we do if the grammar does not define ERROR:
113583      **
113584      **  * Report an error message, and throw away the input token.
113585      **
113586      **  * If the input token is $, then fail the parse.
113587      **
113588      ** As before, subsequent error messages are suppressed until
113589      ** three input tokens have been successfully shifted.
113590      */
113591      if( yypParser->yyerrcnt<=0 ){
113592        yy_syntax_error(yypParser,yymajor,yyminorunion);
113593      }
113594      yypParser->yyerrcnt = 3;
113595      yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
113596      if( yyendofinput ){
113597        yy_parse_failed(yypParser);
113598      }
113599      yymajor = YYNOCODE;
113600#endif
113601    }
113602  }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
113603  return;
113604}
113605
113606/************** End of parse.c ***********************************************/
113607/************** Begin file tokenize.c ****************************************/
113608/*
113609** 2001 September 15
113610**
113611** The author disclaims copyright to this source code.  In place of
113612** a legal notice, here is a blessing:
113613**
113614**    May you do good and not evil.
113615**    May you find forgiveness for yourself and forgive others.
113616**    May you share freely, never taking more than you give.
113617**
113618*************************************************************************
113619** An tokenizer for SQL
113620**
113621** This file contains C code that splits an SQL input string up into
113622** individual tokens and sends those tokens one-by-one over to the
113623** parser for analysis.
113624*/
113625/* #include <stdlib.h> */
113626
113627/*
113628** The charMap() macro maps alphabetic characters into their
113629** lower-case ASCII equivalent.  On ASCII machines, this is just
113630** an upper-to-lower case map.  On EBCDIC machines we also need
113631** to adjust the encoding.  Only alphabetic characters and underscores
113632** need to be translated.
113633*/
113634#ifdef SQLITE_ASCII
113635# define charMap(X) sqlite3UpperToLower[(unsigned char)X]
113636#endif
113637#ifdef SQLITE_EBCDIC
113638# define charMap(X) ebcdicToAscii[(unsigned char)X]
113639const unsigned char ebcdicToAscii[] = {
113640/* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
113641   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
113642   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
113643   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
113644   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
113645   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
113646   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
113647   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
113648   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
113649   0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
113650   0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
113651   0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
113652   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
113653   0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
113654   0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
113655   0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
113656   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
113657};
113658#endif
113659
113660/*
113661** The sqlite3KeywordCode function looks up an identifier to determine if
113662** it is a keyword.  If it is a keyword, the token code of that keyword is
113663** returned.  If the input is not a keyword, TK_ID is returned.
113664**
113665** The implementation of this routine was generated by a program,
113666** mkkeywordhash.h, located in the tool subdirectory of the distribution.
113667** The output of the mkkeywordhash.c program is written into a file
113668** named keywordhash.h and then included into this source file by
113669** the #include below.
113670*/
113671/************** Include keywordhash.h in the middle of tokenize.c ************/
113672/************** Begin file keywordhash.h *************************************/
113673/***** This file contains automatically generated code ******
113674**
113675** The code in this file has been automatically generated by
113676**
113677**   sqlite/tool/mkkeywordhash.c
113678**
113679** The code in this file implements a function that determines whether
113680** or not a given identifier is really an SQL keyword.  The same thing
113681** might be implemented more directly using a hand-written hash table.
113682** But by using this automatically generated code, the size of the code
113683** is substantially reduced.  This is important for embedded applications
113684** on platforms with limited memory.
113685*/
113686/* Hash score: 175 */
113687static int keywordCode(const char *z, int n){
113688  /* zText[] encodes 811 bytes of keywords in 541 bytes */
113689  /*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */
113690  /*   ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE         */
113691  /*   XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY         */
113692  /*   UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE          */
113693  /*   CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN        */
113694  /*   SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME         */
113695  /*   AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS     */
113696  /*   CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF      */
113697  /*   ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW         */
113698  /*   INITIALLY                                                          */
113699  static const char zText[540] = {
113700    'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
113701    'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
113702    'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
113703    'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
113704    'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
113705    'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
113706    'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
113707    'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
113708    'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
113709    'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
113710    'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U',
113711    'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S',
113712    'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C',
113713    'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L',
113714    'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D',
113715    'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E',
113716    'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A',
113717    'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',
113718    'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W',
113719    'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C',
113720    'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R',
113721    'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M',
113722    'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U',
113723    'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M',
113724    'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T',
113725    'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L',
113726    'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S',
113727    'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L',
113728    'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V',
113729    'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y',
113730  };
113731  static const unsigned char aHash[127] = {
113732      72, 101, 114,  70,   0,  45,   0,   0,  78,   0,  73,   0,   0,
113733      42,  12,  74,  15,   0, 113,  81,  50, 108,   0,  19,   0,   0,
113734     118,   0, 116, 111,   0,  22,  89,   0,   9,   0,   0,  66,  67,
113735       0,  65,   6,   0,  48,  86,  98,   0, 115,  97,   0,   0,  44,
113736       0,  99,  24,   0,  17,   0, 119,  49,  23,   0,   5, 106,  25,
113737      92,   0,   0, 121, 102,  56, 120,  53,  28,  51,   0,  87,   0,
113738      96,  26,   0,  95,   0,   0,   0,  91,  88,  93,  84, 105,  14,
113739      39, 104,   0,  77,   0,  18,  85, 107,  32,   0, 117,  76, 109,
113740      58,  46,  80,   0,   0,  90,  40,   0, 112,   0,  36,   0,   0,
113741      29,   0,  82,  59,  60,   0,  20,  57,   0,  52,
113742  };
113743  static const unsigned char aNext[121] = {
113744       0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
113745       0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
113746       0,   7,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
113747       0,   0,   0,   0,  33,   0,  21,   0,   0,   0,  43,   3,  47,
113748       0,   0,   0,   0,  30,   0,  54,   0,  38,   0,   0,   0,   1,
113749      62,   0,   0,  63,   0,  41,   0,   0,   0,   0,   0,   0,   0,
113750      61,   0,   0,   0,   0,  31,  55,  16,  34,  10,   0,   0,   0,
113751       0,   0,   0,   0,  11,  68,  75,   0,   8,   0, 100,  94,   0,
113752     103,   0,  83,   0,  71,   0,   0, 110,  27,  37,  69,  79,   0,
113753      35,  64,   0,   0,
113754  };
113755  static const unsigned char aLen[121] = {
113756       7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
113757       7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,
113758      11,   6,   2,   7,   5,   5,   9,   6,   9,   9,   7,  10,  10,
113759       4,   6,   2,   3,   9,   4,   2,   6,   5,   6,   6,   5,   6,
113760       5,   5,   7,   7,   7,   3,   2,   4,   4,   7,   3,   6,   4,
113761       7,   6,  12,   6,   9,   4,   6,   5,   4,   7,   6,   5,   6,
113762       7,   5,   4,   5,   6,   5,   7,   3,   7,  13,   2,   2,   4,
113763       6,   6,   8,   5,  17,  12,   7,   8,   8,   2,   4,   4,   4,
113764       4,   4,   2,   2,   6,   5,   8,   5,   5,   8,   3,   5,   5,
113765       6,   4,   9,   3,
113766  };
113767  static const unsigned short int aOffset[121] = {
113768       0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
113769      36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
113770      86,  91,  95,  96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
113771     159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197,
113772     203, 206, 210, 217, 223, 223, 223, 226, 229, 233, 234, 238, 244,
113773     248, 255, 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320,
113774     326, 332, 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383,
113775     387, 393, 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458,
113776     462, 466, 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516,
113777     521, 527, 531, 536,
113778  };
113779  static const unsigned char aCode[121] = {
113780    TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,
113781    TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,
113782    TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,
113783    TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,
113784    TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,
113785    TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,
113786    TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,
113787    TK_INTERSECT,  TK_TRIGGER,    TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
113788    TK_OFFSET,     TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,
113789    TK_OR,         TK_UNIQUE,     TK_QUERY,      TK_ATTACH,     TK_HAVING,
113790    TK_GROUP,      TK_UPDATE,     TK_BEGIN,      TK_JOIN_KW,    TK_RELEASE,
113791    TK_BETWEEN,    TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,
113792    TK_LIKE_KW,    TK_CASCADE,    TK_ASC,        TK_DELETE,     TK_CASE,
113793    TK_COLLATE,    TK_CREATE,     TK_CTIME_KW,   TK_DETACH,     TK_IMMEDIATE,
113794    TK_JOIN,       TK_INSERT,     TK_MATCH,      TK_PLAN,       TK_ANALYZE,
113795    TK_PRAGMA,     TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,
113796    TK_WHEN,       TK_WHERE,      TK_RENAME,     TK_AFTER,      TK_REPLACE,
113797    TK_AND,        TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         TK_IN,
113798    TK_CAST,       TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,
113799    TK_CTIME_KW,   TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   TK_DISTINCT,
113800    TK_IS,         TK_DROP,       TK_FAIL,       TK_FROM,       TK_JOIN_KW,
113801    TK_LIKE_KW,    TK_BY,         TK_IF,         TK_ISNULL,     TK_ORDER,
113802    TK_RESTRICT,   TK_JOIN_KW,    TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,
113803    TK_UNION,      TK_USING,      TK_VACUUM,     TK_VIEW,       TK_INITIALLY,
113804    TK_ALL,
113805  };
113806  int h, i;
113807  if( n<2 ) return TK_ID;
113808  h = ((charMap(z[0])*4) ^
113809      (charMap(z[n-1])*3) ^
113810      n) % 127;
113811  for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
113812    if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
113813      testcase( i==0 ); /* REINDEX */
113814      testcase( i==1 ); /* INDEXED */
113815      testcase( i==2 ); /* INDEX */
113816      testcase( i==3 ); /* DESC */
113817      testcase( i==4 ); /* ESCAPE */
113818      testcase( i==5 ); /* EACH */
113819      testcase( i==6 ); /* CHECK */
113820      testcase( i==7 ); /* KEY */
113821      testcase( i==8 ); /* BEFORE */
113822      testcase( i==9 ); /* FOREIGN */
113823      testcase( i==10 ); /* FOR */
113824      testcase( i==11 ); /* IGNORE */
113825      testcase( i==12 ); /* REGEXP */
113826      testcase( i==13 ); /* EXPLAIN */
113827      testcase( i==14 ); /* INSTEAD */
113828      testcase( i==15 ); /* ADD */
113829      testcase( i==16 ); /* DATABASE */
113830      testcase( i==17 ); /* AS */
113831      testcase( i==18 ); /* SELECT */
113832      testcase( i==19 ); /* TABLE */
113833      testcase( i==20 ); /* LEFT */
113834      testcase( i==21 ); /* THEN */
113835      testcase( i==22 ); /* END */
113836      testcase( i==23 ); /* DEFERRABLE */
113837      testcase( i==24 ); /* ELSE */
113838      testcase( i==25 ); /* EXCEPT */
113839      testcase( i==26 ); /* TRANSACTION */
113840      testcase( i==27 ); /* ACTION */
113841      testcase( i==28 ); /* ON */
113842      testcase( i==29 ); /* NATURAL */
113843      testcase( i==30 ); /* ALTER */
113844      testcase( i==31 ); /* RAISE */
113845      testcase( i==32 ); /* EXCLUSIVE */
113846      testcase( i==33 ); /* EXISTS */
113847      testcase( i==34 ); /* SAVEPOINT */
113848      testcase( i==35 ); /* INTERSECT */
113849      testcase( i==36 ); /* TRIGGER */
113850      testcase( i==37 ); /* REFERENCES */
113851      testcase( i==38 ); /* CONSTRAINT */
113852      testcase( i==39 ); /* INTO */
113853      testcase( i==40 ); /* OFFSET */
113854      testcase( i==41 ); /* OF */
113855      testcase( i==42 ); /* SET */
113856      testcase( i==43 ); /* TEMPORARY */
113857      testcase( i==44 ); /* TEMP */
113858      testcase( i==45 ); /* OR */
113859      testcase( i==46 ); /* UNIQUE */
113860      testcase( i==47 ); /* QUERY */
113861      testcase( i==48 ); /* ATTACH */
113862      testcase( i==49 ); /* HAVING */
113863      testcase( i==50 ); /* GROUP */
113864      testcase( i==51 ); /* UPDATE */
113865      testcase( i==52 ); /* BEGIN */
113866      testcase( i==53 ); /* INNER */
113867      testcase( i==54 ); /* RELEASE */
113868      testcase( i==55 ); /* BETWEEN */
113869      testcase( i==56 ); /* NOTNULL */
113870      testcase( i==57 ); /* NOT */
113871      testcase( i==58 ); /* NO */
113872      testcase( i==59 ); /* NULL */
113873      testcase( i==60 ); /* LIKE */
113874      testcase( i==61 ); /* CASCADE */
113875      testcase( i==62 ); /* ASC */
113876      testcase( i==63 ); /* DELETE */
113877      testcase( i==64 ); /* CASE */
113878      testcase( i==65 ); /* COLLATE */
113879      testcase( i==66 ); /* CREATE */
113880      testcase( i==67 ); /* CURRENT_DATE */
113881      testcase( i==68 ); /* DETACH */
113882      testcase( i==69 ); /* IMMEDIATE */
113883      testcase( i==70 ); /* JOIN */
113884      testcase( i==71 ); /* INSERT */
113885      testcase( i==72 ); /* MATCH */
113886      testcase( i==73 ); /* PLAN */
113887      testcase( i==74 ); /* ANALYZE */
113888      testcase( i==75 ); /* PRAGMA */
113889      testcase( i==76 ); /* ABORT */
113890      testcase( i==77 ); /* VALUES */
113891      testcase( i==78 ); /* VIRTUAL */
113892      testcase( i==79 ); /* LIMIT */
113893      testcase( i==80 ); /* WHEN */
113894      testcase( i==81 ); /* WHERE */
113895      testcase( i==82 ); /* RENAME */
113896      testcase( i==83 ); /* AFTER */
113897      testcase( i==84 ); /* REPLACE */
113898      testcase( i==85 ); /* AND */
113899      testcase( i==86 ); /* DEFAULT */
113900      testcase( i==87 ); /* AUTOINCREMENT */
113901      testcase( i==88 ); /* TO */
113902      testcase( i==89 ); /* IN */
113903      testcase( i==90 ); /* CAST */
113904      testcase( i==91 ); /* COLUMN */
113905      testcase( i==92 ); /* COMMIT */
113906      testcase( i==93 ); /* CONFLICT */
113907      testcase( i==94 ); /* CROSS */
113908      testcase( i==95 ); /* CURRENT_TIMESTAMP */
113909      testcase( i==96 ); /* CURRENT_TIME */
113910      testcase( i==97 ); /* PRIMARY */
113911      testcase( i==98 ); /* DEFERRED */
113912      testcase( i==99 ); /* DISTINCT */
113913      testcase( i==100 ); /* IS */
113914      testcase( i==101 ); /* DROP */
113915      testcase( i==102 ); /* FAIL */
113916      testcase( i==103 ); /* FROM */
113917      testcase( i==104 ); /* FULL */
113918      testcase( i==105 ); /* GLOB */
113919      testcase( i==106 ); /* BY */
113920      testcase( i==107 ); /* IF */
113921      testcase( i==108 ); /* ISNULL */
113922      testcase( i==109 ); /* ORDER */
113923      testcase( i==110 ); /* RESTRICT */
113924      testcase( i==111 ); /* OUTER */
113925      testcase( i==112 ); /* RIGHT */
113926      testcase( i==113 ); /* ROLLBACK */
113927      testcase( i==114 ); /* ROW */
113928      testcase( i==115 ); /* UNION */
113929      testcase( i==116 ); /* USING */
113930      testcase( i==117 ); /* VACUUM */
113931      testcase( i==118 ); /* VIEW */
113932      testcase( i==119 ); /* INITIALLY */
113933      testcase( i==120 ); /* ALL */
113934      return aCode[i];
113935    }
113936  }
113937  return TK_ID;
113938}
113939SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
113940  return keywordCode((char*)z, n);
113941}
113942#define SQLITE_N_KEYWORD 121
113943
113944/************** End of keywordhash.h *****************************************/
113945/************** Continuing where we left off in tokenize.c *******************/
113946
113947
113948/*
113949** If X is a character that can be used in an identifier then
113950** IdChar(X) will be true.  Otherwise it is false.
113951**
113952** For ASCII, any character with the high-order bit set is
113953** allowed in an identifier.  For 7-bit characters,
113954** sqlite3IsIdChar[X] must be 1.
113955**
113956** For EBCDIC, the rules are more complex but have the same
113957** end result.
113958**
113959** Ticket #1066.  the SQL standard does not allow '$' in the
113960** middle of identfiers.  But many SQL implementations do.
113961** SQLite will allow '$' in identifiers for compatibility.
113962** But the feature is undocumented.
113963*/
113964#ifdef SQLITE_ASCII
113965#define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
113966#endif
113967#ifdef SQLITE_EBCDIC
113968SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
113969/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
113970    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
113971    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
113972    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
113973    0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
113974    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
113975    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
113976    1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
113977    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
113978    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
113979    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
113980    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
113981    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
113982};
113983#define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
113984#endif
113985
113986
113987/*
113988** Return the length of the token that begins at z[0].
113989** Store the token type in *tokenType before returning.
113990*/
113991SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
113992  int i, c;
113993  switch( *z ){
113994    case ' ': case '\t': case '\n': case '\f': case '\r': {
113995      testcase( z[0]==' ' );
113996      testcase( z[0]=='\t' );
113997      testcase( z[0]=='\n' );
113998      testcase( z[0]=='\f' );
113999      testcase( z[0]=='\r' );
114000      for(i=1; sqlite3Isspace(z[i]); i++){}
114001      *tokenType = TK_SPACE;
114002      return i;
114003    }
114004    case '-': {
114005      if( z[1]=='-' ){
114006        /* IMP: R-50417-27976 -- syntax diagram for comments */
114007        for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
114008        *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
114009        return i;
114010      }
114011      *tokenType = TK_MINUS;
114012      return 1;
114013    }
114014    case '(': {
114015      *tokenType = TK_LP;
114016      return 1;
114017    }
114018    case ')': {
114019      *tokenType = TK_RP;
114020      return 1;
114021    }
114022    case ';': {
114023      *tokenType = TK_SEMI;
114024      return 1;
114025    }
114026    case '+': {
114027      *tokenType = TK_PLUS;
114028      return 1;
114029    }
114030    case '*': {
114031      *tokenType = TK_STAR;
114032      return 1;
114033    }
114034    case '/': {
114035      if( z[1]!='*' || z[2]==0 ){
114036        *tokenType = TK_SLASH;
114037        return 1;
114038      }
114039      /* IMP: R-50417-27976 -- syntax diagram for comments */
114040      for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
114041      if( c ) i++;
114042      *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
114043      return i;
114044    }
114045    case '%': {
114046      *tokenType = TK_REM;
114047      return 1;
114048    }
114049    case '=': {
114050      *tokenType = TK_EQ;
114051      return 1 + (z[1]=='=');
114052    }
114053    case '<': {
114054      if( (c=z[1])=='=' ){
114055        *tokenType = TK_LE;
114056        return 2;
114057      }else if( c=='>' ){
114058        *tokenType = TK_NE;
114059        return 2;
114060      }else if( c=='<' ){
114061        *tokenType = TK_LSHIFT;
114062        return 2;
114063      }else{
114064        *tokenType = TK_LT;
114065        return 1;
114066      }
114067    }
114068    case '>': {
114069      if( (c=z[1])=='=' ){
114070        *tokenType = TK_GE;
114071        return 2;
114072      }else if( c=='>' ){
114073        *tokenType = TK_RSHIFT;
114074        return 2;
114075      }else{
114076        *tokenType = TK_GT;
114077        return 1;
114078      }
114079    }
114080    case '!': {
114081      if( z[1]!='=' ){
114082        *tokenType = TK_ILLEGAL;
114083        return 2;
114084      }else{
114085        *tokenType = TK_NE;
114086        return 2;
114087      }
114088    }
114089    case '|': {
114090      if( z[1]!='|' ){
114091        *tokenType = TK_BITOR;
114092        return 1;
114093      }else{
114094        *tokenType = TK_CONCAT;
114095        return 2;
114096      }
114097    }
114098    case ',': {
114099      *tokenType = TK_COMMA;
114100      return 1;
114101    }
114102    case '&': {
114103      *tokenType = TK_BITAND;
114104      return 1;
114105    }
114106    case '~': {
114107      *tokenType = TK_BITNOT;
114108      return 1;
114109    }
114110    case '`':
114111    case '\'':
114112    case '"': {
114113      int delim = z[0];
114114      testcase( delim=='`' );
114115      testcase( delim=='\'' );
114116      testcase( delim=='"' );
114117      for(i=1; (c=z[i])!=0; i++){
114118        if( c==delim ){
114119          if( z[i+1]==delim ){
114120            i++;
114121          }else{
114122            break;
114123          }
114124        }
114125      }
114126      if( c=='\'' ){
114127        *tokenType = TK_STRING;
114128        return i+1;
114129      }else if( c!=0 ){
114130        *tokenType = TK_ID;
114131        return i+1;
114132      }else{
114133        *tokenType = TK_ILLEGAL;
114134        return i;
114135      }
114136    }
114137    case '.': {
114138#ifndef SQLITE_OMIT_FLOATING_POINT
114139      if( !sqlite3Isdigit(z[1]) )
114140#endif
114141      {
114142        *tokenType = TK_DOT;
114143        return 1;
114144      }
114145      /* If the next character is a digit, this is a floating point
114146      ** number that begins with ".".  Fall thru into the next case */
114147    }
114148    case '0': case '1': case '2': case '3': case '4':
114149    case '5': case '6': case '7': case '8': case '9': {
114150      testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );
114151      testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );
114152      testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );
114153      testcase( z[0]=='9' );
114154      *tokenType = TK_INTEGER;
114155      for(i=0; sqlite3Isdigit(z[i]); i++){}
114156#ifndef SQLITE_OMIT_FLOATING_POINT
114157      if( z[i]=='.' ){
114158        i++;
114159        while( sqlite3Isdigit(z[i]) ){ i++; }
114160        *tokenType = TK_FLOAT;
114161      }
114162      if( (z[i]=='e' || z[i]=='E') &&
114163           ( sqlite3Isdigit(z[i+1])
114164            || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
114165           )
114166      ){
114167        i += 2;
114168        while( sqlite3Isdigit(z[i]) ){ i++; }
114169        *tokenType = TK_FLOAT;
114170      }
114171#endif
114172      while( IdChar(z[i]) ){
114173        *tokenType = TK_ILLEGAL;
114174        i++;
114175      }
114176      return i;
114177    }
114178    case '[': {
114179      for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
114180      *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
114181      return i;
114182    }
114183    case '?': {
114184      *tokenType = TK_VARIABLE;
114185      for(i=1; sqlite3Isdigit(z[i]); i++){}
114186      return i;
114187    }
114188    case '#': {
114189      for(i=1; sqlite3Isdigit(z[i]); i++){}
114190      if( i>1 ){
114191        /* Parameters of the form #NNN (where NNN is a number) are used
114192        ** internally by sqlite3NestedParse.  */
114193        *tokenType = TK_REGISTER;
114194        return i;
114195      }
114196      /* Fall through into the next case if the '#' is not followed by
114197      ** a digit. Try to match #AAAA where AAAA is a parameter name. */
114198    }
114199#ifndef SQLITE_OMIT_TCL_VARIABLE
114200    case '$':
114201#endif
114202    case '@':  /* For compatibility with MS SQL Server */
114203    case ':': {
114204      int n = 0;
114205      testcase( z[0]=='$' );  testcase( z[0]=='@' );  testcase( z[0]==':' );
114206      *tokenType = TK_VARIABLE;
114207      for(i=1; (c=z[i])!=0; i++){
114208        if( IdChar(c) ){
114209          n++;
114210#ifndef SQLITE_OMIT_TCL_VARIABLE
114211        }else if( c=='(' && n>0 ){
114212          do{
114213            i++;
114214          }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
114215          if( c==')' ){
114216            i++;
114217          }else{
114218            *tokenType = TK_ILLEGAL;
114219          }
114220          break;
114221        }else if( c==':' && z[i+1]==':' ){
114222          i++;
114223#endif
114224        }else{
114225          break;
114226        }
114227      }
114228      if( n==0 ) *tokenType = TK_ILLEGAL;
114229      return i;
114230    }
114231#ifndef SQLITE_OMIT_BLOB_LITERAL
114232    case 'x': case 'X': {
114233      testcase( z[0]=='x' ); testcase( z[0]=='X' );
114234      if( z[1]=='\'' ){
114235        *tokenType = TK_BLOB;
114236        for(i=2; sqlite3Isxdigit(z[i]); i++){}
114237        if( z[i]!='\'' || i%2 ){
114238          *tokenType = TK_ILLEGAL;
114239          while( z[i] && z[i]!='\'' ){ i++; }
114240        }
114241        if( z[i] ) i++;
114242        return i;
114243      }
114244      /* Otherwise fall through to the next case */
114245    }
114246#endif
114247    default: {
114248      if( !IdChar(*z) ){
114249        break;
114250      }
114251      for(i=1; IdChar(z[i]); i++){}
114252      *tokenType = keywordCode((char*)z, i);
114253      return i;
114254    }
114255  }
114256  *tokenType = TK_ILLEGAL;
114257  return 1;
114258}
114259
114260/*
114261** Run the parser on the given SQL string.  The parser structure is
114262** passed in.  An SQLITE_ status code is returned.  If an error occurs
114263** then an and attempt is made to write an error message into
114264** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
114265** error message.
114266*/
114267SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
114268  int nErr = 0;                   /* Number of errors encountered */
114269  int i;                          /* Loop counter */
114270  void *pEngine;                  /* The LEMON-generated LALR(1) parser */
114271  int tokenType;                  /* type of the next token */
114272  int lastTokenParsed = -1;       /* type of the previous token */
114273  u8 enableLookaside;             /* Saved value of db->lookaside.bEnabled */
114274  sqlite3 *db = pParse->db;       /* The database connection */
114275  int mxSqlLen;                   /* Max length of an SQL string */
114276
114277
114278  mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
114279  if( db->activeVdbeCnt==0 ){
114280    db->u1.isInterrupted = 0;
114281  }
114282  pParse->rc = SQLITE_OK;
114283  pParse->zTail = zSql;
114284  i = 0;
114285  assert( pzErrMsg!=0 );
114286  pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
114287  if( pEngine==0 ){
114288    db->mallocFailed = 1;
114289    return SQLITE_NOMEM;
114290  }
114291  assert( pParse->pNewTable==0 );
114292  assert( pParse->pNewTrigger==0 );
114293  assert( pParse->nVar==0 );
114294  assert( pParse->nzVar==0 );
114295  assert( pParse->azVar==0 );
114296  enableLookaside = db->lookaside.bEnabled;
114297  if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
114298  while( !db->mallocFailed && zSql[i]!=0 ){
114299    assert( i>=0 );
114300    pParse->sLastToken.z = &zSql[i];
114301    pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
114302    i += pParse->sLastToken.n;
114303    if( i>mxSqlLen ){
114304      pParse->rc = SQLITE_TOOBIG;
114305      break;
114306    }
114307    switch( tokenType ){
114308      case TK_SPACE: {
114309        if( db->u1.isInterrupted ){
114310          sqlite3ErrorMsg(pParse, "interrupt");
114311          pParse->rc = SQLITE_INTERRUPT;
114312          goto abort_parse;
114313        }
114314        break;
114315      }
114316      case TK_ILLEGAL: {
114317        sqlite3DbFree(db, *pzErrMsg);
114318        *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
114319                        &pParse->sLastToken);
114320        nErr++;
114321        goto abort_parse;
114322      }
114323      case TK_SEMI: {
114324        pParse->zTail = &zSql[i];
114325        /* Fall thru into the default case */
114326      }
114327      default: {
114328        sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
114329        lastTokenParsed = tokenType;
114330        if( pParse->rc!=SQLITE_OK ){
114331          goto abort_parse;
114332        }
114333        break;
114334      }
114335    }
114336  }
114337abort_parse:
114338  if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
114339    if( lastTokenParsed!=TK_SEMI ){
114340      sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
114341      pParse->zTail = &zSql[i];
114342    }
114343    sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
114344  }
114345#ifdef YYTRACKMAXSTACKDEPTH
114346  sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
114347      sqlite3ParserStackPeak(pEngine)
114348  );
114349#endif /* YYDEBUG */
114350  sqlite3ParserFree(pEngine, sqlite3_free);
114351  db->lookaside.bEnabled = enableLookaside;
114352  if( db->mallocFailed ){
114353    pParse->rc = SQLITE_NOMEM;
114354  }
114355  if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
114356    sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
114357  }
114358  assert( pzErrMsg!=0 );
114359  if( pParse->zErrMsg ){
114360    *pzErrMsg = pParse->zErrMsg;
114361    sqlite3_log(pParse->rc, "%s", *pzErrMsg);
114362    pParse->zErrMsg = 0;
114363    nErr++;
114364  }
114365  if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
114366    sqlite3VdbeDelete(pParse->pVdbe);
114367    pParse->pVdbe = 0;
114368  }
114369#ifndef SQLITE_OMIT_SHARED_CACHE
114370  if( pParse->nested==0 ){
114371    sqlite3DbFree(db, pParse->aTableLock);
114372    pParse->aTableLock = 0;
114373    pParse->nTableLock = 0;
114374  }
114375#endif
114376#ifndef SQLITE_OMIT_VIRTUALTABLE
114377  sqlite3_free(pParse->apVtabLock);
114378#endif
114379
114380  if( !IN_DECLARE_VTAB ){
114381    /* If the pParse->declareVtab flag is set, do not delete any table
114382    ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
114383    ** will take responsibility for freeing the Table structure.
114384    */
114385    sqlite3DeleteTable(db, pParse->pNewTable);
114386  }
114387
114388  sqlite3DeleteTrigger(db, pParse->pNewTrigger);
114389  for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]);
114390  sqlite3DbFree(db, pParse->azVar);
114391  sqlite3DbFree(db, pParse->aAlias);
114392  while( pParse->pAinc ){
114393    AutoincInfo *p = pParse->pAinc;
114394    pParse->pAinc = p->pNext;
114395    sqlite3DbFree(db, p);
114396  }
114397  while( pParse->pZombieTab ){
114398    Table *p = pParse->pZombieTab;
114399    pParse->pZombieTab = p->pNextZombie;
114400    sqlite3DeleteTable(db, p);
114401  }
114402  if( nErr>0 && pParse->rc==SQLITE_OK ){
114403    pParse->rc = SQLITE_ERROR;
114404  }
114405  return nErr;
114406}
114407
114408/************** End of tokenize.c ********************************************/
114409/************** Begin file complete.c ****************************************/
114410/*
114411** 2001 September 15
114412**
114413** The author disclaims copyright to this source code.  In place of
114414** a legal notice, here is a blessing:
114415**
114416**    May you do good and not evil.
114417**    May you find forgiveness for yourself and forgive others.
114418**    May you share freely, never taking more than you give.
114419**
114420*************************************************************************
114421** An tokenizer for SQL
114422**
114423** This file contains C code that implements the sqlite3_complete() API.
114424** This code used to be part of the tokenizer.c source file.  But by
114425** separating it out, the code will be automatically omitted from
114426** static links that do not use it.
114427*/
114428#ifndef SQLITE_OMIT_COMPLETE
114429
114430/*
114431** This is defined in tokenize.c.  We just have to import the definition.
114432*/
114433#ifndef SQLITE_AMALGAMATION
114434#ifdef SQLITE_ASCII
114435#define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
114436#endif
114437#ifdef SQLITE_EBCDIC
114438SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
114439#define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
114440#endif
114441#endif /* SQLITE_AMALGAMATION */
114442
114443
114444/*
114445** Token types used by the sqlite3_complete() routine.  See the header
114446** comments on that procedure for additional information.
114447*/
114448#define tkSEMI    0
114449#define tkWS      1
114450#define tkOTHER   2
114451#ifndef SQLITE_OMIT_TRIGGER
114452#define tkEXPLAIN 3
114453#define tkCREATE  4
114454#define tkTEMP    5
114455#define tkTRIGGER 6
114456#define tkEND     7
114457#endif
114458
114459/*
114460** Return TRUE if the given SQL string ends in a semicolon.
114461**
114462** Special handling is require for CREATE TRIGGER statements.
114463** Whenever the CREATE TRIGGER keywords are seen, the statement
114464** must end with ";END;".
114465**
114466** This implementation uses a state machine with 8 states:
114467**
114468**   (0) INVALID   We have not yet seen a non-whitespace character.
114469**
114470**   (1) START     At the beginning or end of an SQL statement.  This routine
114471**                 returns 1 if it ends in the START state and 0 if it ends
114472**                 in any other state.
114473**
114474**   (2) NORMAL    We are in the middle of statement which ends with a single
114475**                 semicolon.
114476**
114477**   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of
114478**                 a statement.
114479**
114480**   (4) CREATE    The keyword CREATE has been seen at the beginning of a
114481**                 statement, possibly preceeded by EXPLAIN and/or followed by
114482**                 TEMP or TEMPORARY
114483**
114484**   (5) TRIGGER   We are in the middle of a trigger definition that must be
114485**                 ended by a semicolon, the keyword END, and another semicolon.
114486**
114487**   (6) SEMI      We've seen the first semicolon in the ";END;" that occurs at
114488**                 the end of a trigger definition.
114489**
114490**   (7) END       We've seen the ";END" of the ";END;" that occurs at the end
114491**                 of a trigger difinition.
114492**
114493** Transitions between states above are determined by tokens extracted
114494** from the input.  The following tokens are significant:
114495**
114496**   (0) tkSEMI      A semicolon.
114497**   (1) tkWS        Whitespace.
114498**   (2) tkOTHER     Any other SQL token.
114499**   (3) tkEXPLAIN   The "explain" keyword.
114500**   (4) tkCREATE    The "create" keyword.
114501**   (5) tkTEMP      The "temp" or "temporary" keyword.
114502**   (6) tkTRIGGER   The "trigger" keyword.
114503**   (7) tkEND       The "end" keyword.
114504**
114505** Whitespace never causes a state transition and is always ignored.
114506** This means that a SQL string of all whitespace is invalid.
114507**
114508** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
114509** to recognize the end of a trigger can be omitted.  All we have to do
114510** is look for a semicolon that is not part of an string or comment.
114511*/
114512SQLITE_API int sqlite3_complete(const char *zSql){
114513  u8 state = 0;   /* Current state, using numbers defined in header comment */
114514  u8 token;       /* Value of the next token */
114515
114516#ifndef SQLITE_OMIT_TRIGGER
114517  /* A complex statement machine used to detect the end of a CREATE TRIGGER
114518  ** statement.  This is the normal case.
114519  */
114520  static const u8 trans[8][8] = {
114521                     /* Token:                                                */
114522     /* State:       **  SEMI  WS  OTHER  EXPLAIN  CREATE  TEMP  TRIGGER  END */
114523     /* 0 INVALID: */ {    1,  0,     2,       3,      4,    2,       2,   2, },
114524     /* 1   START: */ {    1,  1,     2,       3,      4,    2,       2,   2, },
114525     /* 2  NORMAL: */ {    1,  2,     2,       2,      2,    2,       2,   2, },
114526     /* 3 EXPLAIN: */ {    1,  3,     3,       2,      4,    2,       2,   2, },
114527     /* 4  CREATE: */ {    1,  4,     2,       2,      2,    4,       5,   2, },
114528     /* 5 TRIGGER: */ {    6,  5,     5,       5,      5,    5,       5,   5, },
114529     /* 6    SEMI: */ {    6,  6,     5,       5,      5,    5,       5,   7, },
114530     /* 7     END: */ {    1,  7,     5,       5,      5,    5,       5,   5, },
114531  };
114532#else
114533  /* If triggers are not supported by this compile then the statement machine
114534  ** used to detect the end of a statement is much simplier
114535  */
114536  static const u8 trans[3][3] = {
114537                     /* Token:           */
114538     /* State:       **  SEMI  WS  OTHER */
114539     /* 0 INVALID: */ {    1,  0,     2, },
114540     /* 1   START: */ {    1,  1,     2, },
114541     /* 2  NORMAL: */ {    1,  2,     2, },
114542  };
114543#endif /* SQLITE_OMIT_TRIGGER */
114544
114545  while( *zSql ){
114546    switch( *zSql ){
114547      case ';': {  /* A semicolon */
114548        token = tkSEMI;
114549        break;
114550      }
114551      case ' ':
114552      case '\r':
114553      case '\t':
114554      case '\n':
114555      case '\f': {  /* White space is ignored */
114556        token = tkWS;
114557        break;
114558      }
114559      case '/': {   /* C-style comments */
114560        if( zSql[1]!='*' ){
114561          token = tkOTHER;
114562          break;
114563        }
114564        zSql += 2;
114565        while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
114566        if( zSql[0]==0 ) return 0;
114567        zSql++;
114568        token = tkWS;
114569        break;
114570      }
114571      case '-': {   /* SQL-style comments from "--" to end of line */
114572        if( zSql[1]!='-' ){
114573          token = tkOTHER;
114574          break;
114575        }
114576        while( *zSql && *zSql!='\n' ){ zSql++; }
114577        if( *zSql==0 ) return state==1;
114578        token = tkWS;
114579        break;
114580      }
114581      case '[': {   /* Microsoft-style identifiers in [...] */
114582        zSql++;
114583        while( *zSql && *zSql!=']' ){ zSql++; }
114584        if( *zSql==0 ) return 0;
114585        token = tkOTHER;
114586        break;
114587      }
114588      case '`':     /* Grave-accent quoted symbols used by MySQL */
114589      case '"':     /* single- and double-quoted strings */
114590      case '\'': {
114591        int c = *zSql;
114592        zSql++;
114593        while( *zSql && *zSql!=c ){ zSql++; }
114594        if( *zSql==0 ) return 0;
114595        token = tkOTHER;
114596        break;
114597      }
114598      default: {
114599#ifdef SQLITE_EBCDIC
114600        unsigned char c;
114601#endif
114602        if( IdChar((u8)*zSql) ){
114603          /* Keywords and unquoted identifiers */
114604          int nId;
114605          for(nId=1; IdChar(zSql[nId]); nId++){}
114606#ifdef SQLITE_OMIT_TRIGGER
114607          token = tkOTHER;
114608#else
114609          switch( *zSql ){
114610            case 'c': case 'C': {
114611              if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
114612                token = tkCREATE;
114613              }else{
114614                token = tkOTHER;
114615              }
114616              break;
114617            }
114618            case 't': case 'T': {
114619              if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
114620                token = tkTRIGGER;
114621              }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
114622                token = tkTEMP;
114623              }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
114624                token = tkTEMP;
114625              }else{
114626                token = tkOTHER;
114627              }
114628              break;
114629            }
114630            case 'e':  case 'E': {
114631              if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
114632                token = tkEND;
114633              }else
114634#ifndef SQLITE_OMIT_EXPLAIN
114635              if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
114636                token = tkEXPLAIN;
114637              }else
114638#endif
114639              {
114640                token = tkOTHER;
114641              }
114642              break;
114643            }
114644            default: {
114645              token = tkOTHER;
114646              break;
114647            }
114648          }
114649#endif /* SQLITE_OMIT_TRIGGER */
114650          zSql += nId-1;
114651        }else{
114652          /* Operators and special symbols */
114653          token = tkOTHER;
114654        }
114655        break;
114656      }
114657    }
114658    state = trans[state][token];
114659    zSql++;
114660  }
114661  return state==1;
114662}
114663
114664#ifndef SQLITE_OMIT_UTF16
114665/*
114666** This routine is the same as the sqlite3_complete() routine described
114667** above, except that the parameter is required to be UTF-16 encoded, not
114668** UTF-8.
114669*/
114670SQLITE_API int sqlite3_complete16(const void *zSql){
114671  sqlite3_value *pVal;
114672  char const *zSql8;
114673  int rc = SQLITE_NOMEM;
114674
114675#ifndef SQLITE_OMIT_AUTOINIT
114676  rc = sqlite3_initialize();
114677  if( rc ) return rc;
114678#endif
114679  pVal = sqlite3ValueNew(0);
114680  sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
114681  zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
114682  if( zSql8 ){
114683    rc = sqlite3_complete(zSql8);
114684  }else{
114685    rc = SQLITE_NOMEM;
114686  }
114687  sqlite3ValueFree(pVal);
114688  return sqlite3ApiExit(0, rc);
114689}
114690#endif /* SQLITE_OMIT_UTF16 */
114691#endif /* SQLITE_OMIT_COMPLETE */
114692
114693/************** End of complete.c ********************************************/
114694/************** Begin file main.c ********************************************/
114695/*
114696** 2001 September 15
114697**
114698** The author disclaims copyright to this source code.  In place of
114699** a legal notice, here is a blessing:
114700**
114701**    May you do good and not evil.
114702**    May you find forgiveness for yourself and forgive others.
114703**    May you share freely, never taking more than you give.
114704**
114705*************************************************************************
114706** Main file for the SQLite library.  The routines in this file
114707** implement the programmer interface to the library.  Routines in
114708** other files are for internal use by SQLite and should not be
114709** accessed by users of the library.
114710*/
114711
114712#ifdef SQLITE_ENABLE_FTS3
114713/************** Include fts3.h in the middle of main.c ***********************/
114714/************** Begin file fts3.h ********************************************/
114715/*
114716** 2006 Oct 10
114717**
114718** The author disclaims copyright to this source code.  In place of
114719** a legal notice, here is a blessing:
114720**
114721**    May you do good and not evil.
114722**    May you find forgiveness for yourself and forgive others.
114723**    May you share freely, never taking more than you give.
114724**
114725******************************************************************************
114726**
114727** This header file is used by programs that want to link against the
114728** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
114729*/
114730
114731#if 0
114732extern "C" {
114733#endif  /* __cplusplus */
114734
114735SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
114736
114737#if 0
114738}  /* extern "C" */
114739#endif  /* __cplusplus */
114740
114741/************** End of fts3.h ************************************************/
114742/************** Continuing where we left off in main.c ***********************/
114743#endif
114744#ifdef SQLITE_ENABLE_RTREE
114745/************** Include rtree.h in the middle of main.c **********************/
114746/************** Begin file rtree.h *******************************************/
114747/*
114748** 2008 May 26
114749**
114750** The author disclaims copyright to this source code.  In place of
114751** a legal notice, here is a blessing:
114752**
114753**    May you do good and not evil.
114754**    May you find forgiveness for yourself and forgive others.
114755**    May you share freely, never taking more than you give.
114756**
114757******************************************************************************
114758**
114759** This header file is used by programs that want to link against the
114760** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
114761*/
114762
114763#if 0
114764extern "C" {
114765#endif  /* __cplusplus */
114766
114767SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
114768
114769#if 0
114770}  /* extern "C" */
114771#endif  /* __cplusplus */
114772
114773/************** End of rtree.h ***********************************************/
114774/************** Continuing where we left off in main.c ***********************/
114775#endif
114776#ifdef SQLITE_ENABLE_ICU
114777/************** Include sqliteicu.h in the middle of main.c ******************/
114778/************** Begin file sqliteicu.h ***************************************/
114779/*
114780** 2008 May 26
114781**
114782** The author disclaims copyright to this source code.  In place of
114783** a legal notice, here is a blessing:
114784**
114785**    May you do good and not evil.
114786**    May you find forgiveness for yourself and forgive others.
114787**    May you share freely, never taking more than you give.
114788**
114789******************************************************************************
114790**
114791** This header file is used by programs that want to link against the
114792** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
114793*/
114794
114795#if 0
114796extern "C" {
114797#endif  /* __cplusplus */
114798
114799SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
114800
114801#if 0
114802}  /* extern "C" */
114803#endif  /* __cplusplus */
114804
114805
114806/************** End of sqliteicu.h *******************************************/
114807/************** Continuing where we left off in main.c ***********************/
114808#endif
114809
114810#ifndef SQLITE_AMALGAMATION
114811/* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
114812** contains the text of SQLITE_VERSION macro.
114813*/
114814SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
114815#endif
114816
114817/* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
114818** a pointer to the to the sqlite3_version[] string constant.
114819*/
114820SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
114821
114822/* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
114823** pointer to a string constant whose value is the same as the
114824** SQLITE_SOURCE_ID C preprocessor macro.
114825*/
114826SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
114827
114828/* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
114829** returns an integer equal to SQLITE_VERSION_NUMBER.
114830*/
114831SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
114832
114833/* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
114834** zero if and only if SQLite was compiled with mutexing code omitted due to
114835** the SQLITE_THREADSAFE compile-time option being set to 0.
114836*/
114837SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
114838
114839#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
114840/*
114841** If the following function pointer is not NULL and if
114842** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
114843** I/O active are written using this function.  These messages
114844** are intended for debugging activity only.
114845*/
114846SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
114847#endif
114848
114849/*
114850** If the following global variable points to a string which is the
114851** name of a directory, then that directory will be used to store
114852** temporary files.
114853**
114854** See also the "PRAGMA temp_store_directory" SQL command.
114855*/
114856SQLITE_API char *sqlite3_temp_directory = 0;
114857
114858/*
114859** If the following global variable points to a string which is the
114860** name of a directory, then that directory will be used to store
114861** all database files specified with a relative pathname.
114862**
114863** See also the "PRAGMA data_store_directory" SQL command.
114864*/
114865SQLITE_API char *sqlite3_data_directory = 0;
114866
114867/*
114868** Initialize SQLite.
114869**
114870** This routine must be called to initialize the memory allocation,
114871** VFS, and mutex subsystems prior to doing any serious work with
114872** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
114873** this routine will be called automatically by key routines such as
114874** sqlite3_open().
114875**
114876** This routine is a no-op except on its very first call for the process,
114877** or for the first call after a call to sqlite3_shutdown.
114878**
114879** The first thread to call this routine runs the initialization to
114880** completion.  If subsequent threads call this routine before the first
114881** thread has finished the initialization process, then the subsequent
114882** threads must block until the first thread finishes with the initialization.
114883**
114884** The first thread might call this routine recursively.  Recursive
114885** calls to this routine should not block, of course.  Otherwise the
114886** initialization process would never complete.
114887**
114888** Let X be the first thread to enter this routine.  Let Y be some other
114889** thread.  Then while the initial invocation of this routine by X is
114890** incomplete, it is required that:
114891**
114892**    *  Calls to this routine from Y must block until the outer-most
114893**       call by X completes.
114894**
114895**    *  Recursive calls to this routine from thread X return immediately
114896**       without blocking.
114897*/
114898SQLITE_API int sqlite3_initialize(void){
114899  MUTEX_LOGIC( sqlite3_mutex *pMaster; )       /* The main static mutex */
114900  int rc;                                      /* Result code */
114901
114902#ifdef SQLITE_OMIT_WSD
114903  rc = sqlite3_wsd_init(4096, 24);
114904  if( rc!=SQLITE_OK ){
114905    return rc;
114906  }
114907#endif
114908
114909  /* If SQLite is already completely initialized, then this call
114910  ** to sqlite3_initialize() should be a no-op.  But the initialization
114911  ** must be complete.  So isInit must not be set until the very end
114912  ** of this routine.
114913  */
114914  if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
114915
114916#ifdef SQLITE_ENABLE_SQLLOG
114917  {
114918    extern void sqlite3_init_sqllog(void);
114919    sqlite3_init_sqllog();
114920  }
114921#endif
114922
114923  /* Make sure the mutex subsystem is initialized.  If unable to
114924  ** initialize the mutex subsystem, return early with the error.
114925  ** If the system is so sick that we are unable to allocate a mutex,
114926  ** there is not much SQLite is going to be able to do.
114927  **
114928  ** The mutex subsystem must take care of serializing its own
114929  ** initialization.
114930  */
114931  rc = sqlite3MutexInit();
114932  if( rc ) return rc;
114933
114934  /* Initialize the malloc() system and the recursive pInitMutex mutex.
114935  ** This operation is protected by the STATIC_MASTER mutex.  Note that
114936  ** MutexAlloc() is called for a static mutex prior to initializing the
114937  ** malloc subsystem - this implies that the allocation of a static
114938  ** mutex must not require support from the malloc subsystem.
114939  */
114940  MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
114941  sqlite3_mutex_enter(pMaster);
114942  sqlite3GlobalConfig.isMutexInit = 1;
114943  if( !sqlite3GlobalConfig.isMallocInit ){
114944    rc = sqlite3MallocInit();
114945  }
114946  if( rc==SQLITE_OK ){
114947    sqlite3GlobalConfig.isMallocInit = 1;
114948    if( !sqlite3GlobalConfig.pInitMutex ){
114949      sqlite3GlobalConfig.pInitMutex =
114950           sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
114951      if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
114952        rc = SQLITE_NOMEM;
114953      }
114954    }
114955  }
114956  if( rc==SQLITE_OK ){
114957    sqlite3GlobalConfig.nRefInitMutex++;
114958  }
114959  sqlite3_mutex_leave(pMaster);
114960
114961  /* If rc is not SQLITE_OK at this point, then either the malloc
114962  ** subsystem could not be initialized or the system failed to allocate
114963  ** the pInitMutex mutex. Return an error in either case.  */
114964  if( rc!=SQLITE_OK ){
114965    return rc;
114966  }
114967
114968  /* Do the rest of the initialization under the recursive mutex so
114969  ** that we will be able to handle recursive calls into
114970  ** sqlite3_initialize().  The recursive calls normally come through
114971  ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
114972  ** recursive calls might also be possible.
114973  **
114974  ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
114975  ** to the xInit method, so the xInit method need not be threadsafe.
114976  **
114977  ** The following mutex is what serializes access to the appdef pcache xInit
114978  ** methods.  The sqlite3_pcache_methods.xInit() all is embedded in the
114979  ** call to sqlite3PcacheInitialize().
114980  */
114981  sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
114982  if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
114983    FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
114984    sqlite3GlobalConfig.inProgress = 1;
114985    memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
114986    sqlite3RegisterGlobalFunctions();
114987    if( sqlite3GlobalConfig.isPCacheInit==0 ){
114988      rc = sqlite3PcacheInitialize();
114989    }
114990    if( rc==SQLITE_OK ){
114991      sqlite3GlobalConfig.isPCacheInit = 1;
114992      rc = sqlite3OsInit();
114993    }
114994    if( rc==SQLITE_OK ){
114995      sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
114996          sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
114997      sqlite3GlobalConfig.isInit = 1;
114998    }
114999    sqlite3GlobalConfig.inProgress = 0;
115000  }
115001  sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
115002
115003  /* Go back under the static mutex and clean up the recursive
115004  ** mutex to prevent a resource leak.
115005  */
115006  sqlite3_mutex_enter(pMaster);
115007  sqlite3GlobalConfig.nRefInitMutex--;
115008  if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
115009    assert( sqlite3GlobalConfig.nRefInitMutex==0 );
115010    sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
115011    sqlite3GlobalConfig.pInitMutex = 0;
115012  }
115013  sqlite3_mutex_leave(pMaster);
115014
115015  /* The following is just a sanity check to make sure SQLite has
115016  ** been compiled correctly.  It is important to run this code, but
115017  ** we don't want to run it too often and soak up CPU cycles for no
115018  ** reason.  So we run it once during initialization.
115019  */
115020#ifndef NDEBUG
115021#ifndef SQLITE_OMIT_FLOATING_POINT
115022  /* This section of code's only "output" is via assert() statements. */
115023  if ( rc==SQLITE_OK ){
115024    u64 x = (((u64)1)<<63)-1;
115025    double y;
115026    assert(sizeof(x)==8);
115027    assert(sizeof(x)==sizeof(y));
115028    memcpy(&y, &x, 8);
115029    assert( sqlite3IsNaN(y) );
115030  }
115031#endif
115032#endif
115033
115034  /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
115035  ** compile-time option.
115036  */
115037#ifdef SQLITE_EXTRA_INIT
115038  if( rc==SQLITE_OK && sqlite3GlobalConfig.isInit ){
115039    int SQLITE_EXTRA_INIT(const char*);
115040    rc = SQLITE_EXTRA_INIT(0);
115041  }
115042#endif
115043
115044  return rc;
115045}
115046
115047/*
115048** Undo the effects of sqlite3_initialize().  Must not be called while
115049** there are outstanding database connections or memory allocations or
115050** while any part of SQLite is otherwise in use in any thread.  This
115051** routine is not threadsafe.  But it is safe to invoke this routine
115052** on when SQLite is already shut down.  If SQLite is already shut down
115053** when this routine is invoked, then this routine is a harmless no-op.
115054*/
115055SQLITE_API int sqlite3_shutdown(void){
115056  if( sqlite3GlobalConfig.isInit ){
115057#ifdef SQLITE_EXTRA_SHUTDOWN
115058    void SQLITE_EXTRA_SHUTDOWN(void);
115059    SQLITE_EXTRA_SHUTDOWN();
115060#endif
115061    sqlite3_os_end();
115062    sqlite3_reset_auto_extension();
115063    sqlite3GlobalConfig.isInit = 0;
115064  }
115065  if( sqlite3GlobalConfig.isPCacheInit ){
115066    sqlite3PcacheShutdown();
115067    sqlite3GlobalConfig.isPCacheInit = 0;
115068  }
115069  if( sqlite3GlobalConfig.isMallocInit ){
115070    sqlite3MallocEnd();
115071    sqlite3GlobalConfig.isMallocInit = 0;
115072
115073#ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
115074    /* The heap subsystem has now been shutdown and these values are supposed
115075    ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
115076    ** which would rely on that heap subsystem; therefore, make sure these
115077    ** values cannot refer to heap memory that was just invalidated when the
115078    ** heap subsystem was shutdown.  This is only done if the current call to
115079    ** this function resulted in the heap subsystem actually being shutdown.
115080    */
115081    sqlite3_data_directory = 0;
115082    sqlite3_temp_directory = 0;
115083#endif
115084  }
115085  if( sqlite3GlobalConfig.isMutexInit ){
115086    sqlite3MutexEnd();
115087    sqlite3GlobalConfig.isMutexInit = 0;
115088  }
115089
115090  return SQLITE_OK;
115091}
115092
115093/*
115094** This API allows applications to modify the global configuration of
115095** the SQLite library at run-time.
115096**
115097** This routine should only be called when there are no outstanding
115098** database connections or memory allocations.  This routine is not
115099** threadsafe.  Failure to heed these warnings can lead to unpredictable
115100** behavior.
115101*/
115102SQLITE_API int sqlite3_config(int op, ...){
115103  va_list ap;
115104  int rc = SQLITE_OK;
115105
115106  /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
115107  ** the SQLite library is in use. */
115108  if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
115109
115110  va_start(ap, op);
115111  switch( op ){
115112
115113    /* Mutex configuration options are only available in a threadsafe
115114    ** compile.
115115    */
115116#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
115117    case SQLITE_CONFIG_SINGLETHREAD: {
115118      /* Disable all mutexing */
115119      sqlite3GlobalConfig.bCoreMutex = 0;
115120      sqlite3GlobalConfig.bFullMutex = 0;
115121      break;
115122    }
115123    case SQLITE_CONFIG_MULTITHREAD: {
115124      /* Disable mutexing of database connections */
115125      /* Enable mutexing of core data structures */
115126      sqlite3GlobalConfig.bCoreMutex = 1;
115127      sqlite3GlobalConfig.bFullMutex = 0;
115128      break;
115129    }
115130    case SQLITE_CONFIG_SERIALIZED: {
115131      /* Enable all mutexing */
115132      sqlite3GlobalConfig.bCoreMutex = 1;
115133      sqlite3GlobalConfig.bFullMutex = 1;
115134      break;
115135    }
115136    case SQLITE_CONFIG_MUTEX: {
115137      /* Specify an alternative mutex implementation */
115138      sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
115139      break;
115140    }
115141    case SQLITE_CONFIG_GETMUTEX: {
115142      /* Retrieve the current mutex implementation */
115143      *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
115144      break;
115145    }
115146#endif
115147
115148
115149    case SQLITE_CONFIG_MALLOC: {
115150      /* Specify an alternative malloc implementation */
115151      sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
115152      break;
115153    }
115154    case SQLITE_CONFIG_GETMALLOC: {
115155      /* Retrieve the current malloc() implementation */
115156      if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
115157      *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
115158      break;
115159    }
115160    case SQLITE_CONFIG_MEMSTATUS: {
115161      /* Enable or disable the malloc status collection */
115162      sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
115163      break;
115164    }
115165    case SQLITE_CONFIG_SCRATCH: {
115166      /* Designate a buffer for scratch memory space */
115167      sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
115168      sqlite3GlobalConfig.szScratch = va_arg(ap, int);
115169      sqlite3GlobalConfig.nScratch = va_arg(ap, int);
115170      break;
115171    }
115172    case SQLITE_CONFIG_PAGECACHE: {
115173      /* Designate a buffer for page cache memory space */
115174      sqlite3GlobalConfig.pPage = va_arg(ap, void*);
115175      sqlite3GlobalConfig.szPage = va_arg(ap, int);
115176      sqlite3GlobalConfig.nPage = va_arg(ap, int);
115177      break;
115178    }
115179
115180    case SQLITE_CONFIG_PCACHE: {
115181      /* no-op */
115182      break;
115183    }
115184    case SQLITE_CONFIG_GETPCACHE: {
115185      /* now an error */
115186      rc = SQLITE_ERROR;
115187      break;
115188    }
115189
115190    case SQLITE_CONFIG_PCACHE2: {
115191      /* Specify an alternative page cache implementation */
115192      sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
115193      break;
115194    }
115195    case SQLITE_CONFIG_GETPCACHE2: {
115196      if( sqlite3GlobalConfig.pcache2.xInit==0 ){
115197        sqlite3PCacheSetDefault();
115198      }
115199      *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
115200      break;
115201    }
115202
115203#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
115204    case SQLITE_CONFIG_HEAP: {
115205      /* Designate a buffer for heap memory space */
115206      sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
115207      sqlite3GlobalConfig.nHeap = va_arg(ap, int);
115208      sqlite3GlobalConfig.mnReq = va_arg(ap, int);
115209
115210      if( sqlite3GlobalConfig.mnReq<1 ){
115211        sqlite3GlobalConfig.mnReq = 1;
115212      }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
115213        /* cap min request size at 2^12 */
115214        sqlite3GlobalConfig.mnReq = (1<<12);
115215      }
115216
115217      if( sqlite3GlobalConfig.pHeap==0 ){
115218        /* If the heap pointer is NULL, then restore the malloc implementation
115219        ** back to NULL pointers too.  This will cause the malloc to go
115220        ** back to its default implementation when sqlite3_initialize() is
115221        ** run.
115222        */
115223        memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
115224      }else{
115225        /* The heap pointer is not NULL, then install one of the
115226        ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor
115227        ** ENABLE_MEMSYS5 is defined, return an error.
115228        */
115229#ifdef SQLITE_ENABLE_MEMSYS3
115230        sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
115231#endif
115232#ifdef SQLITE_ENABLE_MEMSYS5
115233        sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
115234#endif
115235      }
115236      break;
115237    }
115238#endif
115239
115240    case SQLITE_CONFIG_LOOKASIDE: {
115241      sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
115242      sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
115243      break;
115244    }
115245
115246    /* Record a pointer to the logger funcction and its first argument.
115247    ** The default is NULL.  Logging is disabled if the function pointer is
115248    ** NULL.
115249    */
115250    case SQLITE_CONFIG_LOG: {
115251      /* MSVC is picky about pulling func ptrs from va lists.
115252      ** http://support.microsoft.com/kb/47961
115253      ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
115254      */
115255      typedef void(*LOGFUNC_t)(void*,int,const char*);
115256      sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
115257      sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
115258      break;
115259    }
115260
115261    case SQLITE_CONFIG_URI: {
115262      sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
115263      break;
115264    }
115265
115266    case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
115267      sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
115268      break;
115269    }
115270
115271#ifdef SQLITE_ENABLE_SQLLOG
115272    case SQLITE_CONFIG_SQLLOG: {
115273      typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
115274      sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
115275      sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
115276      break;
115277    }
115278#endif
115279
115280    case SQLITE_CONFIG_MMAP_SIZE: {
115281      sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
115282      sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
115283      if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
115284        mxMmap = SQLITE_MAX_MMAP_SIZE;
115285      }
115286      sqlite3GlobalConfig.mxMmap = mxMmap;
115287      if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
115288      if( szMmap>mxMmap) szMmap = mxMmap;
115289      sqlite3GlobalConfig.szMmap = szMmap;
115290      break;
115291    }
115292
115293    default: {
115294      rc = SQLITE_ERROR;
115295      break;
115296    }
115297  }
115298  va_end(ap);
115299  return rc;
115300}
115301
115302/*
115303** Set up the lookaside buffers for a database connection.
115304** Return SQLITE_OK on success.
115305** If lookaside is already active, return SQLITE_BUSY.
115306**
115307** The sz parameter is the number of bytes in each lookaside slot.
115308** The cnt parameter is the number of slots.  If pStart is NULL the
115309** space for the lookaside memory is obtained from sqlite3_malloc().
115310** If pStart is not NULL then it is sz*cnt bytes of memory to use for
115311** the lookaside memory.
115312*/
115313static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
115314  void *pStart;
115315  if( db->lookaside.nOut ){
115316    return SQLITE_BUSY;
115317  }
115318  /* Free any existing lookaside buffer for this handle before
115319  ** allocating a new one so we don't have to have space for
115320  ** both at the same time.
115321  */
115322  if( db->lookaside.bMalloced ){
115323    sqlite3_free(db->lookaside.pStart);
115324  }
115325  /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
115326  ** than a pointer to be useful.
115327  */
115328  sz = ROUNDDOWN8(sz);  /* IMP: R-33038-09382 */
115329  if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
115330  if( cnt<0 ) cnt = 0;
115331  if( sz==0 || cnt==0 ){
115332    sz = 0;
115333    pStart = 0;
115334  }else if( pBuf==0 ){
115335    sqlite3BeginBenignMalloc();
115336    pStart = sqlite3Malloc( sz*cnt );  /* IMP: R-61949-35727 */
115337    sqlite3EndBenignMalloc();
115338    if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
115339  }else{
115340    pStart = pBuf;
115341  }
115342  db->lookaside.pStart = pStart;
115343  db->lookaside.pFree = 0;
115344  db->lookaside.sz = (u16)sz;
115345  if( pStart ){
115346    int i;
115347    LookasideSlot *p;
115348    assert( sz > (int)sizeof(LookasideSlot*) );
115349    p = (LookasideSlot*)pStart;
115350    for(i=cnt-1; i>=0; i--){
115351      p->pNext = db->lookaside.pFree;
115352      db->lookaside.pFree = p;
115353      p = (LookasideSlot*)&((u8*)p)[sz];
115354    }
115355    db->lookaside.pEnd = p;
115356    db->lookaside.bEnabled = 1;
115357    db->lookaside.bMalloced = pBuf==0 ?1:0;
115358  }else{
115359    db->lookaside.pEnd = 0;
115360    db->lookaside.bEnabled = 0;
115361    db->lookaside.bMalloced = 0;
115362  }
115363  return SQLITE_OK;
115364}
115365
115366/*
115367** Return the mutex associated with a database connection.
115368*/
115369SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
115370  return db->mutex;
115371}
115372
115373/*
115374** Free up as much memory as we can from the given database
115375** connection.
115376*/
115377SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){
115378  int i;
115379  sqlite3_mutex_enter(db->mutex);
115380  sqlite3BtreeEnterAll(db);
115381  for(i=0; i<db->nDb; i++){
115382    Btree *pBt = db->aDb[i].pBt;
115383    if( pBt ){
115384      Pager *pPager = sqlite3BtreePager(pBt);
115385      sqlite3PagerShrink(pPager);
115386    }
115387  }
115388  sqlite3BtreeLeaveAll(db);
115389  sqlite3_mutex_leave(db->mutex);
115390  return SQLITE_OK;
115391}
115392
115393/*
115394** Configuration settings for an individual database connection
115395*/
115396SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
115397  va_list ap;
115398  int rc;
115399  va_start(ap, op);
115400  switch( op ){
115401    case SQLITE_DBCONFIG_LOOKASIDE: {
115402      void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
115403      int sz = va_arg(ap, int);       /* IMP: R-47871-25994 */
115404      int cnt = va_arg(ap, int);      /* IMP: R-04460-53386 */
115405      rc = setupLookaside(db, pBuf, sz, cnt);
115406      break;
115407    }
115408    default: {
115409      static const struct {
115410        int op;      /* The opcode */
115411        u32 mask;    /* Mask of the bit in sqlite3.flags to set/clear */
115412      } aFlagOp[] = {
115413        { SQLITE_DBCONFIG_ENABLE_FKEY,    SQLITE_ForeignKeys    },
115414        { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger  },
115415      };
115416      unsigned int i;
115417      rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
115418      for(i=0; i<ArraySize(aFlagOp); i++){
115419        if( aFlagOp[i].op==op ){
115420          int onoff = va_arg(ap, int);
115421          int *pRes = va_arg(ap, int*);
115422          int oldFlags = db->flags;
115423          if( onoff>0 ){
115424            db->flags |= aFlagOp[i].mask;
115425          }else if( onoff==0 ){
115426            db->flags &= ~aFlagOp[i].mask;
115427          }
115428          if( oldFlags!=db->flags ){
115429            sqlite3ExpirePreparedStatements(db);
115430          }
115431          if( pRes ){
115432            *pRes = (db->flags & aFlagOp[i].mask)!=0;
115433          }
115434          rc = SQLITE_OK;
115435          break;
115436        }
115437      }
115438      break;
115439    }
115440  }
115441  va_end(ap);
115442  return rc;
115443}
115444
115445
115446/*
115447** Return true if the buffer z[0..n-1] contains all spaces.
115448*/
115449static int allSpaces(const char *z, int n){
115450  while( n>0 && z[n-1]==' ' ){ n--; }
115451  return n==0;
115452}
115453
115454/*
115455** This is the default collating function named "BINARY" which is always
115456** available.
115457**
115458** If the padFlag argument is not NULL then space padding at the end
115459** of strings is ignored.  This implements the RTRIM collation.
115460*/
115461static int binCollFunc(
115462  void *padFlag,
115463  int nKey1, const void *pKey1,
115464  int nKey2, const void *pKey2
115465){
115466  int rc, n;
115467  n = nKey1<nKey2 ? nKey1 : nKey2;
115468  rc = memcmp(pKey1, pKey2, n);
115469  if( rc==0 ){
115470    if( padFlag
115471     && allSpaces(((char*)pKey1)+n, nKey1-n)
115472     && allSpaces(((char*)pKey2)+n, nKey2-n)
115473    ){
115474      /* Leave rc unchanged at 0 */
115475    }else{
115476      rc = nKey1 - nKey2;
115477    }
115478  }
115479  return rc;
115480}
115481
115482/*
115483** Another built-in collating sequence: NOCASE.
115484**
115485** This collating sequence is intended to be used for "case independant
115486** comparison". SQLite's knowledge of upper and lower case equivalents
115487** extends only to the 26 characters used in the English language.
115488**
115489** At the moment there is only a UTF-8 implementation.
115490*/
115491static int nocaseCollatingFunc(
115492  void *NotUsed,
115493  int nKey1, const void *pKey1,
115494  int nKey2, const void *pKey2
115495){
115496  int r = sqlite3StrNICmp(
115497      (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
115498  UNUSED_PARAMETER(NotUsed);
115499  if( 0==r ){
115500    r = nKey1-nKey2;
115501  }
115502  return r;
115503}
115504
115505/*
115506** Return the ROWID of the most recent insert
115507*/
115508SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
115509  return db->lastRowid;
115510}
115511
115512/*
115513** Return the number of changes in the most recent call to sqlite3_exec().
115514*/
115515SQLITE_API int sqlite3_changes(sqlite3 *db){
115516  return db->nChange;
115517}
115518
115519/*
115520** Return the number of changes since the database handle was opened.
115521*/
115522SQLITE_API int sqlite3_total_changes(sqlite3 *db){
115523  return db->nTotalChange;
115524}
115525
115526/*
115527** Close all open savepoints. This function only manipulates fields of the
115528** database handle object, it does not close any savepoints that may be open
115529** at the b-tree/pager level.
115530*/
115531SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
115532  while( db->pSavepoint ){
115533    Savepoint *pTmp = db->pSavepoint;
115534    db->pSavepoint = pTmp->pNext;
115535    sqlite3DbFree(db, pTmp);
115536  }
115537  db->nSavepoint = 0;
115538  db->nStatement = 0;
115539  db->isTransactionSavepoint = 0;
115540}
115541
115542/*
115543** Invoke the destructor function associated with FuncDef p, if any. Except,
115544** if this is not the last copy of the function, do not invoke it. Multiple
115545** copies of a single function are created when create_function() is called
115546** with SQLITE_ANY as the encoding.
115547*/
115548static void functionDestroy(sqlite3 *db, FuncDef *p){
115549  FuncDestructor *pDestructor = p->pDestructor;
115550  if( pDestructor ){
115551    pDestructor->nRef--;
115552    if( pDestructor->nRef==0 ){
115553      pDestructor->xDestroy(pDestructor->pUserData);
115554      sqlite3DbFree(db, pDestructor);
115555    }
115556  }
115557}
115558
115559/*
115560** Disconnect all sqlite3_vtab objects that belong to database connection
115561** db. This is called when db is being closed.
115562*/
115563static void disconnectAllVtab(sqlite3 *db){
115564#ifndef SQLITE_OMIT_VIRTUALTABLE
115565  int i;
115566  sqlite3BtreeEnterAll(db);
115567  for(i=0; i<db->nDb; i++){
115568    Schema *pSchema = db->aDb[i].pSchema;
115569    if( db->aDb[i].pSchema ){
115570      HashElem *p;
115571      for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
115572        Table *pTab = (Table *)sqliteHashData(p);
115573        if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
115574      }
115575    }
115576  }
115577  sqlite3BtreeLeaveAll(db);
115578#else
115579  UNUSED_PARAMETER(db);
115580#endif
115581}
115582
115583/*
115584** Return TRUE if database connection db has unfinalized prepared
115585** statements or unfinished sqlite3_backup objects.
115586*/
115587static int connectionIsBusy(sqlite3 *db){
115588  int j;
115589  assert( sqlite3_mutex_held(db->mutex) );
115590  if( db->pVdbe ) return 1;
115591  for(j=0; j<db->nDb; j++){
115592    Btree *pBt = db->aDb[j].pBt;
115593    if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
115594  }
115595  return 0;
115596}
115597
115598/*
115599** Close an existing SQLite database
115600*/
115601static int sqlite3Close(sqlite3 *db, int forceZombie){
115602  if( !db ){
115603    return SQLITE_OK;
115604  }
115605  if( !sqlite3SafetyCheckSickOrOk(db) ){
115606    return SQLITE_MISUSE_BKPT;
115607  }
115608  sqlite3_mutex_enter(db->mutex);
115609
115610  /* Force xDisconnect calls on all virtual tables */
115611  disconnectAllVtab(db);
115612
115613  /* If a transaction is open, the disconnectAllVtab() call above
115614  ** will not have called the xDisconnect() method on any virtual
115615  ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
115616  ** call will do so. We need to do this before the check for active
115617  ** SQL statements below, as the v-table implementation may be storing
115618  ** some prepared statements internally.
115619  */
115620  sqlite3VtabRollback(db);
115621
115622  /* Legacy behavior (sqlite3_close() behavior) is to return
115623  ** SQLITE_BUSY if the connection can not be closed immediately.
115624  */
115625  if( !forceZombie && connectionIsBusy(db) ){
115626    sqlite3Error(db, SQLITE_BUSY, "unable to close due to unfinalized "
115627       "statements or unfinished backups");
115628    sqlite3_mutex_leave(db->mutex);
115629    return SQLITE_BUSY;
115630  }
115631
115632#ifdef SQLITE_ENABLE_SQLLOG
115633  if( sqlite3GlobalConfig.xSqllog ){
115634    /* Closing the handle. Fourth parameter is passed the value 2. */
115635    sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
115636  }
115637#endif
115638
115639  /* Convert the connection into a zombie and then close it.
115640  */
115641  db->magic = SQLITE_MAGIC_ZOMBIE;
115642  sqlite3LeaveMutexAndCloseZombie(db);
115643  return SQLITE_OK;
115644}
115645
115646/*
115647** Two variations on the public interface for closing a database
115648** connection. The sqlite3_close() version returns SQLITE_BUSY and
115649** leaves the connection option if there are unfinalized prepared
115650** statements or unfinished sqlite3_backups.  The sqlite3_close_v2()
115651** version forces the connection to become a zombie if there are
115652** unclosed resources, and arranges for deallocation when the last
115653** prepare statement or sqlite3_backup closes.
115654*/
115655SQLITE_API int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
115656SQLITE_API int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
115657
115658
115659/*
115660** Close the mutex on database connection db.
115661**
115662** Furthermore, if database connection db is a zombie (meaning that there
115663** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
115664** every sqlite3_stmt has now been finalized and every sqlite3_backup has
115665** finished, then free all resources.
115666*/
115667SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
115668  HashElem *i;                    /* Hash table iterator */
115669  int j;
115670
115671  /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
115672  ** or if the connection has not yet been closed by sqlite3_close_v2(),
115673  ** then just leave the mutex and return.
115674  */
115675  if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
115676    sqlite3_mutex_leave(db->mutex);
115677    return;
115678  }
115679
115680  /* If we reach this point, it means that the database connection has
115681  ** closed all sqlite3_stmt and sqlite3_backup objects and has been
115682  ** passed to sqlite3_close (meaning that it is a zombie).  Therefore,
115683  ** go ahead and free all resources.
115684  */
115685
115686  /* If a transaction is open, roll it back. This also ensures that if
115687  ** any database schemas have been modified by an uncommitted transaction
115688  ** they are reset. And that the required b-tree mutex is held to make
115689  ** the pager rollback and schema reset an atomic operation. */
115690  sqlite3RollbackAll(db, SQLITE_OK);
115691
115692  /* Free any outstanding Savepoint structures. */
115693  sqlite3CloseSavepoints(db);
115694
115695  /* Close all database connections */
115696  for(j=0; j<db->nDb; j++){
115697    struct Db *pDb = &db->aDb[j];
115698    if( pDb->pBt ){
115699      sqlite3BtreeClose(pDb->pBt);
115700      pDb->pBt = 0;
115701      if( j!=1 ){
115702        pDb->pSchema = 0;
115703      }
115704    }
115705  }
115706  /* Clear the TEMP schema separately and last */
115707  if( db->aDb[1].pSchema ){
115708    sqlite3SchemaClear(db->aDb[1].pSchema);
115709  }
115710  sqlite3VtabUnlockList(db);
115711
115712  /* Free up the array of auxiliary databases */
115713  sqlite3CollapseDatabaseArray(db);
115714  assert( db->nDb<=2 );
115715  assert( db->aDb==db->aDbStatic );
115716
115717  /* Tell the code in notify.c that the connection no longer holds any
115718  ** locks and does not require any further unlock-notify callbacks.
115719  */
115720  sqlite3ConnectionClosed(db);
115721
115722  for(j=0; j<ArraySize(db->aFunc.a); j++){
115723    FuncDef *pNext, *pHash, *p;
115724    for(p=db->aFunc.a[j]; p; p=pHash){
115725      pHash = p->pHash;
115726      while( p ){
115727        functionDestroy(db, p);
115728        pNext = p->pNext;
115729        sqlite3DbFree(db, p);
115730        p = pNext;
115731      }
115732    }
115733  }
115734  for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
115735    CollSeq *pColl = (CollSeq *)sqliteHashData(i);
115736    /* Invoke any destructors registered for collation sequence user data. */
115737    for(j=0; j<3; j++){
115738      if( pColl[j].xDel ){
115739        pColl[j].xDel(pColl[j].pUser);
115740      }
115741    }
115742    sqlite3DbFree(db, pColl);
115743  }
115744  sqlite3HashClear(&db->aCollSeq);
115745#ifndef SQLITE_OMIT_VIRTUALTABLE
115746  for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
115747    Module *pMod = (Module *)sqliteHashData(i);
115748    if( pMod->xDestroy ){
115749      pMod->xDestroy(pMod->pAux);
115750    }
115751    sqlite3DbFree(db, pMod);
115752  }
115753  sqlite3HashClear(&db->aModule);
115754#endif
115755
115756  sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
115757  if( db->pErr ){
115758    sqlite3ValueFree(db->pErr);
115759  }
115760  sqlite3CloseExtensions(db);
115761
115762  db->magic = SQLITE_MAGIC_ERROR;
115763
115764  /* The temp-database schema is allocated differently from the other schema
115765  ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
115766  ** So it needs to be freed here. Todo: Why not roll the temp schema into
115767  ** the same sqliteMalloc() as the one that allocates the database
115768  ** structure?
115769  */
115770  sqlite3DbFree(db, db->aDb[1].pSchema);
115771  sqlite3_mutex_leave(db->mutex);
115772  db->magic = SQLITE_MAGIC_CLOSED;
115773  sqlite3_mutex_free(db->mutex);
115774  assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
115775  if( db->lookaside.bMalloced ){
115776    sqlite3_free(db->lookaside.pStart);
115777  }
115778  sqlite3_free(db);
115779}
115780
115781/*
115782** Rollback all database files.  If tripCode is not SQLITE_OK, then
115783** any open cursors are invalidated ("tripped" - as in "tripping a circuit
115784** breaker") and made to return tripCode if there are any further
115785** attempts to use that cursor.
115786*/
115787SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
115788  int i;
115789  int inTrans = 0;
115790  assert( sqlite3_mutex_held(db->mutex) );
115791  sqlite3BeginBenignMalloc();
115792
115793  /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
115794  ** This is important in case the transaction being rolled back has
115795  ** modified the database schema. If the b-tree mutexes are not taken
115796  ** here, then another shared-cache connection might sneak in between
115797  ** the database rollback and schema reset, which can cause false
115798  ** corruption reports in some cases.  */
115799  sqlite3BtreeEnterAll(db);
115800
115801  for(i=0; i<db->nDb; i++){
115802    Btree *p = db->aDb[i].pBt;
115803    if( p ){
115804      if( sqlite3BtreeIsInTrans(p) ){
115805        inTrans = 1;
115806      }
115807      sqlite3BtreeRollback(p, tripCode);
115808      db->aDb[i].inTrans = 0;
115809    }
115810  }
115811  sqlite3VtabRollback(db);
115812  sqlite3EndBenignMalloc();
115813
115814  if( (db->flags&SQLITE_InternChanges)!=0 && db->init.busy==0 ){
115815    sqlite3ExpirePreparedStatements(db);
115816    sqlite3ResetAllSchemasOfConnection(db);
115817  }
115818  sqlite3BtreeLeaveAll(db);
115819
115820  /* Any deferred constraint violations have now been resolved. */
115821  db->nDeferredCons = 0;
115822
115823  /* If one has been configured, invoke the rollback-hook callback */
115824  if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
115825    db->xRollbackCallback(db->pRollbackArg);
115826  }
115827}
115828
115829/*
115830** Return a static string containing the name corresponding to the error code
115831** specified in the argument.
115832*/
115833#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) || \
115834    defined(SQLITE_DEBUG_OS_TRACE)
115835SQLITE_PRIVATE const char *sqlite3ErrName(int rc){
115836  const char *zName = 0;
115837  int i, origRc = rc;
115838  for(i=0; i<2 && zName==0; i++, rc &= 0xff){
115839    switch( rc ){
115840      case SQLITE_OK:                 zName = "SQLITE_OK";                break;
115841      case SQLITE_ERROR:              zName = "SQLITE_ERROR";             break;
115842      case SQLITE_INTERNAL:           zName = "SQLITE_INTERNAL";          break;
115843      case SQLITE_PERM:               zName = "SQLITE_PERM";              break;
115844      case SQLITE_ABORT:              zName = "SQLITE_ABORT";             break;
115845      case SQLITE_ABORT_ROLLBACK:     zName = "SQLITE_ABORT_ROLLBACK";    break;
115846      case SQLITE_BUSY:               zName = "SQLITE_BUSY";              break;
115847      case SQLITE_BUSY_RECOVERY:      zName = "SQLITE_BUSY_RECOVERY";     break;
115848      case SQLITE_LOCKED:             zName = "SQLITE_LOCKED";            break;
115849      case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
115850      case SQLITE_NOMEM:              zName = "SQLITE_NOMEM";             break;
115851      case SQLITE_READONLY:           zName = "SQLITE_READONLY";          break;
115852      case SQLITE_READONLY_RECOVERY:  zName = "SQLITE_READONLY_RECOVERY"; break;
115853      case SQLITE_READONLY_CANTLOCK:  zName = "SQLITE_READONLY_CANTLOCK"; break;
115854      case SQLITE_READONLY_ROLLBACK:  zName = "SQLITE_READONLY_ROLLBACK"; break;
115855      case SQLITE_INTERRUPT:          zName = "SQLITE_INTERRUPT";         break;
115856      case SQLITE_IOERR:              zName = "SQLITE_IOERR";             break;
115857      case SQLITE_IOERR_READ:         zName = "SQLITE_IOERR_READ";        break;
115858      case SQLITE_IOERR_SHORT_READ:   zName = "SQLITE_IOERR_SHORT_READ";  break;
115859      case SQLITE_IOERR_WRITE:        zName = "SQLITE_IOERR_WRITE";       break;
115860      case SQLITE_IOERR_FSYNC:        zName = "SQLITE_IOERR_FSYNC";       break;
115861      case SQLITE_IOERR_DIR_FSYNC:    zName = "SQLITE_IOERR_DIR_FSYNC";   break;
115862      case SQLITE_IOERR_TRUNCATE:     zName = "SQLITE_IOERR_TRUNCATE";    break;
115863      case SQLITE_IOERR_FSTAT:        zName = "SQLITE_IOERR_FSTAT";       break;
115864      case SQLITE_IOERR_UNLOCK:       zName = "SQLITE_IOERR_UNLOCK";      break;
115865      case SQLITE_IOERR_RDLOCK:       zName = "SQLITE_IOERR_RDLOCK";      break;
115866      case SQLITE_IOERR_DELETE:       zName = "SQLITE_IOERR_DELETE";      break;
115867      case SQLITE_IOERR_BLOCKED:      zName = "SQLITE_IOERR_BLOCKED";     break;
115868      case SQLITE_IOERR_NOMEM:        zName = "SQLITE_IOERR_NOMEM";       break;
115869      case SQLITE_IOERR_ACCESS:       zName = "SQLITE_IOERR_ACCESS";      break;
115870      case SQLITE_IOERR_CHECKRESERVEDLOCK:
115871                                zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
115872      case SQLITE_IOERR_LOCK:         zName = "SQLITE_IOERR_LOCK";        break;
115873      case SQLITE_IOERR_CLOSE:        zName = "SQLITE_IOERR_CLOSE";       break;
115874      case SQLITE_IOERR_DIR_CLOSE:    zName = "SQLITE_IOERR_DIR_CLOSE";   break;
115875      case SQLITE_IOERR_SHMOPEN:      zName = "SQLITE_IOERR_SHMOPEN";     break;
115876      case SQLITE_IOERR_SHMSIZE:      zName = "SQLITE_IOERR_SHMSIZE";     break;
115877      case SQLITE_IOERR_SHMLOCK:      zName = "SQLITE_IOERR_SHMLOCK";     break;
115878      case SQLITE_IOERR_SHMMAP:       zName = "SQLITE_IOERR_SHMMAP";      break;
115879      case SQLITE_IOERR_SEEK:         zName = "SQLITE_IOERR_SEEK";        break;
115880      case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
115881      case SQLITE_IOERR_MMAP:         zName = "SQLITE_IOERR_MMAP";        break;
115882      case SQLITE_CORRUPT:            zName = "SQLITE_CORRUPT";           break;
115883      case SQLITE_CORRUPT_VTAB:       zName = "SQLITE_CORRUPT_VTAB";      break;
115884      case SQLITE_NOTFOUND:           zName = "SQLITE_NOTFOUND";          break;
115885      case SQLITE_FULL:               zName = "SQLITE_FULL";              break;
115886      case SQLITE_CANTOPEN:           zName = "SQLITE_CANTOPEN";          break;
115887      case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
115888      case SQLITE_CANTOPEN_ISDIR:     zName = "SQLITE_CANTOPEN_ISDIR";    break;
115889      case SQLITE_CANTOPEN_FULLPATH:  zName = "SQLITE_CANTOPEN_FULLPATH"; break;
115890      case SQLITE_PROTOCOL:           zName = "SQLITE_PROTOCOL";          break;
115891      case SQLITE_EMPTY:              zName = "SQLITE_EMPTY";             break;
115892      case SQLITE_SCHEMA:             zName = "SQLITE_SCHEMA";            break;
115893      case SQLITE_TOOBIG:             zName = "SQLITE_TOOBIG";            break;
115894      case SQLITE_CONSTRAINT:         zName = "SQLITE_CONSTRAINT";        break;
115895      case SQLITE_CONSTRAINT_UNIQUE:  zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
115896      case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
115897      case SQLITE_CONSTRAINT_FOREIGNKEY:
115898                                zName = "SQLITE_CONSTRAINT_FOREIGNKEY";   break;
115899      case SQLITE_CONSTRAINT_CHECK:   zName = "SQLITE_CONSTRAINT_CHECK";  break;
115900      case SQLITE_CONSTRAINT_PRIMARYKEY:
115901                                zName = "SQLITE_CONSTRAINT_PRIMARYKEY";   break;
115902      case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
115903      case SQLITE_CONSTRAINT_COMMITHOOK:
115904                                zName = "SQLITE_CONSTRAINT_COMMITHOOK";   break;
115905      case SQLITE_CONSTRAINT_VTAB:    zName = "SQLITE_CONSTRAINT_VTAB";   break;
115906      case SQLITE_CONSTRAINT_FUNCTION:
115907                                zName = "SQLITE_CONSTRAINT_FUNCTION";     break;
115908      case SQLITE_MISMATCH:           zName = "SQLITE_MISMATCH";          break;
115909      case SQLITE_MISUSE:             zName = "SQLITE_MISUSE";            break;
115910      case SQLITE_NOLFS:              zName = "SQLITE_NOLFS";             break;
115911      case SQLITE_AUTH:               zName = "SQLITE_AUTH";              break;
115912      case SQLITE_FORMAT:             zName = "SQLITE_FORMAT";            break;
115913      case SQLITE_RANGE:              zName = "SQLITE_RANGE";             break;
115914      case SQLITE_NOTADB:             zName = "SQLITE_NOTADB";            break;
115915      case SQLITE_ROW:                zName = "SQLITE_ROW";               break;
115916      case SQLITE_NOTICE:             zName = "SQLITE_NOTICE";            break;
115917      case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
115918      case SQLITE_NOTICE_RECOVER_ROLLBACK:
115919                                zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
115920      case SQLITE_WARNING:            zName = "SQLITE_WARNING";           break;
115921      case SQLITE_DONE:               zName = "SQLITE_DONE";              break;
115922    }
115923  }
115924  if( zName==0 ){
115925    static char zBuf[50];
115926    sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
115927    zName = zBuf;
115928  }
115929  return zName;
115930}
115931#endif
115932
115933/*
115934** Return a static string that describes the kind of error specified in the
115935** argument.
115936*/
115937SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
115938  static const char* const aMsg[] = {
115939    /* SQLITE_OK          */ "not an error",
115940    /* SQLITE_ERROR       */ "SQL logic error or missing database",
115941    /* SQLITE_INTERNAL    */ 0,
115942    /* SQLITE_PERM        */ "access permission denied",
115943    /* SQLITE_ABORT       */ "callback requested query abort",
115944    /* SQLITE_BUSY        */ "database is locked",
115945    /* SQLITE_LOCKED      */ "database table is locked",
115946    /* SQLITE_NOMEM       */ "out of memory",
115947    /* SQLITE_READONLY    */ "attempt to write a readonly database",
115948    /* SQLITE_INTERRUPT   */ "interrupted",
115949    /* SQLITE_IOERR       */ "disk I/O error",
115950    /* SQLITE_CORRUPT     */ "database disk image is malformed",
115951    /* SQLITE_NOTFOUND    */ "unknown operation",
115952    /* SQLITE_FULL        */ "database or disk is full",
115953    /* SQLITE_CANTOPEN    */ "unable to open database file",
115954    /* SQLITE_PROTOCOL    */ "locking protocol",
115955    /* SQLITE_EMPTY       */ "table contains no data",
115956    /* SQLITE_SCHEMA      */ "database schema has changed",
115957    /* SQLITE_TOOBIG      */ "string or blob too big",
115958    /* SQLITE_CONSTRAINT  */ "constraint failed",
115959    /* SQLITE_MISMATCH    */ "datatype mismatch",
115960    /* SQLITE_MISUSE      */ "library routine called out of sequence",
115961    /* SQLITE_NOLFS       */ "large file support is disabled",
115962    /* SQLITE_AUTH        */ "authorization denied",
115963    /* SQLITE_FORMAT      */ "auxiliary database format error",
115964    /* SQLITE_RANGE       */ "bind or column index out of range",
115965    /* SQLITE_NOTADB      */ "file is encrypted or is not a database",
115966  };
115967  const char *zErr = "unknown error";
115968  switch( rc ){
115969    case SQLITE_ABORT_ROLLBACK: {
115970      zErr = "abort due to ROLLBACK";
115971      break;
115972    }
115973    default: {
115974      rc &= 0xff;
115975      if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
115976        zErr = aMsg[rc];
115977      }
115978      break;
115979    }
115980  }
115981  return zErr;
115982}
115983
115984/*
115985** This routine implements a busy callback that sleeps and tries
115986** again until a timeout value is reached.  The timeout value is
115987** an integer number of milliseconds passed in as the first
115988** argument.
115989*/
115990static int sqliteDefaultBusyCallback(
115991 void *ptr,               /* Database connection */
115992 int count                /* Number of times table has been busy */
115993){
115994#if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
115995  static const u8 delays[] =
115996     { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
115997  static const u8 totals[] =
115998     { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
115999# define NDELAY ArraySize(delays)
116000  sqlite3 *db = (sqlite3 *)ptr;
116001  int timeout = db->busyTimeout;
116002  int delay, prior;
116003
116004  assert( count>=0 );
116005  if( count < NDELAY ){
116006    delay = delays[count];
116007    prior = totals[count];
116008  }else{
116009    delay = delays[NDELAY-1];
116010    prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
116011  }
116012  if( prior + delay > timeout ){
116013    delay = timeout - prior;
116014    if( delay<=0 ) return 0;
116015  }
116016  sqlite3OsSleep(db->pVfs, delay*1000);
116017  return 1;
116018#else
116019  sqlite3 *db = (sqlite3 *)ptr;
116020  int timeout = ((sqlite3 *)ptr)->busyTimeout;
116021  if( (count+1)*1000 > timeout ){
116022    return 0;
116023  }
116024  sqlite3OsSleep(db->pVfs, 1000000);
116025  return 1;
116026#endif
116027}
116028
116029/*
116030** Invoke the given busy handler.
116031**
116032** This routine is called when an operation failed with a lock.
116033** If this routine returns non-zero, the lock is retried.  If it
116034** returns 0, the operation aborts with an SQLITE_BUSY error.
116035*/
116036SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
116037  int rc;
116038  if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
116039  rc = p->xFunc(p->pArg, p->nBusy);
116040  if( rc==0 ){
116041    p->nBusy = -1;
116042  }else{
116043    p->nBusy++;
116044  }
116045  return rc;
116046}
116047
116048/*
116049** This routine sets the busy callback for an Sqlite database to the
116050** given callback function with the given argument.
116051*/
116052SQLITE_API int sqlite3_busy_handler(
116053  sqlite3 *db,
116054  int (*xBusy)(void*,int),
116055  void *pArg
116056){
116057  sqlite3_mutex_enter(db->mutex);
116058  db->busyHandler.xFunc = xBusy;
116059  db->busyHandler.pArg = pArg;
116060  db->busyHandler.nBusy = 0;
116061  db->busyTimeout = 0;
116062  sqlite3_mutex_leave(db->mutex);
116063  return SQLITE_OK;
116064}
116065
116066#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
116067/*
116068** This routine sets the progress callback for an Sqlite database to the
116069** given callback function with the given argument. The progress callback will
116070** be invoked every nOps opcodes.
116071*/
116072SQLITE_API void sqlite3_progress_handler(
116073  sqlite3 *db,
116074  int nOps,
116075  int (*xProgress)(void*),
116076  void *pArg
116077){
116078  sqlite3_mutex_enter(db->mutex);
116079  if( nOps>0 ){
116080    db->xProgress = xProgress;
116081    db->nProgressOps = nOps;
116082    db->pProgressArg = pArg;
116083  }else{
116084    db->xProgress = 0;
116085    db->nProgressOps = 0;
116086    db->pProgressArg = 0;
116087  }
116088  sqlite3_mutex_leave(db->mutex);
116089}
116090#endif
116091
116092
116093/*
116094** This routine installs a default busy handler that waits for the
116095** specified number of milliseconds before returning 0.
116096*/
116097SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
116098  if( ms>0 ){
116099    sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
116100    db->busyTimeout = ms;
116101  }else{
116102    sqlite3_busy_handler(db, 0, 0);
116103  }
116104  return SQLITE_OK;
116105}
116106
116107/*
116108** Cause any pending operation to stop at its earliest opportunity.
116109*/
116110SQLITE_API void sqlite3_interrupt(sqlite3 *db){
116111  db->u1.isInterrupted = 1;
116112}
116113
116114
116115/*
116116** This function is exactly the same as sqlite3_create_function(), except
116117** that it is designed to be called by internal code. The difference is
116118** that if a malloc() fails in sqlite3_create_function(), an error code
116119** is returned and the mallocFailed flag cleared.
116120*/
116121SQLITE_PRIVATE int sqlite3CreateFunc(
116122  sqlite3 *db,
116123  const char *zFunctionName,
116124  int nArg,
116125  int enc,
116126  void *pUserData,
116127  void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
116128  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
116129  void (*xFinal)(sqlite3_context*),
116130  FuncDestructor *pDestructor
116131){
116132  FuncDef *p;
116133  int nName;
116134
116135  assert( sqlite3_mutex_held(db->mutex) );
116136  if( zFunctionName==0 ||
116137      (xFunc && (xFinal || xStep)) ||
116138      (!xFunc && (xFinal && !xStep)) ||
116139      (!xFunc && (!xFinal && xStep)) ||
116140      (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
116141      (255<(nName = sqlite3Strlen30( zFunctionName))) ){
116142    return SQLITE_MISUSE_BKPT;
116143  }
116144
116145#ifndef SQLITE_OMIT_UTF16
116146  /* If SQLITE_UTF16 is specified as the encoding type, transform this
116147  ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
116148  ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
116149  **
116150  ** If SQLITE_ANY is specified, add three versions of the function
116151  ** to the hash table.
116152  */
116153  if( enc==SQLITE_UTF16 ){
116154    enc = SQLITE_UTF16NATIVE;
116155  }else if( enc==SQLITE_ANY ){
116156    int rc;
116157    rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
116158         pUserData, xFunc, xStep, xFinal, pDestructor);
116159    if( rc==SQLITE_OK ){
116160      rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
116161          pUserData, xFunc, xStep, xFinal, pDestructor);
116162    }
116163    if( rc!=SQLITE_OK ){
116164      return rc;
116165    }
116166    enc = SQLITE_UTF16BE;
116167  }
116168#else
116169  enc = SQLITE_UTF8;
116170#endif
116171
116172  /* Check if an existing function is being overridden or deleted. If so,
116173  ** and there are active VMs, then return SQLITE_BUSY. If a function
116174  ** is being overridden/deleted but there are no active VMs, allow the
116175  ** operation to continue but invalidate all precompiled statements.
116176  */
116177  p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
116178  if( p && p->iPrefEnc==enc && p->nArg==nArg ){
116179    if( db->activeVdbeCnt ){
116180      sqlite3Error(db, SQLITE_BUSY,
116181        "unable to delete/modify user-function due to active statements");
116182      assert( !db->mallocFailed );
116183      return SQLITE_BUSY;
116184    }else{
116185      sqlite3ExpirePreparedStatements(db);
116186    }
116187  }
116188
116189  p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
116190  assert(p || db->mallocFailed);
116191  if( !p ){
116192    return SQLITE_NOMEM;
116193  }
116194
116195  /* If an older version of the function with a configured destructor is
116196  ** being replaced invoke the destructor function here. */
116197  functionDestroy(db, p);
116198
116199  if( pDestructor ){
116200    pDestructor->nRef++;
116201  }
116202  p->pDestructor = pDestructor;
116203  p->flags = 0;
116204  p->xFunc = xFunc;
116205  p->xStep = xStep;
116206  p->xFinalize = xFinal;
116207  p->pUserData = pUserData;
116208  p->nArg = (u16)nArg;
116209  return SQLITE_OK;
116210}
116211
116212/*
116213** Create new user functions.
116214*/
116215SQLITE_API int sqlite3_create_function(
116216  sqlite3 *db,
116217  const char *zFunc,
116218  int nArg,
116219  int enc,
116220  void *p,
116221  void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
116222  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
116223  void (*xFinal)(sqlite3_context*)
116224){
116225  return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
116226                                    xFinal, 0);
116227}
116228
116229SQLITE_API int sqlite3_create_function_v2(
116230  sqlite3 *db,
116231  const char *zFunc,
116232  int nArg,
116233  int enc,
116234  void *p,
116235  void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
116236  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
116237  void (*xFinal)(sqlite3_context*),
116238  void (*xDestroy)(void *)
116239){
116240  int rc = SQLITE_ERROR;
116241  FuncDestructor *pArg = 0;
116242  sqlite3_mutex_enter(db->mutex);
116243  if( xDestroy ){
116244    pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
116245    if( !pArg ){
116246      xDestroy(p);
116247      goto out;
116248    }
116249    pArg->xDestroy = xDestroy;
116250    pArg->pUserData = p;
116251  }
116252  rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
116253  if( pArg && pArg->nRef==0 ){
116254    assert( rc!=SQLITE_OK );
116255    xDestroy(p);
116256    sqlite3DbFree(db, pArg);
116257  }
116258
116259 out:
116260  rc = sqlite3ApiExit(db, rc);
116261  sqlite3_mutex_leave(db->mutex);
116262  return rc;
116263}
116264
116265#ifndef SQLITE_OMIT_UTF16
116266SQLITE_API int sqlite3_create_function16(
116267  sqlite3 *db,
116268  const void *zFunctionName,
116269  int nArg,
116270  int eTextRep,
116271  void *p,
116272  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
116273  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
116274  void (*xFinal)(sqlite3_context*)
116275){
116276  int rc;
116277  char *zFunc8;
116278  sqlite3_mutex_enter(db->mutex);
116279  assert( !db->mallocFailed );
116280  zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
116281  rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
116282  sqlite3DbFree(db, zFunc8);
116283  rc = sqlite3ApiExit(db, rc);
116284  sqlite3_mutex_leave(db->mutex);
116285  return rc;
116286}
116287#endif
116288
116289
116290/*
116291** Declare that a function has been overloaded by a virtual table.
116292**
116293** If the function already exists as a regular global function, then
116294** this routine is a no-op.  If the function does not exist, then create
116295** a new one that always throws a run-time error.
116296**
116297** When virtual tables intend to provide an overloaded function, they
116298** should call this routine to make sure the global function exists.
116299** A global function must exist in order for name resolution to work
116300** properly.
116301*/
116302SQLITE_API int sqlite3_overload_function(
116303  sqlite3 *db,
116304  const char *zName,
116305  int nArg
116306){
116307  int nName = sqlite3Strlen30(zName);
116308  int rc = SQLITE_OK;
116309  sqlite3_mutex_enter(db->mutex);
116310  if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
116311    rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
116312                           0, sqlite3InvalidFunction, 0, 0, 0);
116313  }
116314  rc = sqlite3ApiExit(db, rc);
116315  sqlite3_mutex_leave(db->mutex);
116316  return rc;
116317}
116318
116319#ifndef SQLITE_OMIT_TRACE
116320/*
116321** Register a trace function.  The pArg from the previously registered trace
116322** is returned.
116323**
116324** A NULL trace function means that no tracing is executes.  A non-NULL
116325** trace is a pointer to a function that is invoked at the start of each
116326** SQL statement.
116327*/
116328SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
116329  void *pOld;
116330  sqlite3_mutex_enter(db->mutex);
116331  pOld = db->pTraceArg;
116332  db->xTrace = xTrace;
116333  db->pTraceArg = pArg;
116334  sqlite3_mutex_leave(db->mutex);
116335  return pOld;
116336}
116337/*
116338** Register a profile function.  The pArg from the previously registered
116339** profile function is returned.
116340**
116341** A NULL profile function means that no profiling is executes.  A non-NULL
116342** profile is a pointer to a function that is invoked at the conclusion of
116343** each SQL statement that is run.
116344*/
116345SQLITE_API void *sqlite3_profile(
116346  sqlite3 *db,
116347  void (*xProfile)(void*,const char*,sqlite_uint64),
116348  void *pArg
116349){
116350  void *pOld;
116351  sqlite3_mutex_enter(db->mutex);
116352  pOld = db->pProfileArg;
116353  db->xProfile = xProfile;
116354  db->pProfileArg = pArg;
116355  sqlite3_mutex_leave(db->mutex);
116356  return pOld;
116357}
116358#endif /* SQLITE_OMIT_TRACE */
116359
116360/*
116361** Register a function to be invoked when a transaction commits.
116362** If the invoked function returns non-zero, then the commit becomes a
116363** rollback.
116364*/
116365SQLITE_API void *sqlite3_commit_hook(
116366  sqlite3 *db,              /* Attach the hook to this database */
116367  int (*xCallback)(void*),  /* Function to invoke on each commit */
116368  void *pArg                /* Argument to the function */
116369){
116370  void *pOld;
116371  sqlite3_mutex_enter(db->mutex);
116372  pOld = db->pCommitArg;
116373  db->xCommitCallback = xCallback;
116374  db->pCommitArg = pArg;
116375  sqlite3_mutex_leave(db->mutex);
116376  return pOld;
116377}
116378
116379/*
116380** Register a callback to be invoked each time a row is updated,
116381** inserted or deleted using this database connection.
116382*/
116383SQLITE_API void *sqlite3_update_hook(
116384  sqlite3 *db,              /* Attach the hook to this database */
116385  void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
116386  void *pArg                /* Argument to the function */
116387){
116388  void *pRet;
116389  sqlite3_mutex_enter(db->mutex);
116390  pRet = db->pUpdateArg;
116391  db->xUpdateCallback = xCallback;
116392  db->pUpdateArg = pArg;
116393  sqlite3_mutex_leave(db->mutex);
116394  return pRet;
116395}
116396
116397/*
116398** Register a callback to be invoked each time a transaction is rolled
116399** back by this database connection.
116400*/
116401SQLITE_API void *sqlite3_rollback_hook(
116402  sqlite3 *db,              /* Attach the hook to this database */
116403  void (*xCallback)(void*), /* Callback function */
116404  void *pArg                /* Argument to the function */
116405){
116406  void *pRet;
116407  sqlite3_mutex_enter(db->mutex);
116408  pRet = db->pRollbackArg;
116409  db->xRollbackCallback = xCallback;
116410  db->pRollbackArg = pArg;
116411  sqlite3_mutex_leave(db->mutex);
116412  return pRet;
116413}
116414
116415#ifndef SQLITE_OMIT_WAL
116416/*
116417** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
116418** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
116419** is greater than sqlite3.pWalArg cast to an integer (the value configured by
116420** wal_autocheckpoint()).
116421*/
116422SQLITE_PRIVATE int sqlite3WalDefaultHook(
116423  void *pClientData,     /* Argument */
116424  sqlite3 *db,           /* Connection */
116425  const char *zDb,       /* Database */
116426  int nFrame             /* Size of WAL */
116427){
116428  if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
116429    sqlite3BeginBenignMalloc();
116430    sqlite3_wal_checkpoint(db, zDb);
116431    sqlite3EndBenignMalloc();
116432  }
116433  return SQLITE_OK;
116434}
116435#endif /* SQLITE_OMIT_WAL */
116436
116437/*
116438** Configure an sqlite3_wal_hook() callback to automatically checkpoint
116439** a database after committing a transaction if there are nFrame or
116440** more frames in the log file. Passing zero or a negative value as the
116441** nFrame parameter disables automatic checkpoints entirely.
116442**
116443** The callback registered by this function replaces any existing callback
116444** registered using sqlite3_wal_hook(). Likewise, registering a callback
116445** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
116446** configured by this function.
116447*/
116448SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
116449#ifdef SQLITE_OMIT_WAL
116450  UNUSED_PARAMETER(db);
116451  UNUSED_PARAMETER(nFrame);
116452#else
116453  if( nFrame>0 ){
116454    sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
116455  }else{
116456    sqlite3_wal_hook(db, 0, 0);
116457  }
116458#endif
116459  return SQLITE_OK;
116460}
116461
116462/*
116463** Register a callback to be invoked each time a transaction is written
116464** into the write-ahead-log by this database connection.
116465*/
116466SQLITE_API void *sqlite3_wal_hook(
116467  sqlite3 *db,                    /* Attach the hook to this db handle */
116468  int(*xCallback)(void *, sqlite3*, const char*, int),
116469  void *pArg                      /* First argument passed to xCallback() */
116470){
116471#ifndef SQLITE_OMIT_WAL
116472  void *pRet;
116473  sqlite3_mutex_enter(db->mutex);
116474  pRet = db->pWalArg;
116475  db->xWalCallback = xCallback;
116476  db->pWalArg = pArg;
116477  sqlite3_mutex_leave(db->mutex);
116478  return pRet;
116479#else
116480  return 0;
116481#endif
116482}
116483
116484/*
116485** Checkpoint database zDb.
116486*/
116487SQLITE_API int sqlite3_wal_checkpoint_v2(
116488  sqlite3 *db,                    /* Database handle */
116489  const char *zDb,                /* Name of attached database (or NULL) */
116490  int eMode,                      /* SQLITE_CHECKPOINT_* value */
116491  int *pnLog,                     /* OUT: Size of WAL log in frames */
116492  int *pnCkpt                     /* OUT: Total number of frames checkpointed */
116493){
116494#ifdef SQLITE_OMIT_WAL
116495  return SQLITE_OK;
116496#else
116497  int rc;                         /* Return code */
116498  int iDb = SQLITE_MAX_ATTACHED;  /* sqlite3.aDb[] index of db to checkpoint */
116499
116500  /* Initialize the output variables to -1 in case an error occurs. */
116501  if( pnLog ) *pnLog = -1;
116502  if( pnCkpt ) *pnCkpt = -1;
116503
116504  assert( SQLITE_CHECKPOINT_FULL>SQLITE_CHECKPOINT_PASSIVE );
116505  assert( SQLITE_CHECKPOINT_FULL<SQLITE_CHECKPOINT_RESTART );
116506  assert( SQLITE_CHECKPOINT_PASSIVE+2==SQLITE_CHECKPOINT_RESTART );
116507  if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_RESTART ){
116508    return SQLITE_MISUSE;
116509  }
116510
116511  sqlite3_mutex_enter(db->mutex);
116512  if( zDb && zDb[0] ){
116513    iDb = sqlite3FindDbName(db, zDb);
116514  }
116515  if( iDb<0 ){
116516    rc = SQLITE_ERROR;
116517    sqlite3Error(db, SQLITE_ERROR, "unknown database: %s", zDb);
116518  }else{
116519    rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
116520    sqlite3Error(db, rc, 0);
116521  }
116522  rc = sqlite3ApiExit(db, rc);
116523  sqlite3_mutex_leave(db->mutex);
116524  return rc;
116525#endif
116526}
116527
116528
116529/*
116530** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
116531** to contains a zero-length string, all attached databases are
116532** checkpointed.
116533*/
116534SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
116535  return sqlite3_wal_checkpoint_v2(db, zDb, SQLITE_CHECKPOINT_PASSIVE, 0, 0);
116536}
116537
116538#ifndef SQLITE_OMIT_WAL
116539/*
116540** Run a checkpoint on database iDb. This is a no-op if database iDb is
116541** not currently open in WAL mode.
116542**
116543** If a transaction is open on the database being checkpointed, this
116544** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
116545** an error occurs while running the checkpoint, an SQLite error code is
116546** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
116547**
116548** The mutex on database handle db should be held by the caller. The mutex
116549** associated with the specific b-tree being checkpointed is taken by
116550** this function while the checkpoint is running.
116551**
116552** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
116553** checkpointed. If an error is encountered it is returned immediately -
116554** no attempt is made to checkpoint any remaining databases.
116555**
116556** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
116557*/
116558SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
116559  int rc = SQLITE_OK;             /* Return code */
116560  int i;                          /* Used to iterate through attached dbs */
116561  int bBusy = 0;                  /* True if SQLITE_BUSY has been encountered */
116562
116563  assert( sqlite3_mutex_held(db->mutex) );
116564  assert( !pnLog || *pnLog==-1 );
116565  assert( !pnCkpt || *pnCkpt==-1 );
116566
116567  for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
116568    if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
116569      rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
116570      pnLog = 0;
116571      pnCkpt = 0;
116572      if( rc==SQLITE_BUSY ){
116573        bBusy = 1;
116574        rc = SQLITE_OK;
116575      }
116576    }
116577  }
116578
116579  return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
116580}
116581#endif /* SQLITE_OMIT_WAL */
116582
116583/*
116584** This function returns true if main-memory should be used instead of
116585** a temporary file for transient pager files and statement journals.
116586** The value returned depends on the value of db->temp_store (runtime
116587** parameter) and the compile time value of SQLITE_TEMP_STORE. The
116588** following table describes the relationship between these two values
116589** and this functions return value.
116590**
116591**   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
116592**   -----------------     --------------     ------------------------------
116593**   0                     any                file      (return 0)
116594**   1                     1                  file      (return 0)
116595**   1                     2                  memory    (return 1)
116596**   1                     0                  file      (return 0)
116597**   2                     1                  file      (return 0)
116598**   2                     2                  memory    (return 1)
116599**   2                     0                  memory    (return 1)
116600**   3                     any                memory    (return 1)
116601*/
116602SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
116603#if SQLITE_TEMP_STORE==1
116604  return ( db->temp_store==2 );
116605#endif
116606#if SQLITE_TEMP_STORE==2
116607  return ( db->temp_store!=1 );
116608#endif
116609#if SQLITE_TEMP_STORE==3
116610  return 1;
116611#endif
116612#if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
116613  return 0;
116614#endif
116615}
116616
116617/*
116618** Return UTF-8 encoded English language explanation of the most recent
116619** error.
116620*/
116621SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
116622  const char *z;
116623  if( !db ){
116624    return sqlite3ErrStr(SQLITE_NOMEM);
116625  }
116626  if( !sqlite3SafetyCheckSickOrOk(db) ){
116627    return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
116628  }
116629  sqlite3_mutex_enter(db->mutex);
116630  if( db->mallocFailed ){
116631    z = sqlite3ErrStr(SQLITE_NOMEM);
116632  }else{
116633    z = (char*)sqlite3_value_text(db->pErr);
116634    assert( !db->mallocFailed );
116635    if( z==0 ){
116636      z = sqlite3ErrStr(db->errCode);
116637    }
116638  }
116639  sqlite3_mutex_leave(db->mutex);
116640  return z;
116641}
116642
116643#ifndef SQLITE_OMIT_UTF16
116644/*
116645** Return UTF-16 encoded English language explanation of the most recent
116646** error.
116647*/
116648SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
116649  static const u16 outOfMem[] = {
116650    'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
116651  };
116652  static const u16 misuse[] = {
116653    'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
116654    'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
116655    'c', 'a', 'l', 'l', 'e', 'd', ' ',
116656    'o', 'u', 't', ' ',
116657    'o', 'f', ' ',
116658    's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
116659  };
116660
116661  const void *z;
116662  if( !db ){
116663    return (void *)outOfMem;
116664  }
116665  if( !sqlite3SafetyCheckSickOrOk(db) ){
116666    return (void *)misuse;
116667  }
116668  sqlite3_mutex_enter(db->mutex);
116669  if( db->mallocFailed ){
116670    z = (void *)outOfMem;
116671  }else{
116672    z = sqlite3_value_text16(db->pErr);
116673    if( z==0 ){
116674      sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
116675           SQLITE_UTF8, SQLITE_STATIC);
116676      z = sqlite3_value_text16(db->pErr);
116677    }
116678    /* A malloc() may have failed within the call to sqlite3_value_text16()
116679    ** above. If this is the case, then the db->mallocFailed flag needs to
116680    ** be cleared before returning. Do this directly, instead of via
116681    ** sqlite3ApiExit(), to avoid setting the database handle error message.
116682    */
116683    db->mallocFailed = 0;
116684  }
116685  sqlite3_mutex_leave(db->mutex);
116686  return z;
116687}
116688#endif /* SQLITE_OMIT_UTF16 */
116689
116690/*
116691** Return the most recent error code generated by an SQLite routine. If NULL is
116692** passed to this function, we assume a malloc() failed during sqlite3_open().
116693*/
116694SQLITE_API int sqlite3_errcode(sqlite3 *db){
116695  if( db && !sqlite3SafetyCheckSickOrOk(db) ){
116696    return SQLITE_MISUSE_BKPT;
116697  }
116698  if( !db || db->mallocFailed ){
116699    return SQLITE_NOMEM;
116700  }
116701  return db->errCode & db->errMask;
116702}
116703SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
116704  if( db && !sqlite3SafetyCheckSickOrOk(db) ){
116705    return SQLITE_MISUSE_BKPT;
116706  }
116707  if( !db || db->mallocFailed ){
116708    return SQLITE_NOMEM;
116709  }
116710  return db->errCode;
116711}
116712
116713/*
116714** Return a string that describes the kind of error specified in the
116715** argument.  For now, this simply calls the internal sqlite3ErrStr()
116716** function.
116717*/
116718SQLITE_API const char *sqlite3_errstr(int rc){
116719  return sqlite3ErrStr(rc);
116720}
116721
116722/*
116723** Create a new collating function for database "db".  The name is zName
116724** and the encoding is enc.
116725*/
116726static int createCollation(
116727  sqlite3* db,
116728  const char *zName,
116729  u8 enc,
116730  void* pCtx,
116731  int(*xCompare)(void*,int,const void*,int,const void*),
116732  void(*xDel)(void*)
116733){
116734  CollSeq *pColl;
116735  int enc2;
116736  int nName = sqlite3Strlen30(zName);
116737
116738  assert( sqlite3_mutex_held(db->mutex) );
116739
116740  /* If SQLITE_UTF16 is specified as the encoding type, transform this
116741  ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
116742  ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
116743  */
116744  enc2 = enc;
116745  testcase( enc2==SQLITE_UTF16 );
116746  testcase( enc2==SQLITE_UTF16_ALIGNED );
116747  if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
116748    enc2 = SQLITE_UTF16NATIVE;
116749  }
116750  if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
116751    return SQLITE_MISUSE_BKPT;
116752  }
116753
116754  /* Check if this call is removing or replacing an existing collation
116755  ** sequence. If so, and there are active VMs, return busy. If there
116756  ** are no active VMs, invalidate any pre-compiled statements.
116757  */
116758  pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
116759  if( pColl && pColl->xCmp ){
116760    if( db->activeVdbeCnt ){
116761      sqlite3Error(db, SQLITE_BUSY,
116762        "unable to delete/modify collation sequence due to active statements");
116763      return SQLITE_BUSY;
116764    }
116765    sqlite3ExpirePreparedStatements(db);
116766
116767    /* If collation sequence pColl was created directly by a call to
116768    ** sqlite3_create_collation, and not generated by synthCollSeq(),
116769    ** then any copies made by synthCollSeq() need to be invalidated.
116770    ** Also, collation destructor - CollSeq.xDel() - function may need
116771    ** to be called.
116772    */
116773    if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
116774      CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
116775      int j;
116776      for(j=0; j<3; j++){
116777        CollSeq *p = &aColl[j];
116778        if( p->enc==pColl->enc ){
116779          if( p->xDel ){
116780            p->xDel(p->pUser);
116781          }
116782          p->xCmp = 0;
116783        }
116784      }
116785    }
116786  }
116787
116788  pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
116789  if( pColl==0 ) return SQLITE_NOMEM;
116790  pColl->xCmp = xCompare;
116791  pColl->pUser = pCtx;
116792  pColl->xDel = xDel;
116793  pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
116794  sqlite3Error(db, SQLITE_OK, 0);
116795  return SQLITE_OK;
116796}
116797
116798
116799/*
116800** This array defines hard upper bounds on limit values.  The
116801** initializer must be kept in sync with the SQLITE_LIMIT_*
116802** #defines in sqlite3.h.
116803*/
116804static const int aHardLimit[] = {
116805  SQLITE_MAX_LENGTH,
116806  SQLITE_MAX_SQL_LENGTH,
116807  SQLITE_MAX_COLUMN,
116808  SQLITE_MAX_EXPR_DEPTH,
116809  SQLITE_MAX_COMPOUND_SELECT,
116810  SQLITE_MAX_VDBE_OP,
116811  SQLITE_MAX_FUNCTION_ARG,
116812  SQLITE_MAX_ATTACHED,
116813  SQLITE_MAX_LIKE_PATTERN_LENGTH,
116814  SQLITE_MAX_VARIABLE_NUMBER,
116815  SQLITE_MAX_TRIGGER_DEPTH,
116816};
116817
116818/*
116819** Make sure the hard limits are set to reasonable values
116820*/
116821#if SQLITE_MAX_LENGTH<100
116822# error SQLITE_MAX_LENGTH must be at least 100
116823#endif
116824#if SQLITE_MAX_SQL_LENGTH<100
116825# error SQLITE_MAX_SQL_LENGTH must be at least 100
116826#endif
116827#if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
116828# error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
116829#endif
116830#if SQLITE_MAX_COMPOUND_SELECT<2
116831# error SQLITE_MAX_COMPOUND_SELECT must be at least 2
116832#endif
116833#if SQLITE_MAX_VDBE_OP<40
116834# error SQLITE_MAX_VDBE_OP must be at least 40
116835#endif
116836#if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
116837# error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
116838#endif
116839#if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>62
116840# error SQLITE_MAX_ATTACHED must be between 0 and 62
116841#endif
116842#if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
116843# error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
116844#endif
116845#if SQLITE_MAX_COLUMN>32767
116846# error SQLITE_MAX_COLUMN must not exceed 32767
116847#endif
116848#if SQLITE_MAX_TRIGGER_DEPTH<1
116849# error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
116850#endif
116851
116852
116853/*
116854** Change the value of a limit.  Report the old value.
116855** If an invalid limit index is supplied, report -1.
116856** Make no changes but still report the old value if the
116857** new limit is negative.
116858**
116859** A new lower limit does not shrink existing constructs.
116860** It merely prevents new constructs that exceed the limit
116861** from forming.
116862*/
116863SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
116864  int oldLimit;
116865
116866
116867  /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
116868  ** there is a hard upper bound set at compile-time by a C preprocessor
116869  ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
116870  ** "_MAX_".)
116871  */
116872  assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
116873  assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
116874  assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
116875  assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
116876  assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
116877  assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
116878  assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
116879  assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
116880  assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
116881                                               SQLITE_MAX_LIKE_PATTERN_LENGTH );
116882  assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
116883  assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
116884  assert( SQLITE_LIMIT_TRIGGER_DEPTH==(SQLITE_N_LIMIT-1) );
116885
116886
116887  if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
116888    return -1;
116889  }
116890  oldLimit = db->aLimit[limitId];
116891  if( newLimit>=0 ){                   /* IMP: R-52476-28732 */
116892    if( newLimit>aHardLimit[limitId] ){
116893      newLimit = aHardLimit[limitId];  /* IMP: R-51463-25634 */
116894    }
116895    db->aLimit[limitId] = newLimit;
116896  }
116897  return oldLimit;                     /* IMP: R-53341-35419 */
116898}
116899
116900/*
116901** This function is used to parse both URIs and non-URI filenames passed by the
116902** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
116903** URIs specified as part of ATTACH statements.
116904**
116905** The first argument to this function is the name of the VFS to use (or
116906** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
116907** query parameter. The second argument contains the URI (or non-URI filename)
116908** itself. When this function is called the *pFlags variable should contain
116909** the default flags to open the database handle with. The value stored in
116910** *pFlags may be updated before returning if the URI filename contains
116911** "cache=xxx" or "mode=xxx" query parameters.
116912**
116913** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
116914** the VFS that should be used to open the database file. *pzFile is set to
116915** point to a buffer containing the name of the file to open. It is the
116916** responsibility of the caller to eventually call sqlite3_free() to release
116917** this buffer.
116918**
116919** If an error occurs, then an SQLite error code is returned and *pzErrMsg
116920** may be set to point to a buffer containing an English language error
116921** message. It is the responsibility of the caller to eventually release
116922** this buffer by calling sqlite3_free().
116923*/
116924SQLITE_PRIVATE int sqlite3ParseUri(
116925  const char *zDefaultVfs,        /* VFS to use if no "vfs=xxx" query option */
116926  const char *zUri,               /* Nul-terminated URI to parse */
116927  unsigned int *pFlags,           /* IN/OUT: SQLITE_OPEN_XXX flags */
116928  sqlite3_vfs **ppVfs,            /* OUT: VFS to use */
116929  char **pzFile,                  /* OUT: Filename component of URI */
116930  char **pzErrMsg                 /* OUT: Error message (if rc!=SQLITE_OK) */
116931){
116932  int rc = SQLITE_OK;
116933  unsigned int flags = *pFlags;
116934  const char *zVfs = zDefaultVfs;
116935  char *zFile;
116936  char c;
116937  int nUri = sqlite3Strlen30(zUri);
116938
116939  assert( *pzErrMsg==0 );
116940
116941  if( ((flags & SQLITE_OPEN_URI) || sqlite3GlobalConfig.bOpenUri)
116942   && nUri>=5 && memcmp(zUri, "file:", 5)==0
116943  ){
116944    char *zOpt;
116945    int eState;                   /* Parser state when parsing URI */
116946    int iIn;                      /* Input character index */
116947    int iOut = 0;                 /* Output character index */
116948    int nByte = nUri+2;           /* Bytes of space to allocate */
116949
116950    /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
116951    ** method that there may be extra parameters following the file-name.  */
116952    flags |= SQLITE_OPEN_URI;
116953
116954    for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
116955    zFile = sqlite3_malloc(nByte);
116956    if( !zFile ) return SQLITE_NOMEM;
116957
116958    /* Discard the scheme and authority segments of the URI. */
116959    if( zUri[5]=='/' && zUri[6]=='/' ){
116960      iIn = 7;
116961      while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
116962
116963      if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
116964        *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
116965            iIn-7, &zUri[7]);
116966        rc = SQLITE_ERROR;
116967        goto parse_uri_out;
116968      }
116969    }else{
116970      iIn = 5;
116971    }
116972
116973    /* Copy the filename and any query parameters into the zFile buffer.
116974    ** Decode %HH escape codes along the way.
116975    **
116976    ** Within this loop, variable eState may be set to 0, 1 or 2, depending
116977    ** on the parsing context. As follows:
116978    **
116979    **   0: Parsing file-name.
116980    **   1: Parsing name section of a name=value query parameter.
116981    **   2: Parsing value section of a name=value query parameter.
116982    */
116983    eState = 0;
116984    while( (c = zUri[iIn])!=0 && c!='#' ){
116985      iIn++;
116986      if( c=='%'
116987       && sqlite3Isxdigit(zUri[iIn])
116988       && sqlite3Isxdigit(zUri[iIn+1])
116989      ){
116990        int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
116991        octet += sqlite3HexToInt(zUri[iIn++]);
116992
116993        assert( octet>=0 && octet<256 );
116994        if( octet==0 ){
116995          /* This branch is taken when "%00" appears within the URI. In this
116996          ** case we ignore all text in the remainder of the path, name or
116997          ** value currently being parsed. So ignore the current character
116998          ** and skip to the next "?", "=" or "&", as appropriate. */
116999          while( (c = zUri[iIn])!=0 && c!='#'
117000              && (eState!=0 || c!='?')
117001              && (eState!=1 || (c!='=' && c!='&'))
117002              && (eState!=2 || c!='&')
117003          ){
117004            iIn++;
117005          }
117006          continue;
117007        }
117008        c = octet;
117009      }else if( eState==1 && (c=='&' || c=='=') ){
117010        if( zFile[iOut-1]==0 ){
117011          /* An empty option name. Ignore this option altogether. */
117012          while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
117013          continue;
117014        }
117015        if( c=='&' ){
117016          zFile[iOut++] = '\0';
117017        }else{
117018          eState = 2;
117019        }
117020        c = 0;
117021      }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
117022        c = 0;
117023        eState = 1;
117024      }
117025      zFile[iOut++] = c;
117026    }
117027    if( eState==1 ) zFile[iOut++] = '\0';
117028    zFile[iOut++] = '\0';
117029    zFile[iOut++] = '\0';
117030
117031    /* Check if there were any options specified that should be interpreted
117032    ** here. Options that are interpreted here include "vfs" and those that
117033    ** correspond to flags that may be passed to the sqlite3_open_v2()
117034    ** method. */
117035    zOpt = &zFile[sqlite3Strlen30(zFile)+1];
117036    while( zOpt[0] ){
117037      int nOpt = sqlite3Strlen30(zOpt);
117038      char *zVal = &zOpt[nOpt+1];
117039      int nVal = sqlite3Strlen30(zVal);
117040
117041      if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
117042        zVfs = zVal;
117043      }else{
117044        struct OpenMode {
117045          const char *z;
117046          int mode;
117047        } *aMode = 0;
117048        char *zModeType = 0;
117049        int mask = 0;
117050        int limit = 0;
117051
117052        if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
117053          static struct OpenMode aCacheMode[] = {
117054            { "shared",  SQLITE_OPEN_SHAREDCACHE },
117055            { "private", SQLITE_OPEN_PRIVATECACHE },
117056            { 0, 0 }
117057          };
117058
117059          mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
117060          aMode = aCacheMode;
117061          limit = mask;
117062          zModeType = "cache";
117063        }
117064        if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
117065          static struct OpenMode aOpenMode[] = {
117066            { "ro",  SQLITE_OPEN_READONLY },
117067            { "rw",  SQLITE_OPEN_READWRITE },
117068            { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
117069            { "memory", SQLITE_OPEN_MEMORY },
117070            { 0, 0 }
117071          };
117072
117073          mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
117074                   | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
117075          aMode = aOpenMode;
117076          limit = mask & flags;
117077          zModeType = "access";
117078        }
117079
117080        if( aMode ){
117081          int i;
117082          int mode = 0;
117083          for(i=0; aMode[i].z; i++){
117084            const char *z = aMode[i].z;
117085            if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
117086              mode = aMode[i].mode;
117087              break;
117088            }
117089          }
117090          if( mode==0 ){
117091            *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
117092            rc = SQLITE_ERROR;
117093            goto parse_uri_out;
117094          }
117095          if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
117096            *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
117097                                        zModeType, zVal);
117098            rc = SQLITE_PERM;
117099            goto parse_uri_out;
117100          }
117101          flags = (flags & ~mask) | mode;
117102        }
117103      }
117104
117105      zOpt = &zVal[nVal+1];
117106    }
117107
117108  }else{
117109    zFile = sqlite3_malloc(nUri+2);
117110    if( !zFile ) return SQLITE_NOMEM;
117111    memcpy(zFile, zUri, nUri);
117112    zFile[nUri] = '\0';
117113    zFile[nUri+1] = '\0';
117114    flags &= ~SQLITE_OPEN_URI;
117115  }
117116
117117  *ppVfs = sqlite3_vfs_find(zVfs);
117118  if( *ppVfs==0 ){
117119    *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
117120    rc = SQLITE_ERROR;
117121  }
117122 parse_uri_out:
117123  if( rc!=SQLITE_OK ){
117124    sqlite3_free(zFile);
117125    zFile = 0;
117126  }
117127  *pFlags = flags;
117128  *pzFile = zFile;
117129  return rc;
117130}
117131
117132
117133/*
117134** This routine does the work of opening a database on behalf of
117135** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
117136** is UTF-8 encoded.
117137*/
117138static int openDatabase(
117139  const char *zFilename, /* Database filename UTF-8 encoded */
117140  sqlite3 **ppDb,        /* OUT: Returned database handle */
117141  unsigned int flags,    /* Operational flags */
117142  const char *zVfs       /* Name of the VFS to use */
117143){
117144  sqlite3 *db;                    /* Store allocated handle here */
117145  int rc;                         /* Return code */
117146  int isThreadsafe;               /* True for threadsafe connections */
117147  char *zOpen = 0;                /* Filename argument to pass to BtreeOpen() */
117148  char *zErrMsg = 0;              /* Error message from sqlite3ParseUri() */
117149
117150  *ppDb = 0;
117151#ifndef SQLITE_OMIT_AUTOINIT
117152  rc = sqlite3_initialize();
117153  if( rc ) return rc;
117154#endif
117155
117156  /* Only allow sensible combinations of bits in the flags argument.
117157  ** Throw an error if any non-sense combination is used.  If we
117158  ** do not block illegal combinations here, it could trigger
117159  ** assert() statements in deeper layers.  Sensible combinations
117160  ** are:
117161  **
117162  **  1:  SQLITE_OPEN_READONLY
117163  **  2:  SQLITE_OPEN_READWRITE
117164  **  6:  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
117165  */
117166  assert( SQLITE_OPEN_READONLY  == 0x01 );
117167  assert( SQLITE_OPEN_READWRITE == 0x02 );
117168  assert( SQLITE_OPEN_CREATE    == 0x04 );
117169  testcase( (1<<(flags&7))==0x02 ); /* READONLY */
117170  testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
117171  testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
117172  if( ((1<<(flags&7)) & 0x46)==0 ) return SQLITE_MISUSE_BKPT;
117173
117174  if( sqlite3GlobalConfig.bCoreMutex==0 ){
117175    isThreadsafe = 0;
117176  }else if( flags & SQLITE_OPEN_NOMUTEX ){
117177    isThreadsafe = 0;
117178  }else if( flags & SQLITE_OPEN_FULLMUTEX ){
117179    isThreadsafe = 1;
117180  }else{
117181    isThreadsafe = sqlite3GlobalConfig.bFullMutex;
117182  }
117183  if( flags & SQLITE_OPEN_PRIVATECACHE ){
117184    flags &= ~SQLITE_OPEN_SHAREDCACHE;
117185  }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
117186    flags |= SQLITE_OPEN_SHAREDCACHE;
117187  }
117188
117189  /* Remove harmful bits from the flags parameter
117190  **
117191  ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
117192  ** dealt with in the previous code block.  Besides these, the only
117193  ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
117194  ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
117195  ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits.  Silently mask
117196  ** off all other flags.
117197  */
117198  flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
117199               SQLITE_OPEN_EXCLUSIVE |
117200               SQLITE_OPEN_MAIN_DB |
117201               SQLITE_OPEN_TEMP_DB |
117202               SQLITE_OPEN_TRANSIENT_DB |
117203               SQLITE_OPEN_MAIN_JOURNAL |
117204               SQLITE_OPEN_TEMP_JOURNAL |
117205               SQLITE_OPEN_SUBJOURNAL |
117206               SQLITE_OPEN_MASTER_JOURNAL |
117207               SQLITE_OPEN_NOMUTEX |
117208               SQLITE_OPEN_FULLMUTEX |
117209               SQLITE_OPEN_WAL
117210             );
117211
117212  /* Allocate the sqlite data structure */
117213  db = sqlite3MallocZero( sizeof(sqlite3) );
117214  if( db==0 ) goto opendb_out;
117215  if( isThreadsafe ){
117216    db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
117217    if( db->mutex==0 ){
117218      sqlite3_free(db);
117219      db = 0;
117220      goto opendb_out;
117221    }
117222  }
117223  sqlite3_mutex_enter(db->mutex);
117224  db->errMask = 0xff;
117225  db->nDb = 2;
117226  db->magic = SQLITE_MAGIC_BUSY;
117227  db->aDb = db->aDbStatic;
117228
117229  assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
117230  memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
117231  db->autoCommit = 1;
117232  db->nextAutovac = -1;
117233  db->szMmap = sqlite3GlobalConfig.szMmap;
117234  db->nextPagesize = 0;
117235  db->flags |= SQLITE_ShortColNames | SQLITE_AutoIndex | SQLITE_EnableTrigger
117236#if SQLITE_DEFAULT_FILE_FORMAT<4
117237                 | SQLITE_LegacyFileFmt
117238#endif
117239#ifdef SQLITE_ENABLE_LOAD_EXTENSION
117240                 | SQLITE_LoadExtension
117241#endif
117242#if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
117243                 | SQLITE_RecTriggers
117244#endif
117245#if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
117246                 | SQLITE_ForeignKeys
117247#endif
117248      ;
117249  sqlite3HashInit(&db->aCollSeq);
117250#ifndef SQLITE_OMIT_VIRTUALTABLE
117251  sqlite3HashInit(&db->aModule);
117252#endif
117253
117254  /* Add the default collation sequence BINARY. BINARY works for both UTF-8
117255  ** and UTF-16, so add a version for each to avoid any unnecessary
117256  ** conversions. The only error that can occur here is a malloc() failure.
117257  */
117258  createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0);
117259  createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0);
117260  createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0);
117261  createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
117262  if( db->mallocFailed ){
117263    goto opendb_out;
117264  }
117265  db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
117266  assert( db->pDfltColl!=0 );
117267
117268  /* Also add a UTF-8 case-insensitive collation sequence. */
117269  createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
117270
117271  /* Parse the filename/URI argument. */
117272  db->openFlags = flags;
117273  rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
117274  if( rc!=SQLITE_OK ){
117275    if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
117276    sqlite3Error(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
117277    sqlite3_free(zErrMsg);
117278    goto opendb_out;
117279  }
117280
117281  /* Open the backend database driver */
117282  rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
117283                        flags | SQLITE_OPEN_MAIN_DB);
117284  if( rc!=SQLITE_OK ){
117285    if( rc==SQLITE_IOERR_NOMEM ){
117286      rc = SQLITE_NOMEM;
117287    }
117288    sqlite3Error(db, rc, 0);
117289    goto opendb_out;
117290  }
117291  db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
117292  db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
117293
117294
117295  /* The default safety_level for the main database is 'full'; for the temp
117296  ** database it is 'NONE'. This matches the pager layer defaults.
117297  */
117298  db->aDb[0].zName = "main";
117299  db->aDb[0].safety_level = 3;
117300  db->aDb[1].zName = "temp";
117301  db->aDb[1].safety_level = 1;
117302
117303  db->magic = SQLITE_MAGIC_OPEN;
117304  if( db->mallocFailed ){
117305    goto opendb_out;
117306  }
117307
117308  /* Register all built-in functions, but do not attempt to read the
117309  ** database schema yet. This is delayed until the first time the database
117310  ** is accessed.
117311  */
117312  sqlite3Error(db, SQLITE_OK, 0);
117313  sqlite3RegisterBuiltinFunctions(db);
117314
117315  /* Load automatic extensions - extensions that have been registered
117316  ** using the sqlite3_automatic_extension() API.
117317  */
117318  rc = sqlite3_errcode(db);
117319  if( rc==SQLITE_OK ){
117320    sqlite3AutoLoadExtensions(db);
117321    rc = sqlite3_errcode(db);
117322    if( rc!=SQLITE_OK ){
117323      goto opendb_out;
117324    }
117325  }
117326
117327#ifdef SQLITE_ENABLE_FTS1
117328  if( !db->mallocFailed ){
117329    extern int sqlite3Fts1Init(sqlite3*);
117330    rc = sqlite3Fts1Init(db);
117331  }
117332#endif
117333
117334#ifdef SQLITE_ENABLE_FTS2
117335  if( !db->mallocFailed && rc==SQLITE_OK ){
117336    extern int sqlite3Fts2Init(sqlite3*);
117337    rc = sqlite3Fts2Init(db);
117338  }
117339#endif
117340
117341#ifdef SQLITE_ENABLE_FTS3
117342  if( !db->mallocFailed && rc==SQLITE_OK ){
117343    rc = sqlite3Fts3Init(db);
117344  }
117345#endif
117346
117347#ifdef SQLITE_ENABLE_ICU
117348  if( !db->mallocFailed && rc==SQLITE_OK ){
117349    rc = sqlite3IcuInit(db);
117350  }
117351#endif
117352
117353#ifdef SQLITE_ENABLE_RTREE
117354  if( !db->mallocFailed && rc==SQLITE_OK){
117355    rc = sqlite3RtreeInit(db);
117356  }
117357#endif
117358
117359  sqlite3Error(db, rc, 0);
117360
117361  /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
117362  ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
117363  ** mode.  Doing nothing at all also makes NORMAL the default.
117364  */
117365#ifdef SQLITE_DEFAULT_LOCKING_MODE
117366  db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
117367  sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
117368                          SQLITE_DEFAULT_LOCKING_MODE);
117369#endif
117370
117371  /* Enable the lookaside-malloc subsystem */
117372  setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
117373                        sqlite3GlobalConfig.nLookaside);
117374
117375  sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
117376
117377opendb_out:
117378  sqlite3_free(zOpen);
117379  if( db ){
117380    assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
117381    sqlite3_mutex_leave(db->mutex);
117382  }
117383  rc = sqlite3_errcode(db);
117384  assert( db!=0 || rc==SQLITE_NOMEM );
117385  if( rc==SQLITE_NOMEM ){
117386    sqlite3_close(db);
117387    db = 0;
117388  }else if( rc!=SQLITE_OK ){
117389    db->magic = SQLITE_MAGIC_SICK;
117390  }
117391  *ppDb = db;
117392#ifdef SQLITE_ENABLE_SQLLOG
117393  if( sqlite3GlobalConfig.xSqllog ){
117394    /* Opening a db handle. Fourth parameter is passed 0. */
117395    void *pArg = sqlite3GlobalConfig.pSqllogArg;
117396    sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
117397  }
117398#endif
117399  return sqlite3ApiExit(0, rc);
117400}
117401
117402/*
117403** Open a new database handle.
117404*/
117405SQLITE_API int sqlite3_open(
117406  const char *zFilename,
117407  sqlite3 **ppDb
117408){
117409  return openDatabase(zFilename, ppDb,
117410                      SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
117411}
117412SQLITE_API int sqlite3_open_v2(
117413  const char *filename,   /* Database filename (UTF-8) */
117414  sqlite3 **ppDb,         /* OUT: SQLite db handle */
117415  int flags,              /* Flags */
117416  const char *zVfs        /* Name of VFS module to use */
117417){
117418  return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
117419}
117420
117421#ifndef SQLITE_OMIT_UTF16
117422/*
117423** Open a new database handle.
117424*/
117425SQLITE_API int sqlite3_open16(
117426  const void *zFilename,
117427  sqlite3 **ppDb
117428){
117429  char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
117430  sqlite3_value *pVal;
117431  int rc;
117432
117433  assert( zFilename );
117434  assert( ppDb );
117435  *ppDb = 0;
117436#ifndef SQLITE_OMIT_AUTOINIT
117437  rc = sqlite3_initialize();
117438  if( rc ) return rc;
117439#endif
117440  pVal = sqlite3ValueNew(0);
117441  sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
117442  zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
117443  if( zFilename8 ){
117444    rc = openDatabase(zFilename8, ppDb,
117445                      SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
117446    assert( *ppDb || rc==SQLITE_NOMEM );
117447    if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
117448      ENC(*ppDb) = SQLITE_UTF16NATIVE;
117449    }
117450  }else{
117451    rc = SQLITE_NOMEM;
117452  }
117453  sqlite3ValueFree(pVal);
117454
117455  return sqlite3ApiExit(0, rc);
117456}
117457#endif /* SQLITE_OMIT_UTF16 */
117458
117459/*
117460** Register a new collation sequence with the database handle db.
117461*/
117462SQLITE_API int sqlite3_create_collation(
117463  sqlite3* db,
117464  const char *zName,
117465  int enc,
117466  void* pCtx,
117467  int(*xCompare)(void*,int,const void*,int,const void*)
117468){
117469  int rc;
117470  sqlite3_mutex_enter(db->mutex);
117471  assert( !db->mallocFailed );
117472  rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, 0);
117473  rc = sqlite3ApiExit(db, rc);
117474  sqlite3_mutex_leave(db->mutex);
117475  return rc;
117476}
117477
117478/*
117479** Register a new collation sequence with the database handle db.
117480*/
117481SQLITE_API int sqlite3_create_collation_v2(
117482  sqlite3* db,
117483  const char *zName,
117484  int enc,
117485  void* pCtx,
117486  int(*xCompare)(void*,int,const void*,int,const void*),
117487  void(*xDel)(void*)
117488){
117489  int rc;
117490  sqlite3_mutex_enter(db->mutex);
117491  assert( !db->mallocFailed );
117492  rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
117493  rc = sqlite3ApiExit(db, rc);
117494  sqlite3_mutex_leave(db->mutex);
117495  return rc;
117496}
117497
117498#ifndef SQLITE_OMIT_UTF16
117499/*
117500** Register a new collation sequence with the database handle db.
117501*/
117502SQLITE_API int sqlite3_create_collation16(
117503  sqlite3* db,
117504  const void *zName,
117505  int enc,
117506  void* pCtx,
117507  int(*xCompare)(void*,int,const void*,int,const void*)
117508){
117509  int rc = SQLITE_OK;
117510  char *zName8;
117511  sqlite3_mutex_enter(db->mutex);
117512  assert( !db->mallocFailed );
117513  zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
117514  if( zName8 ){
117515    rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
117516    sqlite3DbFree(db, zName8);
117517  }
117518  rc = sqlite3ApiExit(db, rc);
117519  sqlite3_mutex_leave(db->mutex);
117520  return rc;
117521}
117522#endif /* SQLITE_OMIT_UTF16 */
117523
117524/*
117525** Register a collation sequence factory callback with the database handle
117526** db. Replace any previously installed collation sequence factory.
117527*/
117528SQLITE_API int sqlite3_collation_needed(
117529  sqlite3 *db,
117530  void *pCollNeededArg,
117531  void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
117532){
117533  sqlite3_mutex_enter(db->mutex);
117534  db->xCollNeeded = xCollNeeded;
117535  db->xCollNeeded16 = 0;
117536  db->pCollNeededArg = pCollNeededArg;
117537  sqlite3_mutex_leave(db->mutex);
117538  return SQLITE_OK;
117539}
117540
117541#ifndef SQLITE_OMIT_UTF16
117542/*
117543** Register a collation sequence factory callback with the database handle
117544** db. Replace any previously installed collation sequence factory.
117545*/
117546SQLITE_API int sqlite3_collation_needed16(
117547  sqlite3 *db,
117548  void *pCollNeededArg,
117549  void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
117550){
117551  sqlite3_mutex_enter(db->mutex);
117552  db->xCollNeeded = 0;
117553  db->xCollNeeded16 = xCollNeeded16;
117554  db->pCollNeededArg = pCollNeededArg;
117555  sqlite3_mutex_leave(db->mutex);
117556  return SQLITE_OK;
117557}
117558#endif /* SQLITE_OMIT_UTF16 */
117559
117560#ifndef SQLITE_OMIT_DEPRECATED
117561/*
117562** This function is now an anachronism. It used to be used to recover from a
117563** malloc() failure, but SQLite now does this automatically.
117564*/
117565SQLITE_API int sqlite3_global_recover(void){
117566  return SQLITE_OK;
117567}
117568#endif
117569
117570/*
117571** Test to see whether or not the database connection is in autocommit
117572** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
117573** by default.  Autocommit is disabled by a BEGIN statement and reenabled
117574** by the next COMMIT or ROLLBACK.
117575**
117576******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
117577*/
117578SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
117579  return db->autoCommit;
117580}
117581
117582/*
117583** The following routines are subtitutes for constants SQLITE_CORRUPT,
117584** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
117585** constants.  They server two purposes:
117586**
117587**   1.  Serve as a convenient place to set a breakpoint in a debugger
117588**       to detect when version error conditions occurs.
117589**
117590**   2.  Invoke sqlite3_log() to provide the source code location where
117591**       a low-level error is first detected.
117592*/
117593SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
117594  testcase( sqlite3GlobalConfig.xLog!=0 );
117595  sqlite3_log(SQLITE_CORRUPT,
117596              "database corruption at line %d of [%.10s]",
117597              lineno, 20+sqlite3_sourceid());
117598  return SQLITE_CORRUPT;
117599}
117600SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
117601  testcase( sqlite3GlobalConfig.xLog!=0 );
117602  sqlite3_log(SQLITE_MISUSE,
117603              "misuse at line %d of [%.10s]",
117604              lineno, 20+sqlite3_sourceid());
117605  return SQLITE_MISUSE;
117606}
117607SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
117608  testcase( sqlite3GlobalConfig.xLog!=0 );
117609  sqlite3_log(SQLITE_CANTOPEN,
117610              "cannot open file at line %d of [%.10s]",
117611              lineno, 20+sqlite3_sourceid());
117612  return SQLITE_CANTOPEN;
117613}
117614
117615
117616#ifndef SQLITE_OMIT_DEPRECATED
117617/*
117618** This is a convenience routine that makes sure that all thread-specific
117619** data for this thread has been deallocated.
117620**
117621** SQLite no longer uses thread-specific data so this routine is now a
117622** no-op.  It is retained for historical compatibility.
117623*/
117624SQLITE_API void sqlite3_thread_cleanup(void){
117625}
117626#endif
117627
117628/*
117629** Return meta information about a specific column of a database table.
117630** See comment in sqlite3.h (sqlite.h.in) for details.
117631*/
117632#ifdef SQLITE_ENABLE_COLUMN_METADATA
117633SQLITE_API int sqlite3_table_column_metadata(
117634  sqlite3 *db,                /* Connection handle */
117635  const char *zDbName,        /* Database name or NULL */
117636  const char *zTableName,     /* Table name */
117637  const char *zColumnName,    /* Column name */
117638  char const **pzDataType,    /* OUTPUT: Declared data type */
117639  char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
117640  int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
117641  int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
117642  int *pAutoinc               /* OUTPUT: True if column is auto-increment */
117643){
117644  int rc;
117645  char *zErrMsg = 0;
117646  Table *pTab = 0;
117647  Column *pCol = 0;
117648  int iCol;
117649
117650  char const *zDataType = 0;
117651  char const *zCollSeq = 0;
117652  int notnull = 0;
117653  int primarykey = 0;
117654  int autoinc = 0;
117655
117656  /* Ensure the database schema has been loaded */
117657  sqlite3_mutex_enter(db->mutex);
117658  sqlite3BtreeEnterAll(db);
117659  rc = sqlite3Init(db, &zErrMsg);
117660  if( SQLITE_OK!=rc ){
117661    goto error_out;
117662  }
117663
117664  /* Locate the table in question */
117665  pTab = sqlite3FindTable(db, zTableName, zDbName);
117666  if( !pTab || pTab->pSelect ){
117667    pTab = 0;
117668    goto error_out;
117669  }
117670
117671  /* Find the column for which info is requested */
117672  if( sqlite3IsRowid(zColumnName) ){
117673    iCol = pTab->iPKey;
117674    if( iCol>=0 ){
117675      pCol = &pTab->aCol[iCol];
117676    }
117677  }else{
117678    for(iCol=0; iCol<pTab->nCol; iCol++){
117679      pCol = &pTab->aCol[iCol];
117680      if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
117681        break;
117682      }
117683    }
117684    if( iCol==pTab->nCol ){
117685      pTab = 0;
117686      goto error_out;
117687    }
117688  }
117689
117690  /* The following block stores the meta information that will be returned
117691  ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
117692  ** and autoinc. At this point there are two possibilities:
117693  **
117694  **     1. The specified column name was rowid", "oid" or "_rowid_"
117695  **        and there is no explicitly declared IPK column.
117696  **
117697  **     2. The table is not a view and the column name identified an
117698  **        explicitly declared column. Copy meta information from *pCol.
117699  */
117700  if( pCol ){
117701    zDataType = pCol->zType;
117702    zCollSeq = pCol->zColl;
117703    notnull = pCol->notNull!=0;
117704    primarykey  = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
117705    autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
117706  }else{
117707    zDataType = "INTEGER";
117708    primarykey = 1;
117709  }
117710  if( !zCollSeq ){
117711    zCollSeq = "BINARY";
117712  }
117713
117714error_out:
117715  sqlite3BtreeLeaveAll(db);
117716
117717  /* Whether the function call succeeded or failed, set the output parameters
117718  ** to whatever their local counterparts contain. If an error did occur,
117719  ** this has the effect of zeroing all output parameters.
117720  */
117721  if( pzDataType ) *pzDataType = zDataType;
117722  if( pzCollSeq ) *pzCollSeq = zCollSeq;
117723  if( pNotNull ) *pNotNull = notnull;
117724  if( pPrimaryKey ) *pPrimaryKey = primarykey;
117725  if( pAutoinc ) *pAutoinc = autoinc;
117726
117727  if( SQLITE_OK==rc && !pTab ){
117728    sqlite3DbFree(db, zErrMsg);
117729    zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
117730        zColumnName);
117731    rc = SQLITE_ERROR;
117732  }
117733  sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
117734  sqlite3DbFree(db, zErrMsg);
117735  rc = sqlite3ApiExit(db, rc);
117736  sqlite3_mutex_leave(db->mutex);
117737  return rc;
117738}
117739#endif
117740
117741/*
117742** Sleep for a little while.  Return the amount of time slept.
117743*/
117744SQLITE_API int sqlite3_sleep(int ms){
117745  sqlite3_vfs *pVfs;
117746  int rc;
117747  pVfs = sqlite3_vfs_find(0);
117748  if( pVfs==0 ) return 0;
117749
117750  /* This function works in milliseconds, but the underlying OsSleep()
117751  ** API uses microseconds. Hence the 1000's.
117752  */
117753  rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
117754  return rc;
117755}
117756
117757/*
117758** Enable or disable the extended result codes.
117759*/
117760SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
117761  sqlite3_mutex_enter(db->mutex);
117762  db->errMask = onoff ? 0xffffffff : 0xff;
117763  sqlite3_mutex_leave(db->mutex);
117764  return SQLITE_OK;
117765}
117766
117767/*
117768** Invoke the xFileControl method on a particular database.
117769*/
117770SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
117771  int rc = SQLITE_ERROR;
117772  Btree *pBtree;
117773
117774  sqlite3_mutex_enter(db->mutex);
117775  pBtree = sqlite3DbNameToBtree(db, zDbName);
117776  if( pBtree ){
117777    Pager *pPager;
117778    sqlite3_file *fd;
117779    sqlite3BtreeEnter(pBtree);
117780    pPager = sqlite3BtreePager(pBtree);
117781    assert( pPager!=0 );
117782    fd = sqlite3PagerFile(pPager);
117783    assert( fd!=0 );
117784    if( op==SQLITE_FCNTL_FILE_POINTER ){
117785      *(sqlite3_file**)pArg = fd;
117786      rc = SQLITE_OK;
117787    }else if( fd->pMethods ){
117788      rc = sqlite3OsFileControl(fd, op, pArg);
117789    }else{
117790      rc = SQLITE_NOTFOUND;
117791    }
117792    sqlite3BtreeLeave(pBtree);
117793  }
117794  sqlite3_mutex_leave(db->mutex);
117795  return rc;
117796}
117797
117798/*
117799** Interface to the testing logic.
117800*/
117801SQLITE_API int sqlite3_test_control(int op, ...){
117802  int rc = 0;
117803#ifndef SQLITE_OMIT_BUILTIN_TEST
117804  va_list ap;
117805  va_start(ap, op);
117806  switch( op ){
117807
117808    /*
117809    ** Save the current state of the PRNG.
117810    */
117811    case SQLITE_TESTCTRL_PRNG_SAVE: {
117812      sqlite3PrngSaveState();
117813      break;
117814    }
117815
117816    /*
117817    ** Restore the state of the PRNG to the last state saved using
117818    ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
117819    ** this verb acts like PRNG_RESET.
117820    */
117821    case SQLITE_TESTCTRL_PRNG_RESTORE: {
117822      sqlite3PrngRestoreState();
117823      break;
117824    }
117825
117826    /*
117827    ** Reset the PRNG back to its uninitialized state.  The next call
117828    ** to sqlite3_randomness() will reseed the PRNG using a single call
117829    ** to the xRandomness method of the default VFS.
117830    */
117831    case SQLITE_TESTCTRL_PRNG_RESET: {
117832      sqlite3PrngResetState();
117833      break;
117834    }
117835
117836    /*
117837    **  sqlite3_test_control(BITVEC_TEST, size, program)
117838    **
117839    ** Run a test against a Bitvec object of size.  The program argument
117840    ** is an array of integers that defines the test.  Return -1 on a
117841    ** memory allocation error, 0 on success, or non-zero for an error.
117842    ** See the sqlite3BitvecBuiltinTest() for additional information.
117843    */
117844    case SQLITE_TESTCTRL_BITVEC_TEST: {
117845      int sz = va_arg(ap, int);
117846      int *aProg = va_arg(ap, int*);
117847      rc = sqlite3BitvecBuiltinTest(sz, aProg);
117848      break;
117849    }
117850
117851    /*
117852    **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
117853    **
117854    ** Register hooks to call to indicate which malloc() failures
117855    ** are benign.
117856    */
117857    case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
117858      typedef void (*void_function)(void);
117859      void_function xBenignBegin;
117860      void_function xBenignEnd;
117861      xBenignBegin = va_arg(ap, void_function);
117862      xBenignEnd = va_arg(ap, void_function);
117863      sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
117864      break;
117865    }
117866
117867    /*
117868    **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
117869    **
117870    ** Set the PENDING byte to the value in the argument, if X>0.
117871    ** Make no changes if X==0.  Return the value of the pending byte
117872    ** as it existing before this routine was called.
117873    **
117874    ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
117875    ** an incompatible database file format.  Changing the PENDING byte
117876    ** while any database connection is open results in undefined and
117877    ** dileterious behavior.
117878    */
117879    case SQLITE_TESTCTRL_PENDING_BYTE: {
117880      rc = PENDING_BYTE;
117881#ifndef SQLITE_OMIT_WSD
117882      {
117883        unsigned int newVal = va_arg(ap, unsigned int);
117884        if( newVal ) sqlite3PendingByte = newVal;
117885      }
117886#endif
117887      break;
117888    }
117889
117890    /*
117891    **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
117892    **
117893    ** This action provides a run-time test to see whether or not
117894    ** assert() was enabled at compile-time.  If X is true and assert()
117895    ** is enabled, then the return value is true.  If X is true and
117896    ** assert() is disabled, then the return value is zero.  If X is
117897    ** false and assert() is enabled, then the assertion fires and the
117898    ** process aborts.  If X is false and assert() is disabled, then the
117899    ** return value is zero.
117900    */
117901    case SQLITE_TESTCTRL_ASSERT: {
117902      volatile int x = 0;
117903      assert( (x = va_arg(ap,int))!=0 );
117904      rc = x;
117905      break;
117906    }
117907
117908
117909    /*
117910    **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
117911    **
117912    ** This action provides a run-time test to see how the ALWAYS and
117913    ** NEVER macros were defined at compile-time.
117914    **
117915    ** The return value is ALWAYS(X).
117916    **
117917    ** The recommended test is X==2.  If the return value is 2, that means
117918    ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
117919    ** default setting.  If the return value is 1, then ALWAYS() is either
117920    ** hard-coded to true or else it asserts if its argument is false.
117921    ** The first behavior (hard-coded to true) is the case if
117922    ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
117923    ** behavior (assert if the argument to ALWAYS() is false) is the case if
117924    ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
117925    **
117926    ** The run-time test procedure might look something like this:
117927    **
117928    **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
117929    **      // ALWAYS() and NEVER() are no-op pass-through macros
117930    **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
117931    **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
117932    **    }else{
117933    **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
117934    **    }
117935    */
117936    case SQLITE_TESTCTRL_ALWAYS: {
117937      int x = va_arg(ap,int);
117938      rc = ALWAYS(x);
117939      break;
117940    }
117941
117942    /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
117943    **
117944    ** Set the nReserve size to N for the main database on the database
117945    ** connection db.
117946    */
117947    case SQLITE_TESTCTRL_RESERVE: {
117948      sqlite3 *db = va_arg(ap, sqlite3*);
117949      int x = va_arg(ap,int);
117950      sqlite3_mutex_enter(db->mutex);
117951      sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
117952      sqlite3_mutex_leave(db->mutex);
117953      break;
117954    }
117955
117956    /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
117957    **
117958    ** Enable or disable various optimizations for testing purposes.  The
117959    ** argument N is a bitmask of optimizations to be disabled.  For normal
117960    ** operation N should be 0.  The idea is that a test program (like the
117961    ** SQL Logic Test or SLT test module) can run the same SQL multiple times
117962    ** with various optimizations disabled to verify that the same answer
117963    ** is obtained in every case.
117964    */
117965    case SQLITE_TESTCTRL_OPTIMIZATIONS: {
117966      sqlite3 *db = va_arg(ap, sqlite3*);
117967      db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
117968      break;
117969    }
117970
117971#ifdef SQLITE_N_KEYWORD
117972    /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
117973    **
117974    ** If zWord is a keyword recognized by the parser, then return the
117975    ** number of keywords.  Or if zWord is not a keyword, return 0.
117976    **
117977    ** This test feature is only available in the amalgamation since
117978    ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
117979    ** is built using separate source files.
117980    */
117981    case SQLITE_TESTCTRL_ISKEYWORD: {
117982      const char *zWord = va_arg(ap, const char*);
117983      int n = sqlite3Strlen30(zWord);
117984      rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
117985      break;
117986    }
117987#endif
117988
117989    /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
117990    **
117991    ** Pass pFree into sqlite3ScratchFree().
117992    ** If sz>0 then allocate a scratch buffer into pNew.
117993    */
117994    case SQLITE_TESTCTRL_SCRATCHMALLOC: {
117995      void *pFree, **ppNew;
117996      int sz;
117997      sz = va_arg(ap, int);
117998      ppNew = va_arg(ap, void**);
117999      pFree = va_arg(ap, void*);
118000      if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
118001      sqlite3ScratchFree(pFree);
118002      break;
118003    }
118004
118005    /*   sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
118006    **
118007    ** If parameter onoff is non-zero, configure the wrappers so that all
118008    ** subsequent calls to localtime() and variants fail. If onoff is zero,
118009    ** undo this setting.
118010    */
118011    case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
118012      sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
118013      break;
118014    }
118015
118016#if defined(SQLITE_ENABLE_TREE_EXPLAIN)
118017    /*   sqlite3_test_control(SQLITE_TESTCTRL_EXPLAIN_STMT,
118018    **                        sqlite3_stmt*,const char**);
118019    **
118020    ** If compiled with SQLITE_ENABLE_TREE_EXPLAIN, each sqlite3_stmt holds
118021    ** a string that describes the optimized parse tree.  This test-control
118022    ** returns a pointer to that string.
118023    */
118024    case SQLITE_TESTCTRL_EXPLAIN_STMT: {
118025      sqlite3_stmt *pStmt = va_arg(ap, sqlite3_stmt*);
118026      const char **pzRet = va_arg(ap, const char**);
118027      *pzRet = sqlite3VdbeExplanation((Vdbe*)pStmt);
118028      break;
118029    }
118030#endif
118031
118032  }
118033  va_end(ap);
118034#endif /* SQLITE_OMIT_BUILTIN_TEST */
118035  return rc;
118036}
118037
118038/*
118039** This is a utility routine, useful to VFS implementations, that checks
118040** to see if a database file was a URI that contained a specific query
118041** parameter, and if so obtains the value of the query parameter.
118042**
118043** The zFilename argument is the filename pointer passed into the xOpen()
118044** method of a VFS implementation.  The zParam argument is the name of the
118045** query parameter we seek.  This routine returns the value of the zParam
118046** parameter if it exists.  If the parameter does not exist, this routine
118047** returns a NULL pointer.
118048*/
118049SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
118050  if( zFilename==0 ) return 0;
118051  zFilename += sqlite3Strlen30(zFilename) + 1;
118052  while( zFilename[0] ){
118053    int x = strcmp(zFilename, zParam);
118054    zFilename += sqlite3Strlen30(zFilename) + 1;
118055    if( x==0 ) return zFilename;
118056    zFilename += sqlite3Strlen30(zFilename) + 1;
118057  }
118058  return 0;
118059}
118060
118061/*
118062** Return a boolean value for a query parameter.
118063*/
118064SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
118065  const char *z = sqlite3_uri_parameter(zFilename, zParam);
118066  bDflt = bDflt!=0;
118067  return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
118068}
118069
118070/*
118071** Return a 64-bit integer value for a query parameter.
118072*/
118073SQLITE_API sqlite3_int64 sqlite3_uri_int64(
118074  const char *zFilename,    /* Filename as passed to xOpen */
118075  const char *zParam,       /* URI parameter sought */
118076  sqlite3_int64 bDflt       /* return if parameter is missing */
118077){
118078  const char *z = sqlite3_uri_parameter(zFilename, zParam);
118079  sqlite3_int64 v;
118080  if( z && sqlite3Atoi64(z, &v, sqlite3Strlen30(z), SQLITE_UTF8)==SQLITE_OK ){
118081    bDflt = v;
118082  }
118083  return bDflt;
118084}
118085
118086/*
118087** Return the Btree pointer identified by zDbName.  Return NULL if not found.
118088*/
118089SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
118090  int i;
118091  for(i=0; i<db->nDb; i++){
118092    if( db->aDb[i].pBt
118093     && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zName)==0)
118094    ){
118095      return db->aDb[i].pBt;
118096    }
118097  }
118098  return 0;
118099}
118100
118101/*
118102** Return the filename of the database associated with a database
118103** connection.
118104*/
118105SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
118106  Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
118107  return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
118108}
118109
118110/*
118111** Return 1 if database is read-only or 0 if read/write.  Return -1 if
118112** no such database exists.
118113*/
118114SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
118115  Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
118116  return pBt ? sqlite3PagerIsreadonly(sqlite3BtreePager(pBt)) : -1;
118117}
118118
118119/************** End of main.c ************************************************/
118120/************** Begin file notify.c ******************************************/
118121/*
118122** 2009 March 3
118123**
118124** The author disclaims copyright to this source code.  In place of
118125** a legal notice, here is a blessing:
118126**
118127**    May you do good and not evil.
118128**    May you find forgiveness for yourself and forgive others.
118129**    May you share freely, never taking more than you give.
118130**
118131*************************************************************************
118132**
118133** This file contains the implementation of the sqlite3_unlock_notify()
118134** API method and its associated functionality.
118135*/
118136
118137/* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
118138#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
118139
118140/*
118141** Public interfaces:
118142**
118143**   sqlite3ConnectionBlocked()
118144**   sqlite3ConnectionUnlocked()
118145**   sqlite3ConnectionClosed()
118146**   sqlite3_unlock_notify()
118147*/
118148
118149#define assertMutexHeld() \
118150  assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
118151
118152/*
118153** Head of a linked list of all sqlite3 objects created by this process
118154** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
118155** is not NULL. This variable may only accessed while the STATIC_MASTER
118156** mutex is held.
118157*/
118158static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
118159
118160#ifndef NDEBUG
118161/*
118162** This function is a complex assert() that verifies the following
118163** properties of the blocked connections list:
118164**
118165**   1) Each entry in the list has a non-NULL value for either
118166**      pUnlockConnection or pBlockingConnection, or both.
118167**
118168**   2) All entries in the list that share a common value for
118169**      xUnlockNotify are grouped together.
118170**
118171**   3) If the argument db is not NULL, then none of the entries in the
118172**      blocked connections list have pUnlockConnection or pBlockingConnection
118173**      set to db. This is used when closing connection db.
118174*/
118175static void checkListProperties(sqlite3 *db){
118176  sqlite3 *p;
118177  for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
118178    int seen = 0;
118179    sqlite3 *p2;
118180
118181    /* Verify property (1) */
118182    assert( p->pUnlockConnection || p->pBlockingConnection );
118183
118184    /* Verify property (2) */
118185    for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
118186      if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
118187      assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
118188      assert( db==0 || p->pUnlockConnection!=db );
118189      assert( db==0 || p->pBlockingConnection!=db );
118190    }
118191  }
118192}
118193#else
118194# define checkListProperties(x)
118195#endif
118196
118197/*
118198** Remove connection db from the blocked connections list. If connection
118199** db is not currently a part of the list, this function is a no-op.
118200*/
118201static void removeFromBlockedList(sqlite3 *db){
118202  sqlite3 **pp;
118203  assertMutexHeld();
118204  for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
118205    if( *pp==db ){
118206      *pp = (*pp)->pNextBlocked;
118207      break;
118208    }
118209  }
118210}
118211
118212/*
118213** Add connection db to the blocked connections list. It is assumed
118214** that it is not already a part of the list.
118215*/
118216static void addToBlockedList(sqlite3 *db){
118217  sqlite3 **pp;
118218  assertMutexHeld();
118219  for(
118220    pp=&sqlite3BlockedList;
118221    *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
118222    pp=&(*pp)->pNextBlocked
118223  );
118224  db->pNextBlocked = *pp;
118225  *pp = db;
118226}
118227
118228/*
118229** Obtain the STATIC_MASTER mutex.
118230*/
118231static void enterMutex(void){
118232  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
118233  checkListProperties(0);
118234}
118235
118236/*
118237** Release the STATIC_MASTER mutex.
118238*/
118239static void leaveMutex(void){
118240  assertMutexHeld();
118241  checkListProperties(0);
118242  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
118243}
118244
118245/*
118246** Register an unlock-notify callback.
118247**
118248** This is called after connection "db" has attempted some operation
118249** but has received an SQLITE_LOCKED error because another connection
118250** (call it pOther) in the same process was busy using the same shared
118251** cache.  pOther is found by looking at db->pBlockingConnection.
118252**
118253** If there is no blocking connection, the callback is invoked immediately,
118254** before this routine returns.
118255**
118256** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
118257** a deadlock.
118258**
118259** Otherwise, make arrangements to invoke xNotify when pOther drops
118260** its locks.
118261**
118262** Each call to this routine overrides any prior callbacks registered
118263** on the same "db".  If xNotify==0 then any prior callbacks are immediately
118264** cancelled.
118265*/
118266SQLITE_API int sqlite3_unlock_notify(
118267  sqlite3 *db,
118268  void (*xNotify)(void **, int),
118269  void *pArg
118270){
118271  int rc = SQLITE_OK;
118272
118273  sqlite3_mutex_enter(db->mutex);
118274  enterMutex();
118275
118276  if( xNotify==0 ){
118277    removeFromBlockedList(db);
118278    db->pBlockingConnection = 0;
118279    db->pUnlockConnection = 0;
118280    db->xUnlockNotify = 0;
118281    db->pUnlockArg = 0;
118282  }else if( 0==db->pBlockingConnection ){
118283    /* The blocking transaction has been concluded. Or there never was a
118284    ** blocking transaction. In either case, invoke the notify callback
118285    ** immediately.
118286    */
118287    xNotify(&pArg, 1);
118288  }else{
118289    sqlite3 *p;
118290
118291    for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
118292    if( p ){
118293      rc = SQLITE_LOCKED;              /* Deadlock detected. */
118294    }else{
118295      db->pUnlockConnection = db->pBlockingConnection;
118296      db->xUnlockNotify = xNotify;
118297      db->pUnlockArg = pArg;
118298      removeFromBlockedList(db);
118299      addToBlockedList(db);
118300    }
118301  }
118302
118303  leaveMutex();
118304  assert( !db->mallocFailed );
118305  sqlite3Error(db, rc, (rc?"database is deadlocked":0));
118306  sqlite3_mutex_leave(db->mutex);
118307  return rc;
118308}
118309
118310/*
118311** This function is called while stepping or preparing a statement
118312** associated with connection db. The operation will return SQLITE_LOCKED
118313** to the user because it requires a lock that will not be available
118314** until connection pBlocker concludes its current transaction.
118315*/
118316SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
118317  enterMutex();
118318  if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
118319    addToBlockedList(db);
118320  }
118321  db->pBlockingConnection = pBlocker;
118322  leaveMutex();
118323}
118324
118325/*
118326** This function is called when
118327** the transaction opened by database db has just finished. Locks held
118328** by database connection db have been released.
118329**
118330** This function loops through each entry in the blocked connections
118331** list and does the following:
118332**
118333**   1) If the sqlite3.pBlockingConnection member of a list entry is
118334**      set to db, then set pBlockingConnection=0.
118335**
118336**   2) If the sqlite3.pUnlockConnection member of a list entry is
118337**      set to db, then invoke the configured unlock-notify callback and
118338**      set pUnlockConnection=0.
118339**
118340**   3) If the two steps above mean that pBlockingConnection==0 and
118341**      pUnlockConnection==0, remove the entry from the blocked connections
118342**      list.
118343*/
118344SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
118345  void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
118346  int nArg = 0;                            /* Number of entries in aArg[] */
118347  sqlite3 **pp;                            /* Iterator variable */
118348  void **aArg;               /* Arguments to the unlock callback */
118349  void **aDyn = 0;           /* Dynamically allocated space for aArg[] */
118350  void *aStatic[16];         /* Starter space for aArg[].  No malloc required */
118351
118352  aArg = aStatic;
118353  enterMutex();         /* Enter STATIC_MASTER mutex */
118354
118355  /* This loop runs once for each entry in the blocked-connections list. */
118356  for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
118357    sqlite3 *p = *pp;
118358
118359    /* Step 1. */
118360    if( p->pBlockingConnection==db ){
118361      p->pBlockingConnection = 0;
118362    }
118363
118364    /* Step 2. */
118365    if( p->pUnlockConnection==db ){
118366      assert( p->xUnlockNotify );
118367      if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
118368        xUnlockNotify(aArg, nArg);
118369        nArg = 0;
118370      }
118371
118372      sqlite3BeginBenignMalloc();
118373      assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
118374      assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
118375      if( (!aDyn && nArg==(int)ArraySize(aStatic))
118376       || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
118377      ){
118378        /* The aArg[] array needs to grow. */
118379        void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
118380        if( pNew ){
118381          memcpy(pNew, aArg, nArg*sizeof(void *));
118382          sqlite3_free(aDyn);
118383          aDyn = aArg = pNew;
118384        }else{
118385          /* This occurs when the array of context pointers that need to
118386          ** be passed to the unlock-notify callback is larger than the
118387          ** aStatic[] array allocated on the stack and the attempt to
118388          ** allocate a larger array from the heap has failed.
118389          **
118390          ** This is a difficult situation to handle. Returning an error
118391          ** code to the caller is insufficient, as even if an error code
118392          ** is returned the transaction on connection db will still be
118393          ** closed and the unlock-notify callbacks on blocked connections
118394          ** will go unissued. This might cause the application to wait
118395          ** indefinitely for an unlock-notify callback that will never
118396          ** arrive.
118397          **
118398          ** Instead, invoke the unlock-notify callback with the context
118399          ** array already accumulated. We can then clear the array and
118400          ** begin accumulating any further context pointers without
118401          ** requiring any dynamic allocation. This is sub-optimal because
118402          ** it means that instead of one callback with a large array of
118403          ** context pointers the application will receive two or more
118404          ** callbacks with smaller arrays of context pointers, which will
118405          ** reduce the applications ability to prioritize multiple
118406          ** connections. But it is the best that can be done under the
118407          ** circumstances.
118408          */
118409          xUnlockNotify(aArg, nArg);
118410          nArg = 0;
118411        }
118412      }
118413      sqlite3EndBenignMalloc();
118414
118415      aArg[nArg++] = p->pUnlockArg;
118416      xUnlockNotify = p->xUnlockNotify;
118417      p->pUnlockConnection = 0;
118418      p->xUnlockNotify = 0;
118419      p->pUnlockArg = 0;
118420    }
118421
118422    /* Step 3. */
118423    if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
118424      /* Remove connection p from the blocked connections list. */
118425      *pp = p->pNextBlocked;
118426      p->pNextBlocked = 0;
118427    }else{
118428      pp = &p->pNextBlocked;
118429    }
118430  }
118431
118432  if( nArg!=0 ){
118433    xUnlockNotify(aArg, nArg);
118434  }
118435  sqlite3_free(aDyn);
118436  leaveMutex();         /* Leave STATIC_MASTER mutex */
118437}
118438
118439/*
118440** This is called when the database connection passed as an argument is
118441** being closed. The connection is removed from the blocked list.
118442*/
118443SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
118444  sqlite3ConnectionUnlocked(db);
118445  enterMutex();
118446  removeFromBlockedList(db);
118447  checkListProperties(db);
118448  leaveMutex();
118449}
118450#endif
118451
118452/************** End of notify.c **********************************************/
118453/************** Begin file fts3.c ********************************************/
118454/*
118455** 2006 Oct 10
118456**
118457** The author disclaims copyright to this source code.  In place of
118458** a legal notice, here is a blessing:
118459**
118460**    May you do good and not evil.
118461**    May you find forgiveness for yourself and forgive others.
118462**    May you share freely, never taking more than you give.
118463**
118464******************************************************************************
118465**
118466** This is an SQLite module implementing full-text search.
118467*/
118468
118469/*
118470** The code in this file is only compiled if:
118471**
118472**     * The FTS3 module is being built as an extension
118473**       (in which case SQLITE_CORE is not defined), or
118474**
118475**     * The FTS3 module is being built into the core of
118476**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
118477*/
118478
118479/* The full-text index is stored in a series of b+tree (-like)
118480** structures called segments which map terms to doclists.  The
118481** structures are like b+trees in layout, but are constructed from the
118482** bottom up in optimal fashion and are not updatable.  Since trees
118483** are built from the bottom up, things will be described from the
118484** bottom up.
118485**
118486**
118487**** Varints ****
118488** The basic unit of encoding is a variable-length integer called a
118489** varint.  We encode variable-length integers in little-endian order
118490** using seven bits * per byte as follows:
118491**
118492** KEY:
118493**         A = 0xxxxxxx    7 bits of data and one flag bit
118494**         B = 1xxxxxxx    7 bits of data and one flag bit
118495**
118496**  7 bits - A
118497** 14 bits - BA
118498** 21 bits - BBA
118499** and so on.
118500**
118501** This is similar in concept to how sqlite encodes "varints" but
118502** the encoding is not the same.  SQLite varints are big-endian
118503** are are limited to 9 bytes in length whereas FTS3 varints are
118504** little-endian and can be up to 10 bytes in length (in theory).
118505**
118506** Example encodings:
118507**
118508**     1:    0x01
118509**   127:    0x7f
118510**   128:    0x81 0x00
118511**
118512**
118513**** Document lists ****
118514** A doclist (document list) holds a docid-sorted list of hits for a
118515** given term.  Doclists hold docids and associated token positions.
118516** A docid is the unique integer identifier for a single document.
118517** A position is the index of a word within the document.  The first
118518** word of the document has a position of 0.
118519**
118520** FTS3 used to optionally store character offsets using a compile-time
118521** option.  But that functionality is no longer supported.
118522**
118523** A doclist is stored like this:
118524**
118525** array {
118526**   varint docid;          (delta from previous doclist)
118527**   array {                (position list for column 0)
118528**     varint position;     (2 more than the delta from previous position)
118529**   }
118530**   array {
118531**     varint POS_COLUMN;   (marks start of position list for new column)
118532**     varint column;       (index of new column)
118533**     array {
118534**       varint position;   (2 more than the delta from previous position)
118535**     }
118536**   }
118537**   varint POS_END;        (marks end of positions for this document.
118538** }
118539**
118540** Here, array { X } means zero or more occurrences of X, adjacent in
118541** memory.  A "position" is an index of a token in the token stream
118542** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
118543** in the same logical place as the position element, and act as sentinals
118544** ending a position list array.  POS_END is 0.  POS_COLUMN is 1.
118545** The positions numbers are not stored literally but rather as two more
118546** than the difference from the prior position, or the just the position plus
118547** 2 for the first position.  Example:
118548**
118549**   label:       A B C D E  F  G H   I  J K
118550**   value:     123 5 9 1 1 14 35 0 234 72 0
118551**
118552** The 123 value is the first docid.  For column zero in this document
118553** there are two matches at positions 3 and 10 (5-2 and 9-2+3).  The 1
118554** at D signals the start of a new column; the 1 at E indicates that the
118555** new column is column number 1.  There are two positions at 12 and 45
118556** (14-2 and 35-2+12).  The 0 at H indicate the end-of-document.  The
118557** 234 at I is the delta to next docid (357).  It has one position 70
118558** (72-2) and then terminates with the 0 at K.
118559**
118560** A "position-list" is the list of positions for multiple columns for
118561** a single docid.  A "column-list" is the set of positions for a single
118562** column.  Hence, a position-list consists of one or more column-lists,
118563** a document record consists of a docid followed by a position-list and
118564** a doclist consists of one or more document records.
118565**
118566** A bare doclist omits the position information, becoming an
118567** array of varint-encoded docids.
118568**
118569**** Segment leaf nodes ****
118570** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
118571** nodes are written using LeafWriter, and read using LeafReader (to
118572** iterate through a single leaf node's data) and LeavesReader (to
118573** iterate through a segment's entire leaf layer).  Leaf nodes have
118574** the format:
118575**
118576** varint iHeight;             (height from leaf level, always 0)
118577** varint nTerm;               (length of first term)
118578** char pTerm[nTerm];          (content of first term)
118579** varint nDoclist;            (length of term's associated doclist)
118580** char pDoclist[nDoclist];    (content of doclist)
118581** array {
118582**                             (further terms are delta-encoded)
118583**   varint nPrefix;           (length of prefix shared with previous term)
118584**   varint nSuffix;           (length of unshared suffix)
118585**   char pTermSuffix[nSuffix];(unshared suffix of next term)
118586**   varint nDoclist;          (length of term's associated doclist)
118587**   char pDoclist[nDoclist];  (content of doclist)
118588** }
118589**
118590** Here, array { X } means zero or more occurrences of X, adjacent in
118591** memory.
118592**
118593** Leaf nodes are broken into blocks which are stored contiguously in
118594** the %_segments table in sorted order.  This means that when the end
118595** of a node is reached, the next term is in the node with the next
118596** greater node id.
118597**
118598** New data is spilled to a new leaf node when the current node
118599** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
118600** larger than STANDALONE_MIN (default 1024) is placed in a standalone
118601** node (a leaf node with a single term and doclist).  The goal of
118602** these settings is to pack together groups of small doclists while
118603** making it efficient to directly access large doclists.  The
118604** assumption is that large doclists represent terms which are more
118605** likely to be query targets.
118606**
118607** TODO(shess) It may be useful for blocking decisions to be more
118608** dynamic.  For instance, it may make more sense to have a 2.5k leaf
118609** node rather than splitting into 2k and .5k nodes.  My intuition is
118610** that this might extend through 2x or 4x the pagesize.
118611**
118612**
118613**** Segment interior nodes ****
118614** Segment interior nodes store blockids for subtree nodes and terms
118615** to describe what data is stored by the each subtree.  Interior
118616** nodes are written using InteriorWriter, and read using
118617** InteriorReader.  InteriorWriters are created as needed when
118618** SegmentWriter creates new leaf nodes, or when an interior node
118619** itself grows too big and must be split.  The format of interior
118620** nodes:
118621**
118622** varint iHeight;           (height from leaf level, always >0)
118623** varint iBlockid;          (block id of node's leftmost subtree)
118624** optional {
118625**   varint nTerm;           (length of first term)
118626**   char pTerm[nTerm];      (content of first term)
118627**   array {
118628**                                (further terms are delta-encoded)
118629**     varint nPrefix;            (length of shared prefix with previous term)
118630**     varint nSuffix;            (length of unshared suffix)
118631**     char pTermSuffix[nSuffix]; (unshared suffix of next term)
118632**   }
118633** }
118634**
118635** Here, optional { X } means an optional element, while array { X }
118636** means zero or more occurrences of X, adjacent in memory.
118637**
118638** An interior node encodes n terms separating n+1 subtrees.  The
118639** subtree blocks are contiguous, so only the first subtree's blockid
118640** is encoded.  The subtree at iBlockid will contain all terms less
118641** than the first term encoded (or all terms if no term is encoded).
118642** Otherwise, for terms greater than or equal to pTerm[i] but less
118643** than pTerm[i+1], the subtree for that term will be rooted at
118644** iBlockid+i.  Interior nodes only store enough term data to
118645** distinguish adjacent children (if the rightmost term of the left
118646** child is "something", and the leftmost term of the right child is
118647** "wicked", only "w" is stored).
118648**
118649** New data is spilled to a new interior node at the same height when
118650** the current node exceeds INTERIOR_MAX bytes (default 2048).
118651** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
118652** interior nodes and making the tree too skinny.  The interior nodes
118653** at a given height are naturally tracked by interior nodes at
118654** height+1, and so on.
118655**
118656**
118657**** Segment directory ****
118658** The segment directory in table %_segdir stores meta-information for
118659** merging and deleting segments, and also the root node of the
118660** segment's tree.
118661**
118662** The root node is the top node of the segment's tree after encoding
118663** the entire segment, restricted to ROOT_MAX bytes (default 1024).
118664** This could be either a leaf node or an interior node.  If the top
118665** node requires more than ROOT_MAX bytes, it is flushed to %_segments
118666** and a new root interior node is generated (which should always fit
118667** within ROOT_MAX because it only needs space for 2 varints, the
118668** height and the blockid of the previous root).
118669**
118670** The meta-information in the segment directory is:
118671**   level               - segment level (see below)
118672**   idx                 - index within level
118673**                       - (level,idx uniquely identify a segment)
118674**   start_block         - first leaf node
118675**   leaves_end_block    - last leaf node
118676**   end_block           - last block (including interior nodes)
118677**   root                - contents of root node
118678**
118679** If the root node is a leaf node, then start_block,
118680** leaves_end_block, and end_block are all 0.
118681**
118682**
118683**** Segment merging ****
118684** To amortize update costs, segments are grouped into levels and
118685** merged in batches.  Each increase in level represents exponentially
118686** more documents.
118687**
118688** New documents (actually, document updates) are tokenized and
118689** written individually (using LeafWriter) to a level 0 segment, with
118690** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
118691** level 0 segments are merged into a single level 1 segment.  Level 1
118692** is populated like level 0, and eventually MERGE_COUNT level 1
118693** segments are merged to a single level 2 segment (representing
118694** MERGE_COUNT^2 updates), and so on.
118695**
118696** A segment merge traverses all segments at a given level in
118697** parallel, performing a straightforward sorted merge.  Since segment
118698** leaf nodes are written in to the %_segments table in order, this
118699** merge traverses the underlying sqlite disk structures efficiently.
118700** After the merge, all segment blocks from the merged level are
118701** deleted.
118702**
118703** MERGE_COUNT controls how often we merge segments.  16 seems to be
118704** somewhat of a sweet spot for insertion performance.  32 and 64 show
118705** very similar performance numbers to 16 on insertion, though they're
118706** a tiny bit slower (perhaps due to more overhead in merge-time
118707** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
118708** 16, 2 about 66% slower than 16.
118709**
118710** At query time, high MERGE_COUNT increases the number of segments
118711** which need to be scanned and merged.  For instance, with 100k docs
118712** inserted:
118713**
118714**    MERGE_COUNT   segments
118715**       16           25
118716**        8           12
118717**        4           10
118718**        2            6
118719**
118720** This appears to have only a moderate impact on queries for very
118721** frequent terms (which are somewhat dominated by segment merge
118722** costs), and infrequent and non-existent terms still seem to be fast
118723** even with many segments.
118724**
118725** TODO(shess) That said, it would be nice to have a better query-side
118726** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
118727** optimizations to things like doclist merging will swing the sweet
118728** spot around.
118729**
118730**
118731**
118732**** Handling of deletions and updates ****
118733** Since we're using a segmented structure, with no docid-oriented
118734** index into the term index, we clearly cannot simply update the term
118735** index when a document is deleted or updated.  For deletions, we
118736** write an empty doclist (varint(docid) varint(POS_END)), for updates
118737** we simply write the new doclist.  Segment merges overwrite older
118738** data for a particular docid with newer data, so deletes or updates
118739** will eventually overtake the earlier data and knock it out.  The
118740** query logic likewise merges doclists so that newer data knocks out
118741** older data.
118742*/
118743
118744/************** Include fts3Int.h in the middle of fts3.c ********************/
118745/************** Begin file fts3Int.h *****************************************/
118746/*
118747** 2009 Nov 12
118748**
118749** The author disclaims copyright to this source code.  In place of
118750** a legal notice, here is a blessing:
118751**
118752**    May you do good and not evil.
118753**    May you find forgiveness for yourself and forgive others.
118754**    May you share freely, never taking more than you give.
118755**
118756******************************************************************************
118757**
118758*/
118759#ifndef _FTSINT_H
118760#define _FTSINT_H
118761
118762#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
118763# define NDEBUG 1
118764#endif
118765
118766/*
118767** FTS4 is really an extension for FTS3.  It is enabled using the
118768** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
118769** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
118770*/
118771#if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
118772# define SQLITE_ENABLE_FTS3
118773#endif
118774
118775#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
118776
118777/* If not building as part of the core, include sqlite3ext.h. */
118778#ifndef SQLITE_CORE
118779SQLITE_API extern const sqlite3_api_routines *sqlite3_api;
118780#endif
118781
118782/************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
118783/************** Begin file fts3_tokenizer.h **********************************/
118784/*
118785** 2006 July 10
118786**
118787** The author disclaims copyright to this source code.
118788**
118789*************************************************************************
118790** Defines the interface to tokenizers used by fulltext-search.  There
118791** are three basic components:
118792**
118793** sqlite3_tokenizer_module is a singleton defining the tokenizer
118794** interface functions.  This is essentially the class structure for
118795** tokenizers.
118796**
118797** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
118798** including customization information defined at creation time.
118799**
118800** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
118801** tokens from a particular input.
118802*/
118803#ifndef _FTS3_TOKENIZER_H_
118804#define _FTS3_TOKENIZER_H_
118805
118806/* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
118807** If tokenizers are to be allowed to call sqlite3_*() functions, then
118808** we will need a way to register the API consistently.
118809*/
118810
118811/*
118812** Structures used by the tokenizer interface. When a new tokenizer
118813** implementation is registered, the caller provides a pointer to
118814** an sqlite3_tokenizer_module containing pointers to the callback
118815** functions that make up an implementation.
118816**
118817** When an fts3 table is created, it passes any arguments passed to
118818** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
118819** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
118820** implementation. The xCreate() function in turn returns an
118821** sqlite3_tokenizer structure representing the specific tokenizer to
118822** be used for the fts3 table (customized by the tokenizer clause arguments).
118823**
118824** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
118825** method is called. It returns an sqlite3_tokenizer_cursor object
118826** that may be used to tokenize a specific input buffer based on
118827** the tokenization rules supplied by a specific sqlite3_tokenizer
118828** object.
118829*/
118830typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
118831typedef struct sqlite3_tokenizer sqlite3_tokenizer;
118832typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
118833
118834struct sqlite3_tokenizer_module {
118835
118836  /*
118837  ** Structure version. Should always be set to 0 or 1.
118838  */
118839  int iVersion;
118840
118841  /*
118842  ** Create a new tokenizer. The values in the argv[] array are the
118843  ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
118844  ** TABLE statement that created the fts3 table. For example, if
118845  ** the following SQL is executed:
118846  **
118847  **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
118848  **
118849  ** then argc is set to 2, and the argv[] array contains pointers
118850  ** to the strings "arg1" and "arg2".
118851  **
118852  ** This method should return either SQLITE_OK (0), or an SQLite error
118853  ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
118854  ** to point at the newly created tokenizer structure. The generic
118855  ** sqlite3_tokenizer.pModule variable should not be initialized by
118856  ** this callback. The caller will do so.
118857  */
118858  int (*xCreate)(
118859    int argc,                           /* Size of argv array */
118860    const char *const*argv,             /* Tokenizer argument strings */
118861    sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
118862  );
118863
118864  /*
118865  ** Destroy an existing tokenizer. The fts3 module calls this method
118866  ** exactly once for each successful call to xCreate().
118867  */
118868  int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
118869
118870  /*
118871  ** Create a tokenizer cursor to tokenize an input buffer. The caller
118872  ** is responsible for ensuring that the input buffer remains valid
118873  ** until the cursor is closed (using the xClose() method).
118874  */
118875  int (*xOpen)(
118876    sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
118877    const char *pInput, int nBytes,      /* Input buffer */
118878    sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
118879  );
118880
118881  /*
118882  ** Destroy an existing tokenizer cursor. The fts3 module calls this
118883  ** method exactly once for each successful call to xOpen().
118884  */
118885  int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
118886
118887  /*
118888  ** Retrieve the next token from the tokenizer cursor pCursor. This
118889  ** method should either return SQLITE_OK and set the values of the
118890  ** "OUT" variables identified below, or SQLITE_DONE to indicate that
118891  ** the end of the buffer has been reached, or an SQLite error code.
118892  **
118893  ** *ppToken should be set to point at a buffer containing the
118894  ** normalized version of the token (i.e. after any case-folding and/or
118895  ** stemming has been performed). *pnBytes should be set to the length
118896  ** of this buffer in bytes. The input text that generated the token is
118897  ** identified by the byte offsets returned in *piStartOffset and
118898  ** *piEndOffset. *piStartOffset should be set to the index of the first
118899  ** byte of the token in the input buffer. *piEndOffset should be set
118900  ** to the index of the first byte just past the end of the token in
118901  ** the input buffer.
118902  **
118903  ** The buffer *ppToken is set to point at is managed by the tokenizer
118904  ** implementation. It is only required to be valid until the next call
118905  ** to xNext() or xClose().
118906  */
118907  /* TODO(shess) current implementation requires pInput to be
118908  ** nul-terminated.  This should either be fixed, or pInput/nBytes
118909  ** should be converted to zInput.
118910  */
118911  int (*xNext)(
118912    sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
118913    const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
118914    int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
118915    int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
118916    int *piPosition      /* OUT: Number of tokens returned before this one */
118917  );
118918
118919  /***********************************************************************
118920  ** Methods below this point are only available if iVersion>=1.
118921  */
118922
118923  /*
118924  ** Configure the language id of a tokenizer cursor.
118925  */
118926  int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
118927};
118928
118929struct sqlite3_tokenizer {
118930  const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
118931  /* Tokenizer implementations will typically add additional fields */
118932};
118933
118934struct sqlite3_tokenizer_cursor {
118935  sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
118936  /* Tokenizer implementations will typically add additional fields */
118937};
118938
118939int fts3_global_term_cnt(int iTerm, int iCol);
118940int fts3_term_cnt(int iTerm, int iCol);
118941
118942
118943#endif /* _FTS3_TOKENIZER_H_ */
118944
118945/************** End of fts3_tokenizer.h **************************************/
118946/************** Continuing where we left off in fts3Int.h ********************/
118947/************** Include fts3_hash.h in the middle of fts3Int.h ***************/
118948/************** Begin file fts3_hash.h ***************************************/
118949/*
118950** 2001 September 22
118951**
118952** The author disclaims copyright to this source code.  In place of
118953** a legal notice, here is a blessing:
118954**
118955**    May you do good and not evil.
118956**    May you find forgiveness for yourself and forgive others.
118957**    May you share freely, never taking more than you give.
118958**
118959*************************************************************************
118960** This is the header file for the generic hash-table implementation
118961** used in SQLite.  We've modified it slightly to serve as a standalone
118962** hash table implementation for the full-text indexing module.
118963**
118964*/
118965#ifndef _FTS3_HASH_H_
118966#define _FTS3_HASH_H_
118967
118968/* Forward declarations of structures. */
118969typedef struct Fts3Hash Fts3Hash;
118970typedef struct Fts3HashElem Fts3HashElem;
118971
118972/* A complete hash table is an instance of the following structure.
118973** The internals of this structure are intended to be opaque -- client
118974** code should not attempt to access or modify the fields of this structure
118975** directly.  Change this structure only by using the routines below.
118976** However, many of the "procedures" and "functions" for modifying and
118977** accessing this structure are really macros, so we can't really make
118978** this structure opaque.
118979*/
118980struct Fts3Hash {
118981  char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
118982  char copyKey;           /* True if copy of key made on insert */
118983  int count;              /* Number of entries in this table */
118984  Fts3HashElem *first;    /* The first element of the array */
118985  int htsize;             /* Number of buckets in the hash table */
118986  struct _fts3ht {        /* the hash table */
118987    int count;               /* Number of entries with this hash */
118988    Fts3HashElem *chain;     /* Pointer to first entry with this hash */
118989  } *ht;
118990};
118991
118992/* Each element in the hash table is an instance of the following
118993** structure.  All elements are stored on a single doubly-linked list.
118994**
118995** Again, this structure is intended to be opaque, but it can't really
118996** be opaque because it is used by macros.
118997*/
118998struct Fts3HashElem {
118999  Fts3HashElem *next, *prev; /* Next and previous elements in the table */
119000  void *data;                /* Data associated with this element */
119001  void *pKey; int nKey;      /* Key associated with this element */
119002};
119003
119004/*
119005** There are 2 different modes of operation for a hash table:
119006**
119007**   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
119008**                           (including the null-terminator, if any).  Case
119009**                           is respected in comparisons.
119010**
119011**   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long.
119012**                           memcmp() is used to compare keys.
119013**
119014** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
119015*/
119016#define FTS3_HASH_STRING    1
119017#define FTS3_HASH_BINARY    2
119018
119019/*
119020** Access routines.  To delete, insert a NULL pointer.
119021*/
119022SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
119023SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
119024SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
119025SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
119026SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
119027
119028/*
119029** Shorthand for the functions above
119030*/
119031#define fts3HashInit     sqlite3Fts3HashInit
119032#define fts3HashInsert   sqlite3Fts3HashInsert
119033#define fts3HashFind     sqlite3Fts3HashFind
119034#define fts3HashClear    sqlite3Fts3HashClear
119035#define fts3HashFindElem sqlite3Fts3HashFindElem
119036
119037/*
119038** Macros for looping over all elements of a hash table.  The idiom is
119039** like this:
119040**
119041**   Fts3Hash h;
119042**   Fts3HashElem *p;
119043**   ...
119044**   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
119045**     SomeStructure *pData = fts3HashData(p);
119046**     // do something with pData
119047**   }
119048*/
119049#define fts3HashFirst(H)  ((H)->first)
119050#define fts3HashNext(E)   ((E)->next)
119051#define fts3HashData(E)   ((E)->data)
119052#define fts3HashKey(E)    ((E)->pKey)
119053#define fts3HashKeysize(E) ((E)->nKey)
119054
119055/*
119056** Number of entries in a hash table
119057*/
119058#define fts3HashCount(H)  ((H)->count)
119059
119060#endif /* _FTS3_HASH_H_ */
119061
119062/************** End of fts3_hash.h *******************************************/
119063/************** Continuing where we left off in fts3Int.h ********************/
119064
119065/*
119066** This constant controls how often segments are merged. Once there are
119067** FTS3_MERGE_COUNT segments of level N, they are merged into a single
119068** segment of level N+1.
119069*/
119070#define FTS3_MERGE_COUNT 16
119071
119072/*
119073** This is the maximum amount of data (in bytes) to store in the
119074** Fts3Table.pendingTerms hash table. Normally, the hash table is
119075** populated as documents are inserted/updated/deleted in a transaction
119076** and used to create a new segment when the transaction is committed.
119077** However if this limit is reached midway through a transaction, a new
119078** segment is created and the hash table cleared immediately.
119079*/
119080#define FTS3_MAX_PENDING_DATA (1*1024*1024)
119081
119082/*
119083** Macro to return the number of elements in an array. SQLite has a
119084** similar macro called ArraySize(). Use a different name to avoid
119085** a collision when building an amalgamation with built-in FTS3.
119086*/
119087#define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
119088
119089
119090#ifndef MIN
119091# define MIN(x,y) ((x)<(y)?(x):(y))
119092#endif
119093#ifndef MAX
119094# define MAX(x,y) ((x)>(y)?(x):(y))
119095#endif
119096
119097/*
119098** Maximum length of a varint encoded integer. The varint format is different
119099** from that used by SQLite, so the maximum length is 10, not 9.
119100*/
119101#define FTS3_VARINT_MAX 10
119102
119103/*
119104** FTS4 virtual tables may maintain multiple indexes - one index of all terms
119105** in the document set and zero or more prefix indexes. All indexes are stored
119106** as one or more b+-trees in the %_segments and %_segdir tables.
119107**
119108** It is possible to determine which index a b+-tree belongs to based on the
119109** value stored in the "%_segdir.level" column. Given this value L, the index
119110** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
119111** level values between 0 and 1023 (inclusive) belong to index 0, all levels
119112** between 1024 and 2047 to index 1, and so on.
119113**
119114** It is considered impossible for an index to use more than 1024 levels. In
119115** theory though this may happen, but only after at least
119116** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
119117*/
119118#define FTS3_SEGDIR_MAXLEVEL      1024
119119#define FTS3_SEGDIR_MAXLEVEL_STR "1024"
119120
119121/*
119122** The testcase() macro is only used by the amalgamation.  If undefined,
119123** make it a no-op.
119124*/
119125#ifndef testcase
119126# define testcase(X)
119127#endif
119128
119129/*
119130** Terminator values for position-lists and column-lists.
119131*/
119132#define POS_COLUMN  (1)     /* Column-list terminator */
119133#define POS_END     (0)     /* Position-list terminator */
119134
119135/*
119136** This section provides definitions to allow the
119137** FTS3 extension to be compiled outside of the
119138** amalgamation.
119139*/
119140#ifndef SQLITE_AMALGAMATION
119141/*
119142** Macros indicating that conditional expressions are always true or
119143** false.
119144*/
119145#ifdef SQLITE_COVERAGE_TEST
119146# define ALWAYS(x) (1)
119147# define NEVER(X)  (0)
119148#else
119149# define ALWAYS(x) (x)
119150# define NEVER(x)  (x)
119151#endif
119152
119153/*
119154** Internal types used by SQLite.
119155*/
119156typedef unsigned char u8;         /* 1-byte (or larger) unsigned integer */
119157typedef short int i16;            /* 2-byte (or larger) signed integer */
119158typedef unsigned int u32;         /* 4-byte unsigned integer */
119159typedef sqlite3_uint64 u64;       /* 8-byte unsigned integer */
119160typedef sqlite3_int64 i64;        /* 8-byte signed integer */
119161
119162/*
119163** Macro used to suppress compiler warnings for unused parameters.
119164*/
119165#define UNUSED_PARAMETER(x) (void)(x)
119166
119167/*
119168** Activate assert() only if SQLITE_TEST is enabled.
119169*/
119170#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
119171# define NDEBUG 1
119172#endif
119173
119174/*
119175** The TESTONLY macro is used to enclose variable declarations or
119176** other bits of code that are needed to support the arguments
119177** within testcase() and assert() macros.
119178*/
119179#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
119180# define TESTONLY(X)  X
119181#else
119182# define TESTONLY(X)
119183#endif
119184
119185#endif /* SQLITE_AMALGAMATION */
119186
119187#ifdef SQLITE_DEBUG
119188SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
119189# define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
119190#else
119191# define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
119192#endif
119193
119194typedef struct Fts3Table Fts3Table;
119195typedef struct Fts3Cursor Fts3Cursor;
119196typedef struct Fts3Expr Fts3Expr;
119197typedef struct Fts3Phrase Fts3Phrase;
119198typedef struct Fts3PhraseToken Fts3PhraseToken;
119199
119200typedef struct Fts3Doclist Fts3Doclist;
119201typedef struct Fts3SegFilter Fts3SegFilter;
119202typedef struct Fts3DeferredToken Fts3DeferredToken;
119203typedef struct Fts3SegReader Fts3SegReader;
119204typedef struct Fts3MultiSegReader Fts3MultiSegReader;
119205
119206/*
119207** A connection to a fulltext index is an instance of the following
119208** structure. The xCreate and xConnect methods create an instance
119209** of this structure and xDestroy and xDisconnect free that instance.
119210** All other methods receive a pointer to the structure as one of their
119211** arguments.
119212*/
119213struct Fts3Table {
119214  sqlite3_vtab base;              /* Base class used by SQLite core */
119215  sqlite3 *db;                    /* The database connection */
119216  const char *zDb;                /* logical database name */
119217  const char *zName;              /* virtual table name */
119218  int nColumn;                    /* number of named columns in virtual table */
119219  char **azColumn;                /* column names.  malloced */
119220  sqlite3_tokenizer *pTokenizer;  /* tokenizer for inserts and queries */
119221  char *zContentTbl;              /* content=xxx option, or NULL */
119222  char *zLanguageid;              /* languageid=xxx option, or NULL */
119223  u8 bAutoincrmerge;              /* True if automerge=1 */
119224  u32 nLeafAdd;                   /* Number of leaf blocks added this trans */
119225
119226  /* Precompiled statements used by the implementation. Each of these
119227  ** statements is run and reset within a single virtual table API call.
119228  */
119229  sqlite3_stmt *aStmt[37];
119230
119231  char *zReadExprlist;
119232  char *zWriteExprlist;
119233
119234  int nNodeSize;                  /* Soft limit for node size */
119235  u8 bFts4;                       /* True for FTS4, false for FTS3 */
119236  u8 bHasStat;                    /* True if %_stat table exists */
119237  u8 bHasDocsize;                 /* True if %_docsize table exists */
119238  u8 bDescIdx;                    /* True if doclists are in reverse order */
119239  u8 bIgnoreSavepoint;            /* True to ignore xSavepoint invocations */
119240  int nPgsz;                      /* Page size for host database */
119241  char *zSegmentsTbl;             /* Name of %_segments table */
119242  sqlite3_blob *pSegments;        /* Blob handle open on %_segments table */
119243
119244  /*
119245  ** The following array of hash tables is used to buffer pending index
119246  ** updates during transactions. All pending updates buffered at any one
119247  ** time must share a common language-id (see the FTS4 langid= feature).
119248  ** The current language id is stored in variable iPrevLangid.
119249  **
119250  ** A single FTS4 table may have multiple full-text indexes. For each index
119251  ** there is an entry in the aIndex[] array. Index 0 is an index of all the
119252  ** terms that appear in the document set. Each subsequent index in aIndex[]
119253  ** is an index of prefixes of a specific length.
119254  **
119255  ** Variable nPendingData contains an estimate the memory consumed by the
119256  ** pending data structures, including hash table overhead, but not including
119257  ** malloc overhead.  When nPendingData exceeds nMaxPendingData, all hash
119258  ** tables are flushed to disk. Variable iPrevDocid is the docid of the most
119259  ** recently inserted record.
119260  */
119261  int nIndex;                     /* Size of aIndex[] */
119262  struct Fts3Index {
119263    int nPrefix;                  /* Prefix length (0 for main terms index) */
119264    Fts3Hash hPending;            /* Pending terms table for this index */
119265  } *aIndex;
119266  int nMaxPendingData;            /* Max pending data before flush to disk */
119267  int nPendingData;               /* Current bytes of pending data */
119268  sqlite_int64 iPrevDocid;        /* Docid of most recently inserted document */
119269  int iPrevLangid;                /* Langid of recently inserted document */
119270
119271#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
119272  /* State variables used for validating that the transaction control
119273  ** methods of the virtual table are called at appropriate times.  These
119274  ** values do not contribute to FTS functionality; they are used for
119275  ** verifying the operation of the SQLite core.
119276  */
119277  int inTransaction;     /* True after xBegin but before xCommit/xRollback */
119278  int mxSavepoint;       /* Largest valid xSavepoint integer */
119279#endif
119280};
119281
119282/*
119283** When the core wants to read from the virtual table, it creates a
119284** virtual table cursor (an instance of the following structure) using
119285** the xOpen method. Cursors are destroyed using the xClose method.
119286*/
119287struct Fts3Cursor {
119288  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
119289  i16 eSearch;                    /* Search strategy (see below) */
119290  u8 isEof;                       /* True if at End Of Results */
119291  u8 isRequireSeek;               /* True if must seek pStmt to %_content row */
119292  sqlite3_stmt *pStmt;            /* Prepared statement in use by the cursor */
119293  Fts3Expr *pExpr;                /* Parsed MATCH query string */
119294  int iLangid;                    /* Language being queried for */
119295  int nPhrase;                    /* Number of matchable phrases in query */
119296  Fts3DeferredToken *pDeferred;   /* Deferred search tokens, if any */
119297  sqlite3_int64 iPrevId;          /* Previous id read from aDoclist */
119298  char *pNextId;                  /* Pointer into the body of aDoclist */
119299  char *aDoclist;                 /* List of docids for full-text queries */
119300  int nDoclist;                   /* Size of buffer at aDoclist */
119301  u8 bDesc;                       /* True to sort in descending order */
119302  int eEvalmode;                  /* An FTS3_EVAL_XX constant */
119303  int nRowAvg;                    /* Average size of database rows, in pages */
119304  sqlite3_int64 nDoc;             /* Documents in table */
119305
119306  int isMatchinfoNeeded;          /* True when aMatchinfo[] needs filling in */
119307  u32 *aMatchinfo;                /* Information about most recent match */
119308  int nMatchinfo;                 /* Number of elements in aMatchinfo[] */
119309  char *zMatchinfo;               /* Matchinfo specification */
119310};
119311
119312#define FTS3_EVAL_FILTER    0
119313#define FTS3_EVAL_NEXT      1
119314#define FTS3_EVAL_MATCHINFO 2
119315
119316/*
119317** The Fts3Cursor.eSearch member is always set to one of the following.
119318** Actualy, Fts3Cursor.eSearch can be greater than or equal to
119319** FTS3_FULLTEXT_SEARCH.  If so, then Fts3Cursor.eSearch - 2 is the index
119320** of the column to be searched.  For example, in
119321**
119322**     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
119323**     SELECT docid FROM ex1 WHERE b MATCH 'one two three';
119324**
119325** Because the LHS of the MATCH operator is 2nd column "b",
119326** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,
119327** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were "ex1"
119328** indicating that all columns should be searched,
119329** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
119330*/
119331#define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */
119332#define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */
119333#define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */
119334
119335
119336struct Fts3Doclist {
119337  char *aAll;                    /* Array containing doclist (or NULL) */
119338  int nAll;                      /* Size of a[] in bytes */
119339  char *pNextDocid;              /* Pointer to next docid */
119340
119341  sqlite3_int64 iDocid;          /* Current docid (if pList!=0) */
119342  int bFreeList;                 /* True if pList should be sqlite3_free()d */
119343  char *pList;                   /* Pointer to position list following iDocid */
119344  int nList;                     /* Length of position list */
119345};
119346
119347/*
119348** A "phrase" is a sequence of one or more tokens that must match in
119349** sequence.  A single token is the base case and the most common case.
119350** For a sequence of tokens contained in double-quotes (i.e. "one two three")
119351** nToken will be the number of tokens in the string.
119352*/
119353struct Fts3PhraseToken {
119354  char *z;                        /* Text of the token */
119355  int n;                          /* Number of bytes in buffer z */
119356  int isPrefix;                   /* True if token ends with a "*" character */
119357  int bFirst;                     /* True if token must appear at position 0 */
119358
119359  /* Variables above this point are populated when the expression is
119360  ** parsed (by code in fts3_expr.c). Below this point the variables are
119361  ** used when evaluating the expression. */
119362  Fts3DeferredToken *pDeferred;   /* Deferred token object for this token */
119363  Fts3MultiSegReader *pSegcsr;    /* Segment-reader for this token */
119364};
119365
119366struct Fts3Phrase {
119367  /* Cache of doclist for this phrase. */
119368  Fts3Doclist doclist;
119369  int bIncr;                 /* True if doclist is loaded incrementally */
119370  int iDoclistToken;
119371
119372  /* Variables below this point are populated by fts3_expr.c when parsing
119373  ** a MATCH expression. Everything above is part of the evaluation phase.
119374  */
119375  int nToken;                /* Number of tokens in the phrase */
119376  int iColumn;               /* Index of column this phrase must match */
119377  Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
119378};
119379
119380/*
119381** A tree of these objects forms the RHS of a MATCH operator.
119382**
119383** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
119384** points to a malloced buffer, size nDoclist bytes, containing the results
119385** of this phrase query in FTS3 doclist format. As usual, the initial
119386** "Length" field found in doclists stored on disk is omitted from this
119387** buffer.
119388**
119389** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
119390** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
119391** where nCol is the number of columns in the queried FTS table. The array
119392** is populated as follows:
119393**
119394**   aMI[iCol*3 + 0] = Undefined
119395**   aMI[iCol*3 + 1] = Number of occurrences
119396**   aMI[iCol*3 + 2] = Number of rows containing at least one instance
119397**
119398** The aMI array is allocated using sqlite3_malloc(). It should be freed
119399** when the expression node is.
119400*/
119401struct Fts3Expr {
119402  int eType;                 /* One of the FTSQUERY_XXX values defined below */
119403  int nNear;                 /* Valid if eType==FTSQUERY_NEAR */
119404  Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */
119405  Fts3Expr *pLeft;           /* Left operand */
119406  Fts3Expr *pRight;          /* Right operand */
119407  Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */
119408
119409  /* The following are used by the fts3_eval.c module. */
119410  sqlite3_int64 iDocid;      /* Current docid */
119411  u8 bEof;                   /* True this expression is at EOF already */
119412  u8 bStart;                 /* True if iDocid is valid */
119413  u8 bDeferred;              /* True if this expression is entirely deferred */
119414
119415  u32 *aMI;
119416};
119417
119418/*
119419** Candidate values for Fts3Query.eType. Note that the order of the first
119420** four values is in order of precedence when parsing expressions. For
119421** example, the following:
119422**
119423**   "a OR b AND c NOT d NEAR e"
119424**
119425** is equivalent to:
119426**
119427**   "a OR (b AND (c NOT (d NEAR e)))"
119428*/
119429#define FTSQUERY_NEAR   1
119430#define FTSQUERY_NOT    2
119431#define FTSQUERY_AND    3
119432#define FTSQUERY_OR     4
119433#define FTSQUERY_PHRASE 5
119434
119435
119436/* fts3_write.c */
119437SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
119438SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
119439SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
119440SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
119441SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
119442  sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
119443SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
119444  Fts3Table*,int,const char*,int,int,Fts3SegReader**);
119445SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
119446SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
119447SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *);
119448SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
119449
119450SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
119451SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
119452
119453#ifndef SQLITE_DISABLE_FTS4_DEFERRED
119454SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
119455SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
119456SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
119457SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
119458SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
119459#else
119460# define sqlite3Fts3FreeDeferredTokens(x)
119461# define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
119462# define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
119463# define sqlite3Fts3FreeDeferredDoclists(x)
119464# define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
119465#endif
119466
119467SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
119468SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
119469
119470/* Special values interpreted by sqlite3SegReaderCursor() */
119471#define FTS3_SEGCURSOR_PENDING        -1
119472#define FTS3_SEGCURSOR_ALL            -2
119473
119474SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
119475SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
119476SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
119477
119478SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *,
119479    int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
119480
119481/* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
119482#define FTS3_SEGMENT_REQUIRE_POS   0x00000001
119483#define FTS3_SEGMENT_IGNORE_EMPTY  0x00000002
119484#define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
119485#define FTS3_SEGMENT_PREFIX        0x00000008
119486#define FTS3_SEGMENT_SCAN          0x00000010
119487#define FTS3_SEGMENT_FIRST         0x00000020
119488
119489/* Type passed as 4th argument to SegmentReaderIterate() */
119490struct Fts3SegFilter {
119491  const char *zTerm;
119492  int nTerm;
119493  int iCol;
119494  int flags;
119495};
119496
119497struct Fts3MultiSegReader {
119498  /* Used internally by sqlite3Fts3SegReaderXXX() calls */
119499  Fts3SegReader **apSegment;      /* Array of Fts3SegReader objects */
119500  int nSegment;                   /* Size of apSegment array */
119501  int nAdvance;                   /* How many seg-readers to advance */
119502  Fts3SegFilter *pFilter;         /* Pointer to filter object */
119503  char *aBuffer;                  /* Buffer to merge doclists in */
119504  int nBuffer;                    /* Allocated size of aBuffer[] in bytes */
119505
119506  int iColFilter;                 /* If >=0, filter for this column */
119507  int bRestart;
119508
119509  /* Used by fts3.c only. */
119510  int nCost;                      /* Cost of running iterator */
119511  int bLookup;                    /* True if a lookup of a single entry. */
119512
119513  /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
119514  char *zTerm;                    /* Pointer to term buffer */
119515  int nTerm;                      /* Size of zTerm in bytes */
119516  char *aDoclist;                 /* Pointer to doclist buffer */
119517  int nDoclist;                   /* Size of aDoclist[] in bytes */
119518};
119519
119520SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
119521
119522/* fts3.c */
119523SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
119524SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
119525SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
119526SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
119527SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
119528SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
119529SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
119530SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
119531SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
119532
119533/* fts3_tokenizer.c */
119534SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
119535SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
119536SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
119537    sqlite3_tokenizer **, char **
119538);
119539SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
119540
119541/* fts3_snippet.c */
119542SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
119543SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
119544  const char *, const char *, int, int
119545);
119546SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
119547
119548/* fts3_expr.c */
119549SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
119550  char **, int, int, int, const char *, int, Fts3Expr **, char **
119551);
119552SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
119553#ifdef SQLITE_TEST
119554SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
119555SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
119556#endif
119557
119558SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
119559  sqlite3_tokenizer_cursor **
119560);
119561
119562/* fts3_aux.c */
119563SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
119564
119565SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
119566
119567SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
119568    Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
119569SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
119570    Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
119571SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **);
119572SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
119573SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
119574
119575/* fts3_tokenize_vtab.c */
119576SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *);
119577
119578/* fts3_unicode2.c (functions generated by parsing unicode text files) */
119579#ifdef SQLITE_ENABLE_FTS4_UNICODE61
119580SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
119581SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
119582SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
119583#endif
119584
119585#endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
119586#endif /* _FTSINT_H */
119587
119588/************** End of fts3Int.h *********************************************/
119589/************** Continuing where we left off in fts3.c ***********************/
119590#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
119591
119592#if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
119593# define SQLITE_CORE 1
119594#endif
119595
119596/* #include <assert.h> */
119597/* #include <stdlib.h> */
119598/* #include <stddef.h> */
119599/* #include <stdio.h> */
119600/* #include <string.h> */
119601/* #include <stdarg.h> */
119602
119603#ifndef SQLITE_CORE
119604  SQLITE_EXTENSION_INIT1
119605#endif
119606
119607static int fts3EvalNext(Fts3Cursor *pCsr);
119608static int fts3EvalStart(Fts3Cursor *pCsr);
119609static int fts3TermSegReaderCursor(
119610    Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
119611
119612/*
119613** Write a 64-bit variable-length integer to memory starting at p[0].
119614** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
119615** The number of bytes written is returned.
119616*/
119617SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
119618  unsigned char *q = (unsigned char *) p;
119619  sqlite_uint64 vu = v;
119620  do{
119621    *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
119622    vu >>= 7;
119623  }while( vu!=0 );
119624  q[-1] &= 0x7f;  /* turn off high bit in final byte */
119625  assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
119626  return (int) (q - (unsigned char *)p);
119627}
119628
119629/*
119630** Read a 64-bit variable-length integer from memory starting at p[0].
119631** Return the number of bytes read, or 0 on error.
119632** The value is stored in *v.
119633*/
119634SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
119635  const unsigned char *q = (const unsigned char *) p;
119636  sqlite_uint64 x = 0, y = 1;
119637  while( (*q&0x80)==0x80 && q-(unsigned char *)p<FTS3_VARINT_MAX ){
119638    x += y * (*q++ & 0x7f);
119639    y <<= 7;
119640  }
119641  x += y * (*q++);
119642  *v = (sqlite_int64) x;
119643  return (int) (q - (unsigned char *)p);
119644}
119645
119646/*
119647** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
119648** 32-bit integer before it is returned.
119649*/
119650SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
119651 sqlite_int64 i;
119652 int ret = sqlite3Fts3GetVarint(p, &i);
119653 *pi = (int) i;
119654 return ret;
119655}
119656
119657/*
119658** Return the number of bytes required to encode v as a varint
119659*/
119660SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
119661  int i = 0;
119662  do{
119663    i++;
119664    v >>= 7;
119665  }while( v!=0 );
119666  return i;
119667}
119668
119669/*
119670** Convert an SQL-style quoted string into a normal string by removing
119671** the quote characters.  The conversion is done in-place.  If the
119672** input does not begin with a quote character, then this routine
119673** is a no-op.
119674**
119675** Examples:
119676**
119677**     "abc"   becomes   abc
119678**     'xyz'   becomes   xyz
119679**     [pqr]   becomes   pqr
119680**     `mno`   becomes   mno
119681**
119682*/
119683SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
119684  char quote;                     /* Quote character (if any ) */
119685
119686  quote = z[0];
119687  if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
119688    int iIn = 1;                  /* Index of next byte to read from input */
119689    int iOut = 0;                 /* Index of next byte to write to output */
119690
119691    /* If the first byte was a '[', then the close-quote character is a ']' */
119692    if( quote=='[' ) quote = ']';
119693
119694    while( ALWAYS(z[iIn]) ){
119695      if( z[iIn]==quote ){
119696        if( z[iIn+1]!=quote ) break;
119697        z[iOut++] = quote;
119698        iIn += 2;
119699      }else{
119700        z[iOut++] = z[iIn++];
119701      }
119702    }
119703    z[iOut] = '\0';
119704  }
119705}
119706
119707/*
119708** Read a single varint from the doclist at *pp and advance *pp to point
119709** to the first byte past the end of the varint.  Add the value of the varint
119710** to *pVal.
119711*/
119712static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
119713  sqlite3_int64 iVal;
119714  *pp += sqlite3Fts3GetVarint(*pp, &iVal);
119715  *pVal += iVal;
119716}
119717
119718/*
119719** When this function is called, *pp points to the first byte following a
119720** varint that is part of a doclist (or position-list, or any other list
119721** of varints). This function moves *pp to point to the start of that varint,
119722** and sets *pVal by the varint value.
119723**
119724** Argument pStart points to the first byte of the doclist that the
119725** varint is part of.
119726*/
119727static void fts3GetReverseVarint(
119728  char **pp,
119729  char *pStart,
119730  sqlite3_int64 *pVal
119731){
119732  sqlite3_int64 iVal;
119733  char *p;
119734
119735  /* Pointer p now points at the first byte past the varint we are
119736  ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
119737  ** clear on character p[-1]. */
119738  for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
119739  p++;
119740  *pp = p;
119741
119742  sqlite3Fts3GetVarint(p, &iVal);
119743  *pVal = iVal;
119744}
119745
119746/*
119747** The xDisconnect() virtual table method.
119748*/
119749static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
119750  Fts3Table *p = (Fts3Table *)pVtab;
119751  int i;
119752
119753  assert( p->nPendingData==0 );
119754  assert( p->pSegments==0 );
119755
119756  /* Free any prepared statements held */
119757  for(i=0; i<SizeofArray(p->aStmt); i++){
119758    sqlite3_finalize(p->aStmt[i]);
119759  }
119760  sqlite3_free(p->zSegmentsTbl);
119761  sqlite3_free(p->zReadExprlist);
119762  sqlite3_free(p->zWriteExprlist);
119763  sqlite3_free(p->zContentTbl);
119764  sqlite3_free(p->zLanguageid);
119765
119766  /* Invoke the tokenizer destructor to free the tokenizer. */
119767  p->pTokenizer->pModule->xDestroy(p->pTokenizer);
119768
119769  sqlite3_free(p);
119770  return SQLITE_OK;
119771}
119772
119773/*
119774** Construct one or more SQL statements from the format string given
119775** and then evaluate those statements. The success code is written
119776** into *pRc.
119777**
119778** If *pRc is initially non-zero then this routine is a no-op.
119779*/
119780static void fts3DbExec(
119781  int *pRc,              /* Success code */
119782  sqlite3 *db,           /* Database in which to run SQL */
119783  const char *zFormat,   /* Format string for SQL */
119784  ...                    /* Arguments to the format string */
119785){
119786  va_list ap;
119787  char *zSql;
119788  if( *pRc ) return;
119789  va_start(ap, zFormat);
119790  zSql = sqlite3_vmprintf(zFormat, ap);
119791  va_end(ap);
119792  if( zSql==0 ){
119793    *pRc = SQLITE_NOMEM;
119794  }else{
119795    *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
119796    sqlite3_free(zSql);
119797  }
119798}
119799
119800/*
119801** The xDestroy() virtual table method.
119802*/
119803static int fts3DestroyMethod(sqlite3_vtab *pVtab){
119804  Fts3Table *p = (Fts3Table *)pVtab;
119805  int rc = SQLITE_OK;              /* Return code */
119806  const char *zDb = p->zDb;        /* Name of database (e.g. "main", "temp") */
119807  sqlite3 *db = p->db;             /* Database handle */
119808
119809  /* Drop the shadow tables */
119810  if( p->zContentTbl==0 ){
119811    fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
119812  }
119813  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
119814  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
119815  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
119816  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
119817
119818  /* If everything has worked, invoke fts3DisconnectMethod() to free the
119819  ** memory associated with the Fts3Table structure and return SQLITE_OK.
119820  ** Otherwise, return an SQLite error code.
119821  */
119822  return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
119823}
119824
119825
119826/*
119827** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
119828** passed as the first argument. This is done as part of the xConnect()
119829** and xCreate() methods.
119830**
119831** If *pRc is non-zero when this function is called, it is a no-op.
119832** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
119833** before returning.
119834*/
119835static void fts3DeclareVtab(int *pRc, Fts3Table *p){
119836  if( *pRc==SQLITE_OK ){
119837    int i;                        /* Iterator variable */
119838    int rc;                       /* Return code */
119839    char *zSql;                   /* SQL statement passed to declare_vtab() */
119840    char *zCols;                  /* List of user defined columns */
119841    const char *zLanguageid;
119842
119843    zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
119844    sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
119845
119846    /* Create a list of user columns for the virtual table */
119847    zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
119848    for(i=1; zCols && i<p->nColumn; i++){
119849      zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
119850    }
119851
119852    /* Create the whole "CREATE TABLE" statement to pass to SQLite */
119853    zSql = sqlite3_mprintf(
119854        "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
119855        zCols, p->zName, zLanguageid
119856    );
119857    if( !zCols || !zSql ){
119858      rc = SQLITE_NOMEM;
119859    }else{
119860      rc = sqlite3_declare_vtab(p->db, zSql);
119861    }
119862
119863    sqlite3_free(zSql);
119864    sqlite3_free(zCols);
119865    *pRc = rc;
119866  }
119867}
119868
119869/*
119870** Create the %_stat table if it does not already exist.
119871*/
119872SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
119873  fts3DbExec(pRc, p->db,
119874      "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
119875          "(id INTEGER PRIMARY KEY, value BLOB);",
119876      p->zDb, p->zName
119877  );
119878  if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
119879}
119880
119881/*
119882** Create the backing store tables (%_content, %_segments and %_segdir)
119883** required by the FTS3 table passed as the only argument. This is done
119884** as part of the vtab xCreate() method.
119885**
119886** If the p->bHasDocsize boolean is true (indicating that this is an
119887** FTS4 table, not an FTS3 table) then also create the %_docsize and
119888** %_stat tables required by FTS4.
119889*/
119890static int fts3CreateTables(Fts3Table *p){
119891  int rc = SQLITE_OK;             /* Return code */
119892  int i;                          /* Iterator variable */
119893  sqlite3 *db = p->db;            /* The database connection */
119894
119895  if( p->zContentTbl==0 ){
119896    const char *zLanguageid = p->zLanguageid;
119897    char *zContentCols;           /* Columns of %_content table */
119898
119899    /* Create a list of user columns for the content table */
119900    zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
119901    for(i=0; zContentCols && i<p->nColumn; i++){
119902      char *z = p->azColumn[i];
119903      zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
119904    }
119905    if( zLanguageid && zContentCols ){
119906      zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
119907    }
119908    if( zContentCols==0 ) rc = SQLITE_NOMEM;
119909
119910    /* Create the content table */
119911    fts3DbExec(&rc, db,
119912       "CREATE TABLE %Q.'%q_content'(%s)",
119913       p->zDb, p->zName, zContentCols
119914    );
119915    sqlite3_free(zContentCols);
119916  }
119917
119918  /* Create other tables */
119919  fts3DbExec(&rc, db,
119920      "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
119921      p->zDb, p->zName
119922  );
119923  fts3DbExec(&rc, db,
119924      "CREATE TABLE %Q.'%q_segdir'("
119925        "level INTEGER,"
119926        "idx INTEGER,"
119927        "start_block INTEGER,"
119928        "leaves_end_block INTEGER,"
119929        "end_block INTEGER,"
119930        "root BLOB,"
119931        "PRIMARY KEY(level, idx)"
119932      ");",
119933      p->zDb, p->zName
119934  );
119935  if( p->bHasDocsize ){
119936    fts3DbExec(&rc, db,
119937        "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
119938        p->zDb, p->zName
119939    );
119940  }
119941  assert( p->bHasStat==p->bFts4 );
119942  if( p->bHasStat ){
119943    sqlite3Fts3CreateStatTable(&rc, p);
119944  }
119945  return rc;
119946}
119947
119948/*
119949** Store the current database page-size in bytes in p->nPgsz.
119950**
119951** If *pRc is non-zero when this function is called, it is a no-op.
119952** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
119953** before returning.
119954*/
119955static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
119956  if( *pRc==SQLITE_OK ){
119957    int rc;                       /* Return code */
119958    char *zSql;                   /* SQL text "PRAGMA %Q.page_size" */
119959    sqlite3_stmt *pStmt;          /* Compiled "PRAGMA %Q.page_size" statement */
119960
119961    zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
119962    if( !zSql ){
119963      rc = SQLITE_NOMEM;
119964    }else{
119965      rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
119966      if( rc==SQLITE_OK ){
119967        sqlite3_step(pStmt);
119968        p->nPgsz = sqlite3_column_int(pStmt, 0);
119969        rc = sqlite3_finalize(pStmt);
119970      }else if( rc==SQLITE_AUTH ){
119971        p->nPgsz = 1024;
119972        rc = SQLITE_OK;
119973      }
119974    }
119975    assert( p->nPgsz>0 || rc!=SQLITE_OK );
119976    sqlite3_free(zSql);
119977    *pRc = rc;
119978  }
119979}
119980
119981/*
119982** "Special" FTS4 arguments are column specifications of the following form:
119983**
119984**   <key> = <value>
119985**
119986** There may not be whitespace surrounding the "=" character. The <value>
119987** term may be quoted, but the <key> may not.
119988*/
119989static int fts3IsSpecialColumn(
119990  const char *z,
119991  int *pnKey,
119992  char **pzValue
119993){
119994  char *zValue;
119995  const char *zCsr = z;
119996
119997  while( *zCsr!='=' ){
119998    if( *zCsr=='\0' ) return 0;
119999    zCsr++;
120000  }
120001
120002  *pnKey = (int)(zCsr-z);
120003  zValue = sqlite3_mprintf("%s", &zCsr[1]);
120004  if( zValue ){
120005    sqlite3Fts3Dequote(zValue);
120006  }
120007  *pzValue = zValue;
120008  return 1;
120009}
120010
120011/*
120012** Append the output of a printf() style formatting to an existing string.
120013*/
120014static void fts3Appendf(
120015  int *pRc,                       /* IN/OUT: Error code */
120016  char **pz,                      /* IN/OUT: Pointer to string buffer */
120017  const char *zFormat,            /* Printf format string to append */
120018  ...                             /* Arguments for printf format string */
120019){
120020  if( *pRc==SQLITE_OK ){
120021    va_list ap;
120022    char *z;
120023    va_start(ap, zFormat);
120024    z = sqlite3_vmprintf(zFormat, ap);
120025    va_end(ap);
120026    if( z && *pz ){
120027      char *z2 = sqlite3_mprintf("%s%s", *pz, z);
120028      sqlite3_free(z);
120029      z = z2;
120030    }
120031    if( z==0 ) *pRc = SQLITE_NOMEM;
120032    sqlite3_free(*pz);
120033    *pz = z;
120034  }
120035}
120036
120037/*
120038** Return a copy of input string zInput enclosed in double-quotes (") and
120039** with all double quote characters escaped. For example:
120040**
120041**     fts3QuoteId("un \"zip\"")   ->    "un \"\"zip\"\""
120042**
120043** The pointer returned points to memory obtained from sqlite3_malloc(). It
120044** is the callers responsibility to call sqlite3_free() to release this
120045** memory.
120046*/
120047static char *fts3QuoteId(char const *zInput){
120048  int nRet;
120049  char *zRet;
120050  nRet = 2 + (int)strlen(zInput)*2 + 1;
120051  zRet = sqlite3_malloc(nRet);
120052  if( zRet ){
120053    int i;
120054    char *z = zRet;
120055    *(z++) = '"';
120056    for(i=0; zInput[i]; i++){
120057      if( zInput[i]=='"' ) *(z++) = '"';
120058      *(z++) = zInput[i];
120059    }
120060    *(z++) = '"';
120061    *(z++) = '\0';
120062  }
120063  return zRet;
120064}
120065
120066/*
120067** Return a list of comma separated SQL expressions and a FROM clause that
120068** could be used in a SELECT statement such as the following:
120069**
120070**     SELECT <list of expressions> FROM %_content AS x ...
120071**
120072** to return the docid, followed by each column of text data in order
120073** from left to write. If parameter zFunc is not NULL, then instead of
120074** being returned directly each column of text data is passed to an SQL
120075** function named zFunc first. For example, if zFunc is "unzip" and the
120076** table has the three user-defined columns "a", "b", and "c", the following
120077** string is returned:
120078**
120079**     "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
120080**
120081** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
120082** is the responsibility of the caller to eventually free it.
120083**
120084** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
120085** a NULL pointer is returned). Otherwise, if an OOM error is encountered
120086** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
120087** no error occurs, *pRc is left unmodified.
120088*/
120089static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
120090  char *zRet = 0;
120091  char *zFree = 0;
120092  char *zFunction;
120093  int i;
120094
120095  if( p->zContentTbl==0 ){
120096    if( !zFunc ){
120097      zFunction = "";
120098    }else{
120099      zFree = zFunction = fts3QuoteId(zFunc);
120100    }
120101    fts3Appendf(pRc, &zRet, "docid");
120102    for(i=0; i<p->nColumn; i++){
120103      fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
120104    }
120105    if( p->zLanguageid ){
120106      fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
120107    }
120108    sqlite3_free(zFree);
120109  }else{
120110    fts3Appendf(pRc, &zRet, "rowid");
120111    for(i=0; i<p->nColumn; i++){
120112      fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
120113    }
120114    if( p->zLanguageid ){
120115      fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
120116    }
120117  }
120118  fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
120119      p->zDb,
120120      (p->zContentTbl ? p->zContentTbl : p->zName),
120121      (p->zContentTbl ? "" : "_content")
120122  );
120123  return zRet;
120124}
120125
120126/*
120127** Return a list of N comma separated question marks, where N is the number
120128** of columns in the %_content table (one for the docid plus one for each
120129** user-defined text column).
120130**
120131** If argument zFunc is not NULL, then all but the first question mark
120132** is preceded by zFunc and an open bracket, and followed by a closed
120133** bracket. For example, if zFunc is "zip" and the FTS3 table has three
120134** user-defined text columns, the following string is returned:
120135**
120136**     "?, zip(?), zip(?), zip(?)"
120137**
120138** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
120139** is the responsibility of the caller to eventually free it.
120140**
120141** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
120142** a NULL pointer is returned). Otherwise, if an OOM error is encountered
120143** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
120144** no error occurs, *pRc is left unmodified.
120145*/
120146static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
120147  char *zRet = 0;
120148  char *zFree = 0;
120149  char *zFunction;
120150  int i;
120151
120152  if( !zFunc ){
120153    zFunction = "";
120154  }else{
120155    zFree = zFunction = fts3QuoteId(zFunc);
120156  }
120157  fts3Appendf(pRc, &zRet, "?");
120158  for(i=0; i<p->nColumn; i++){
120159    fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
120160  }
120161  if( p->zLanguageid ){
120162    fts3Appendf(pRc, &zRet, ", ?");
120163  }
120164  sqlite3_free(zFree);
120165  return zRet;
120166}
120167
120168/*
120169** This function interprets the string at (*pp) as a non-negative integer
120170** value. It reads the integer and sets *pnOut to the value read, then
120171** sets *pp to point to the byte immediately following the last byte of
120172** the integer value.
120173**
120174** Only decimal digits ('0'..'9') may be part of an integer value.
120175**
120176** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
120177** the output value undefined. Otherwise SQLITE_OK is returned.
120178**
120179** This function is used when parsing the "prefix=" FTS4 parameter.
120180*/
120181static int fts3GobbleInt(const char **pp, int *pnOut){
120182  const char *p;                  /* Iterator pointer */
120183  int nInt = 0;                   /* Output value */
120184
120185  for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
120186    nInt = nInt * 10 + (p[0] - '0');
120187  }
120188  if( p==*pp ) return SQLITE_ERROR;
120189  *pnOut = nInt;
120190  *pp = p;
120191  return SQLITE_OK;
120192}
120193
120194/*
120195** This function is called to allocate an array of Fts3Index structures
120196** representing the indexes maintained by the current FTS table. FTS tables
120197** always maintain the main "terms" index, but may also maintain one or
120198** more "prefix" indexes, depending on the value of the "prefix=" parameter
120199** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
120200**
120201** Argument zParam is passed the value of the "prefix=" option if one was
120202** specified, or NULL otherwise.
120203**
120204** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
120205** the allocated array. *pnIndex is set to the number of elements in the
120206** array. If an error does occur, an SQLite error code is returned.
120207**
120208** Regardless of whether or not an error is returned, it is the responsibility
120209** of the caller to call sqlite3_free() on the output array to free it.
120210*/
120211static int fts3PrefixParameter(
120212  const char *zParam,             /* ABC in prefix=ABC parameter to parse */
120213  int *pnIndex,                   /* OUT: size of *apIndex[] array */
120214  struct Fts3Index **apIndex      /* OUT: Array of indexes for this table */
120215){
120216  struct Fts3Index *aIndex;       /* Allocated array */
120217  int nIndex = 1;                 /* Number of entries in array */
120218
120219  if( zParam && zParam[0] ){
120220    const char *p;
120221    nIndex++;
120222    for(p=zParam; *p; p++){
120223      if( *p==',' ) nIndex++;
120224    }
120225  }
120226
120227  aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
120228  *apIndex = aIndex;
120229  *pnIndex = nIndex;
120230  if( !aIndex ){
120231    return SQLITE_NOMEM;
120232  }
120233
120234  memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
120235  if( zParam ){
120236    const char *p = zParam;
120237    int i;
120238    for(i=1; i<nIndex; i++){
120239      int nPrefix;
120240      if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
120241      aIndex[i].nPrefix = nPrefix;
120242      p++;
120243    }
120244  }
120245
120246  return SQLITE_OK;
120247}
120248
120249/*
120250** This function is called when initializing an FTS4 table that uses the
120251** content=xxx option. It determines the number of and names of the columns
120252** of the new FTS4 table.
120253**
120254** The third argument passed to this function is the value passed to the
120255** config=xxx option (i.e. "xxx"). This function queries the database for
120256** a table of that name. If found, the output variables are populated
120257** as follows:
120258**
120259**   *pnCol:   Set to the number of columns table xxx has,
120260**
120261**   *pnStr:   Set to the total amount of space required to store a copy
120262**             of each columns name, including the nul-terminator.
120263**
120264**   *pazCol:  Set to point to an array of *pnCol strings. Each string is
120265**             the name of the corresponding column in table xxx. The array
120266**             and its contents are allocated using a single allocation. It
120267**             is the responsibility of the caller to free this allocation
120268**             by eventually passing the *pazCol value to sqlite3_free().
120269**
120270** If the table cannot be found, an error code is returned and the output
120271** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
120272** returned (and the output variables are undefined).
120273*/
120274static int fts3ContentColumns(
120275  sqlite3 *db,                    /* Database handle */
120276  const char *zDb,                /* Name of db (i.e. "main", "temp" etc.) */
120277  const char *zTbl,               /* Name of content table */
120278  const char ***pazCol,           /* OUT: Malloc'd array of column names */
120279  int *pnCol,                     /* OUT: Size of array *pazCol */
120280  int *pnStr                      /* OUT: Bytes of string content */
120281){
120282  int rc = SQLITE_OK;             /* Return code */
120283  char *zSql;                     /* "SELECT *" statement on zTbl */
120284  sqlite3_stmt *pStmt = 0;        /* Compiled version of zSql */
120285
120286  zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
120287  if( !zSql ){
120288    rc = SQLITE_NOMEM;
120289  }else{
120290    rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
120291  }
120292  sqlite3_free(zSql);
120293
120294  if( rc==SQLITE_OK ){
120295    const char **azCol;           /* Output array */
120296    int nStr = 0;                 /* Size of all column names (incl. 0x00) */
120297    int nCol;                     /* Number of table columns */
120298    int i;                        /* Used to iterate through columns */
120299
120300    /* Loop through the returned columns. Set nStr to the number of bytes of
120301    ** space required to store a copy of each column name, including the
120302    ** nul-terminator byte.  */
120303    nCol = sqlite3_column_count(pStmt);
120304    for(i=0; i<nCol; i++){
120305      const char *zCol = sqlite3_column_name(pStmt, i);
120306      nStr += (int)strlen(zCol) + 1;
120307    }
120308
120309    /* Allocate and populate the array to return. */
120310    azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
120311    if( azCol==0 ){
120312      rc = SQLITE_NOMEM;
120313    }else{
120314      char *p = (char *)&azCol[nCol];
120315      for(i=0; i<nCol; i++){
120316        const char *zCol = sqlite3_column_name(pStmt, i);
120317        int n = (int)strlen(zCol)+1;
120318        memcpy(p, zCol, n);
120319        azCol[i] = p;
120320        p += n;
120321      }
120322    }
120323    sqlite3_finalize(pStmt);
120324
120325    /* Set the output variables. */
120326    *pnCol = nCol;
120327    *pnStr = nStr;
120328    *pazCol = azCol;
120329  }
120330
120331  return rc;
120332}
120333
120334/*
120335** This function is the implementation of both the xConnect and xCreate
120336** methods of the FTS3 virtual table.
120337**
120338** The argv[] array contains the following:
120339**
120340**   argv[0]   -> module name  ("fts3" or "fts4")
120341**   argv[1]   -> database name
120342**   argv[2]   -> table name
120343**   argv[...] -> "column name" and other module argument fields.
120344*/
120345static int fts3InitVtab(
120346  int isCreate,                   /* True for xCreate, false for xConnect */
120347  sqlite3 *db,                    /* The SQLite database connection */
120348  void *pAux,                     /* Hash table containing tokenizers */
120349  int argc,                       /* Number of elements in argv array */
120350  const char * const *argv,       /* xCreate/xConnect argument array */
120351  sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
120352  char **pzErr                    /* Write any error message here */
120353){
120354  Fts3Hash *pHash = (Fts3Hash *)pAux;
120355  Fts3Table *p = 0;               /* Pointer to allocated vtab */
120356  int rc = SQLITE_OK;             /* Return code */
120357  int i;                          /* Iterator variable */
120358  int nByte;                      /* Size of allocation used for *p */
120359  int iCol;                       /* Column index */
120360  int nString = 0;                /* Bytes required to hold all column names */
120361  int nCol = 0;                   /* Number of columns in the FTS table */
120362  char *zCsr;                     /* Space for holding column names */
120363  int nDb;                        /* Bytes required to hold database name */
120364  int nName;                      /* Bytes required to hold table name */
120365  int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
120366  const char **aCol;              /* Array of column names */
120367  sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
120368
120369  int nIndex;                     /* Size of aIndex[] array */
120370  struct Fts3Index *aIndex = 0;   /* Array of indexes for this table */
120371
120372  /* The results of parsing supported FTS4 key=value options: */
120373  int bNoDocsize = 0;             /* True to omit %_docsize table */
120374  int bDescIdx = 0;               /* True to store descending indexes */
120375  char *zPrefix = 0;              /* Prefix parameter value (or NULL) */
120376  char *zCompress = 0;            /* compress=? parameter (or NULL) */
120377  char *zUncompress = 0;          /* uncompress=? parameter (or NULL) */
120378  char *zContent = 0;             /* content=? parameter (or NULL) */
120379  char *zLanguageid = 0;          /* languageid=? parameter (or NULL) */
120380
120381  assert( strlen(argv[0])==4 );
120382  assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
120383       || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
120384  );
120385
120386  nDb = (int)strlen(argv[1]) + 1;
120387  nName = (int)strlen(argv[2]) + 1;
120388
120389  aCol = (const char **)sqlite3_malloc(sizeof(const char *) * (argc-2) );
120390  if( !aCol ) return SQLITE_NOMEM;
120391  memset((void *)aCol, 0, sizeof(const char *) * (argc-2));
120392
120393  /* Loop through all of the arguments passed by the user to the FTS3/4
120394  ** module (i.e. all the column names and special arguments). This loop
120395  ** does the following:
120396  **
120397  **   + Figures out the number of columns the FTSX table will have, and
120398  **     the number of bytes of space that must be allocated to store copies
120399  **     of the column names.
120400  **
120401  **   + If there is a tokenizer specification included in the arguments,
120402  **     initializes the tokenizer pTokenizer.
120403  */
120404  for(i=3; rc==SQLITE_OK && i<argc; i++){
120405    char const *z = argv[i];
120406    int nKey;
120407    char *zVal;
120408
120409    /* Check if this is a tokenizer specification */
120410    if( !pTokenizer
120411     && strlen(z)>8
120412     && 0==sqlite3_strnicmp(z, "tokenize", 8)
120413     && 0==sqlite3Fts3IsIdChar(z[8])
120414    ){
120415      rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
120416    }
120417
120418    /* Check if it is an FTS4 special argument. */
120419    else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
120420      struct Fts4Option {
120421        const char *zOpt;
120422        int nOpt;
120423      } aFts4Opt[] = {
120424        { "matchinfo",   9 },     /* 0 -> MATCHINFO */
120425        { "prefix",      6 },     /* 1 -> PREFIX */
120426        { "compress",    8 },     /* 2 -> COMPRESS */
120427        { "uncompress", 10 },     /* 3 -> UNCOMPRESS */
120428        { "order",       5 },     /* 4 -> ORDER */
120429        { "content",     7 },     /* 5 -> CONTENT */
120430        { "languageid", 10 }      /* 6 -> LANGUAGEID */
120431      };
120432
120433      int iOpt;
120434      if( !zVal ){
120435        rc = SQLITE_NOMEM;
120436      }else{
120437        for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
120438          struct Fts4Option *pOp = &aFts4Opt[iOpt];
120439          if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
120440            break;
120441          }
120442        }
120443        if( iOpt==SizeofArray(aFts4Opt) ){
120444          *pzErr = sqlite3_mprintf("unrecognized parameter: %s", z);
120445          rc = SQLITE_ERROR;
120446        }else{
120447          switch( iOpt ){
120448            case 0:               /* MATCHINFO */
120449              if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
120450                *pzErr = sqlite3_mprintf("unrecognized matchinfo: %s", zVal);
120451                rc = SQLITE_ERROR;
120452              }
120453              bNoDocsize = 1;
120454              break;
120455
120456            case 1:               /* PREFIX */
120457              sqlite3_free(zPrefix);
120458              zPrefix = zVal;
120459              zVal = 0;
120460              break;
120461
120462            case 2:               /* COMPRESS */
120463              sqlite3_free(zCompress);
120464              zCompress = zVal;
120465              zVal = 0;
120466              break;
120467
120468            case 3:               /* UNCOMPRESS */
120469              sqlite3_free(zUncompress);
120470              zUncompress = zVal;
120471              zVal = 0;
120472              break;
120473
120474            case 4:               /* ORDER */
120475              if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
120476               && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
120477              ){
120478                *pzErr = sqlite3_mprintf("unrecognized order: %s", zVal);
120479                rc = SQLITE_ERROR;
120480              }
120481              bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
120482              break;
120483
120484            case 5:              /* CONTENT */
120485              sqlite3_free(zContent);
120486              zContent = zVal;
120487              zVal = 0;
120488              break;
120489
120490            case 6:              /* LANGUAGEID */
120491              assert( iOpt==6 );
120492              sqlite3_free(zLanguageid);
120493              zLanguageid = zVal;
120494              zVal = 0;
120495              break;
120496          }
120497        }
120498        sqlite3_free(zVal);
120499      }
120500    }
120501
120502    /* Otherwise, the argument is a column name. */
120503    else {
120504      nString += (int)(strlen(z) + 1);
120505      aCol[nCol++] = z;
120506    }
120507  }
120508
120509  /* If a content=xxx option was specified, the following:
120510  **
120511  **   1. Ignore any compress= and uncompress= options.
120512  **
120513  **   2. If no column names were specified as part of the CREATE VIRTUAL
120514  **      TABLE statement, use all columns from the content table.
120515  */
120516  if( rc==SQLITE_OK && zContent ){
120517    sqlite3_free(zCompress);
120518    sqlite3_free(zUncompress);
120519    zCompress = 0;
120520    zUncompress = 0;
120521    if( nCol==0 ){
120522      sqlite3_free((void*)aCol);
120523      aCol = 0;
120524      rc = fts3ContentColumns(db, argv[1], zContent, &aCol, &nCol, &nString);
120525
120526      /* If a languageid= option was specified, remove the language id
120527      ** column from the aCol[] array. */
120528      if( rc==SQLITE_OK && zLanguageid ){
120529        int j;
120530        for(j=0; j<nCol; j++){
120531          if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
120532            int k;
120533            for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
120534            nCol--;
120535            break;
120536          }
120537        }
120538      }
120539    }
120540  }
120541  if( rc!=SQLITE_OK ) goto fts3_init_out;
120542
120543  if( nCol==0 ){
120544    assert( nString==0 );
120545    aCol[0] = "content";
120546    nString = 8;
120547    nCol = 1;
120548  }
120549
120550  if( pTokenizer==0 ){
120551    rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
120552    if( rc!=SQLITE_OK ) goto fts3_init_out;
120553  }
120554  assert( pTokenizer );
120555
120556  rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
120557  if( rc==SQLITE_ERROR ){
120558    assert( zPrefix );
120559    *pzErr = sqlite3_mprintf("error parsing prefix parameter: %s", zPrefix);
120560  }
120561  if( rc!=SQLITE_OK ) goto fts3_init_out;
120562
120563  /* Allocate and populate the Fts3Table structure. */
120564  nByte = sizeof(Fts3Table) +                  /* Fts3Table */
120565          nCol * sizeof(char *) +              /* azColumn */
120566          nIndex * sizeof(struct Fts3Index) +  /* aIndex */
120567          nName +                              /* zName */
120568          nDb +                                /* zDb */
120569          nString;                             /* Space for azColumn strings */
120570  p = (Fts3Table*)sqlite3_malloc(nByte);
120571  if( p==0 ){
120572    rc = SQLITE_NOMEM;
120573    goto fts3_init_out;
120574  }
120575  memset(p, 0, nByte);
120576  p->db = db;
120577  p->nColumn = nCol;
120578  p->nPendingData = 0;
120579  p->azColumn = (char **)&p[1];
120580  p->pTokenizer = pTokenizer;
120581  p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
120582  p->bHasDocsize = (isFts4 && bNoDocsize==0);
120583  p->bHasStat = isFts4;
120584  p->bFts4 = isFts4;
120585  p->bDescIdx = bDescIdx;
120586  p->bAutoincrmerge = 0xff;   /* 0xff means setting unknown */
120587  p->zContentTbl = zContent;
120588  p->zLanguageid = zLanguageid;
120589  zContent = 0;
120590  zLanguageid = 0;
120591  TESTONLY( p->inTransaction = -1 );
120592  TESTONLY( p->mxSavepoint = -1 );
120593
120594  p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
120595  memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
120596  p->nIndex = nIndex;
120597  for(i=0; i<nIndex; i++){
120598    fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
120599  }
120600
120601  /* Fill in the zName and zDb fields of the vtab structure. */
120602  zCsr = (char *)&p->aIndex[nIndex];
120603  p->zName = zCsr;
120604  memcpy(zCsr, argv[2], nName);
120605  zCsr += nName;
120606  p->zDb = zCsr;
120607  memcpy(zCsr, argv[1], nDb);
120608  zCsr += nDb;
120609
120610  /* Fill in the azColumn array */
120611  for(iCol=0; iCol<nCol; iCol++){
120612    char *z;
120613    int n = 0;
120614    z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
120615    memcpy(zCsr, z, n);
120616    zCsr[n] = '\0';
120617    sqlite3Fts3Dequote(zCsr);
120618    p->azColumn[iCol] = zCsr;
120619    zCsr += n+1;
120620    assert( zCsr <= &((char *)p)[nByte] );
120621  }
120622
120623  if( (zCompress==0)!=(zUncompress==0) ){
120624    char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
120625    rc = SQLITE_ERROR;
120626    *pzErr = sqlite3_mprintf("missing %s parameter in fts4 constructor", zMiss);
120627  }
120628  p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
120629  p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
120630  if( rc!=SQLITE_OK ) goto fts3_init_out;
120631
120632  /* If this is an xCreate call, create the underlying tables in the
120633  ** database. TODO: For xConnect(), it could verify that said tables exist.
120634  */
120635  if( isCreate ){
120636    rc = fts3CreateTables(p);
120637  }
120638
120639  /* Check to see if a legacy fts3 table has been "upgraded" by the
120640  ** addition of a %_stat table so that it can use incremental merge.
120641  */
120642  if( !isFts4 && !isCreate ){
120643    int rc2 = SQLITE_OK;
120644    fts3DbExec(&rc2, db, "SELECT 1 FROM %Q.'%q_stat' WHERE id=2",
120645               p->zDb, p->zName);
120646    if( rc2==SQLITE_OK ) p->bHasStat = 1;
120647  }
120648
120649  /* Figure out the page-size for the database. This is required in order to
120650  ** estimate the cost of loading large doclists from the database.  */
120651  fts3DatabasePageSize(&rc, p);
120652  p->nNodeSize = p->nPgsz-35;
120653
120654  /* Declare the table schema to SQLite. */
120655  fts3DeclareVtab(&rc, p);
120656
120657fts3_init_out:
120658  sqlite3_free(zPrefix);
120659  sqlite3_free(aIndex);
120660  sqlite3_free(zCompress);
120661  sqlite3_free(zUncompress);
120662  sqlite3_free(zContent);
120663  sqlite3_free(zLanguageid);
120664  sqlite3_free((void *)aCol);
120665  if( rc!=SQLITE_OK ){
120666    if( p ){
120667      fts3DisconnectMethod((sqlite3_vtab *)p);
120668    }else if( pTokenizer ){
120669      pTokenizer->pModule->xDestroy(pTokenizer);
120670    }
120671  }else{
120672    assert( p->pSegments==0 );
120673    *ppVTab = &p->base;
120674  }
120675  return rc;
120676}
120677
120678/*
120679** The xConnect() and xCreate() methods for the virtual table. All the
120680** work is done in function fts3InitVtab().
120681*/
120682static int fts3ConnectMethod(
120683  sqlite3 *db,                    /* Database connection */
120684  void *pAux,                     /* Pointer to tokenizer hash table */
120685  int argc,                       /* Number of elements in argv array */
120686  const char * const *argv,       /* xCreate/xConnect argument array */
120687  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
120688  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
120689){
120690  return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
120691}
120692static int fts3CreateMethod(
120693  sqlite3 *db,                    /* Database connection */
120694  void *pAux,                     /* Pointer to tokenizer hash table */
120695  int argc,                       /* Number of elements in argv array */
120696  const char * const *argv,       /* xCreate/xConnect argument array */
120697  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
120698  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
120699){
120700  return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
120701}
120702
120703/*
120704** Implementation of the xBestIndex method for FTS3 tables. There
120705** are three possible strategies, in order of preference:
120706**
120707**   1. Direct lookup by rowid or docid.
120708**   2. Full-text search using a MATCH operator on a non-docid column.
120709**   3. Linear scan of %_content table.
120710*/
120711static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
120712  Fts3Table *p = (Fts3Table *)pVTab;
120713  int i;                          /* Iterator variable */
120714  int iCons = -1;                 /* Index of constraint to use */
120715  int iLangidCons = -1;           /* Index of langid=x constraint, if present */
120716
120717  /* By default use a full table scan. This is an expensive option,
120718  ** so search through the constraints to see if a more efficient
120719  ** strategy is possible.
120720  */
120721  pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
120722  pInfo->estimatedCost = 500000;
120723  for(i=0; i<pInfo->nConstraint; i++){
120724    struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
120725    if( pCons->usable==0 ) continue;
120726
120727    /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
120728    if( iCons<0
120729     && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
120730     && (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1 )
120731    ){
120732      pInfo->idxNum = FTS3_DOCID_SEARCH;
120733      pInfo->estimatedCost = 1.0;
120734      iCons = i;
120735    }
120736
120737    /* A MATCH constraint. Use a full-text search.
120738    **
120739    ** If there is more than one MATCH constraint available, use the first
120740    ** one encountered. If there is both a MATCH constraint and a direct
120741    ** rowid/docid lookup, prefer the MATCH strategy. This is done even
120742    ** though the rowid/docid lookup is faster than a MATCH query, selecting
120743    ** it would lead to an "unable to use function MATCH in the requested
120744    ** context" error.
120745    */
120746    if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
120747     && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
120748    ){
120749      pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
120750      pInfo->estimatedCost = 2.0;
120751      iCons = i;
120752    }
120753
120754    /* Equality constraint on the langid column */
120755    if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
120756     && pCons->iColumn==p->nColumn + 2
120757    ){
120758      iLangidCons = i;
120759    }
120760  }
120761
120762  if( iCons>=0 ){
120763    pInfo->aConstraintUsage[iCons].argvIndex = 1;
120764    pInfo->aConstraintUsage[iCons].omit = 1;
120765  }
120766  if( iLangidCons>=0 ){
120767    pInfo->aConstraintUsage[iLangidCons].argvIndex = 2;
120768  }
120769
120770  /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
120771  ** docid) order. Both ascending and descending are possible.
120772  */
120773  if( pInfo->nOrderBy==1 ){
120774    struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
120775    if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
120776      if( pOrder->desc ){
120777        pInfo->idxStr = "DESC";
120778      }else{
120779        pInfo->idxStr = "ASC";
120780      }
120781      pInfo->orderByConsumed = 1;
120782    }
120783  }
120784
120785  assert( p->pSegments==0 );
120786  return SQLITE_OK;
120787}
120788
120789/*
120790** Implementation of xOpen method.
120791*/
120792static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
120793  sqlite3_vtab_cursor *pCsr;               /* Allocated cursor */
120794
120795  UNUSED_PARAMETER(pVTab);
120796
120797  /* Allocate a buffer large enough for an Fts3Cursor structure. If the
120798  ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
120799  ** if the allocation fails, return SQLITE_NOMEM.
120800  */
120801  *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
120802  if( !pCsr ){
120803    return SQLITE_NOMEM;
120804  }
120805  memset(pCsr, 0, sizeof(Fts3Cursor));
120806  return SQLITE_OK;
120807}
120808
120809/*
120810** Close the cursor.  For additional information see the documentation
120811** on the xClose method of the virtual table interface.
120812*/
120813static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
120814  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
120815  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
120816  sqlite3_finalize(pCsr->pStmt);
120817  sqlite3Fts3ExprFree(pCsr->pExpr);
120818  sqlite3Fts3FreeDeferredTokens(pCsr);
120819  sqlite3_free(pCsr->aDoclist);
120820  sqlite3_free(pCsr->aMatchinfo);
120821  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
120822  sqlite3_free(pCsr);
120823  return SQLITE_OK;
120824}
120825
120826/*
120827** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
120828** compose and prepare an SQL statement of the form:
120829**
120830**    "SELECT <columns> FROM %_content WHERE rowid = ?"
120831**
120832** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
120833** it. If an error occurs, return an SQLite error code.
120834**
120835** Otherwise, set *ppStmt to point to pCsr->pStmt and return SQLITE_OK.
120836*/
120837static int fts3CursorSeekStmt(Fts3Cursor *pCsr, sqlite3_stmt **ppStmt){
120838  int rc = SQLITE_OK;
120839  if( pCsr->pStmt==0 ){
120840    Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
120841    char *zSql;
120842    zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
120843    if( !zSql ) return SQLITE_NOMEM;
120844    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
120845    sqlite3_free(zSql);
120846  }
120847  *ppStmt = pCsr->pStmt;
120848  return rc;
120849}
120850
120851/*
120852** Position the pCsr->pStmt statement so that it is on the row
120853** of the %_content table that contains the last match.  Return
120854** SQLITE_OK on success.
120855*/
120856static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
120857  int rc = SQLITE_OK;
120858  if( pCsr->isRequireSeek ){
120859    sqlite3_stmt *pStmt = 0;
120860
120861    rc = fts3CursorSeekStmt(pCsr, &pStmt);
120862    if( rc==SQLITE_OK ){
120863      sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
120864      pCsr->isRequireSeek = 0;
120865      if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
120866        return SQLITE_OK;
120867      }else{
120868        rc = sqlite3_reset(pCsr->pStmt);
120869        if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
120870          /* If no row was found and no error has occurred, then the %_content
120871          ** table is missing a row that is present in the full-text index.
120872          ** The data structures are corrupt.  */
120873          rc = FTS_CORRUPT_VTAB;
120874          pCsr->isEof = 1;
120875        }
120876      }
120877    }
120878  }
120879
120880  if( rc!=SQLITE_OK && pContext ){
120881    sqlite3_result_error_code(pContext, rc);
120882  }
120883  return rc;
120884}
120885
120886/*
120887** This function is used to process a single interior node when searching
120888** a b-tree for a term or term prefix. The node data is passed to this
120889** function via the zNode/nNode parameters. The term to search for is
120890** passed in zTerm/nTerm.
120891**
120892** If piFirst is not NULL, then this function sets *piFirst to the blockid
120893** of the child node that heads the sub-tree that may contain the term.
120894**
120895** If piLast is not NULL, then *piLast is set to the right-most child node
120896** that heads a sub-tree that may contain a term for which zTerm/nTerm is
120897** a prefix.
120898**
120899** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
120900*/
120901static int fts3ScanInteriorNode(
120902  const char *zTerm,              /* Term to select leaves for */
120903  int nTerm,                      /* Size of term zTerm in bytes */
120904  const char *zNode,              /* Buffer containing segment interior node */
120905  int nNode,                      /* Size of buffer at zNode */
120906  sqlite3_int64 *piFirst,         /* OUT: Selected child node */
120907  sqlite3_int64 *piLast           /* OUT: Selected child node */
120908){
120909  int rc = SQLITE_OK;             /* Return code */
120910  const char *zCsr = zNode;       /* Cursor to iterate through node */
120911  const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
120912  char *zBuffer = 0;              /* Buffer to load terms into */
120913  int nAlloc = 0;                 /* Size of allocated buffer */
120914  int isFirstTerm = 1;            /* True when processing first term on page */
120915  sqlite3_int64 iChild;           /* Block id of child node to descend to */
120916
120917  /* Skip over the 'height' varint that occurs at the start of every
120918  ** interior node. Then load the blockid of the left-child of the b-tree
120919  ** node into variable iChild.
120920  **
120921  ** Even if the data structure on disk is corrupted, this (reading two
120922  ** varints from the buffer) does not risk an overread. If zNode is a
120923  ** root node, then the buffer comes from a SELECT statement. SQLite does
120924  ** not make this guarantee explicitly, but in practice there are always
120925  ** either more than 20 bytes of allocated space following the nNode bytes of
120926  ** contents, or two zero bytes. Or, if the node is read from the %_segments
120927  ** table, then there are always 20 bytes of zeroed padding following the
120928  ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
120929  */
120930  zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
120931  zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
120932  if( zCsr>zEnd ){
120933    return FTS_CORRUPT_VTAB;
120934  }
120935
120936  while( zCsr<zEnd && (piFirst || piLast) ){
120937    int cmp;                      /* memcmp() result */
120938    int nSuffix;                  /* Size of term suffix */
120939    int nPrefix = 0;              /* Size of term prefix */
120940    int nBuffer;                  /* Total term size */
120941
120942    /* Load the next term on the node into zBuffer. Use realloc() to expand
120943    ** the size of zBuffer if required.  */
120944    if( !isFirstTerm ){
120945      zCsr += sqlite3Fts3GetVarint32(zCsr, &nPrefix);
120946    }
120947    isFirstTerm = 0;
120948    zCsr += sqlite3Fts3GetVarint32(zCsr, &nSuffix);
120949
120950    if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
120951      rc = FTS_CORRUPT_VTAB;
120952      goto finish_scan;
120953    }
120954    if( nPrefix+nSuffix>nAlloc ){
120955      char *zNew;
120956      nAlloc = (nPrefix+nSuffix) * 2;
120957      zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
120958      if( !zNew ){
120959        rc = SQLITE_NOMEM;
120960        goto finish_scan;
120961      }
120962      zBuffer = zNew;
120963    }
120964    assert( zBuffer );
120965    memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
120966    nBuffer = nPrefix + nSuffix;
120967    zCsr += nSuffix;
120968
120969    /* Compare the term we are searching for with the term just loaded from
120970    ** the interior node. If the specified term is greater than or equal
120971    ** to the term from the interior node, then all terms on the sub-tree
120972    ** headed by node iChild are smaller than zTerm. No need to search
120973    ** iChild.
120974    **
120975    ** If the interior node term is larger than the specified term, then
120976    ** the tree headed by iChild may contain the specified term.
120977    */
120978    cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
120979    if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
120980      *piFirst = iChild;
120981      piFirst = 0;
120982    }
120983
120984    if( piLast && cmp<0 ){
120985      *piLast = iChild;
120986      piLast = 0;
120987    }
120988
120989    iChild++;
120990  };
120991
120992  if( piFirst ) *piFirst = iChild;
120993  if( piLast ) *piLast = iChild;
120994
120995 finish_scan:
120996  sqlite3_free(zBuffer);
120997  return rc;
120998}
120999
121000
121001/*
121002** The buffer pointed to by argument zNode (size nNode bytes) contains an
121003** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
121004** contains a term. This function searches the sub-tree headed by the zNode
121005** node for the range of leaf nodes that may contain the specified term
121006** or terms for which the specified term is a prefix.
121007**
121008** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
121009** left-most leaf node in the tree that may contain the specified term.
121010** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
121011** right-most leaf node that may contain a term for which the specified
121012** term is a prefix.
121013**
121014** It is possible that the range of returned leaf nodes does not contain
121015** the specified term or any terms for which it is a prefix. However, if the
121016** segment does contain any such terms, they are stored within the identified
121017** range. Because this function only inspects interior segment nodes (and
121018** never loads leaf nodes into memory), it is not possible to be sure.
121019**
121020** If an error occurs, an error code other than SQLITE_OK is returned.
121021*/
121022static int fts3SelectLeaf(
121023  Fts3Table *p,                   /* Virtual table handle */
121024  const char *zTerm,              /* Term to select leaves for */
121025  int nTerm,                      /* Size of term zTerm in bytes */
121026  const char *zNode,              /* Buffer containing segment interior node */
121027  int nNode,                      /* Size of buffer at zNode */
121028  sqlite3_int64 *piLeaf,          /* Selected leaf node */
121029  sqlite3_int64 *piLeaf2          /* Selected leaf node */
121030){
121031  int rc;                         /* Return code */
121032  int iHeight;                    /* Height of this node in tree */
121033
121034  assert( piLeaf || piLeaf2 );
121035
121036  sqlite3Fts3GetVarint32(zNode, &iHeight);
121037  rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
121038  assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
121039
121040  if( rc==SQLITE_OK && iHeight>1 ){
121041    char *zBlob = 0;              /* Blob read from %_segments table */
121042    int nBlob;                    /* Size of zBlob in bytes */
121043
121044    if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
121045      rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
121046      if( rc==SQLITE_OK ){
121047        rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
121048      }
121049      sqlite3_free(zBlob);
121050      piLeaf = 0;
121051      zBlob = 0;
121052    }
121053
121054    if( rc==SQLITE_OK ){
121055      rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
121056    }
121057    if( rc==SQLITE_OK ){
121058      rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
121059    }
121060    sqlite3_free(zBlob);
121061  }
121062
121063  return rc;
121064}
121065
121066/*
121067** This function is used to create delta-encoded serialized lists of FTS3
121068** varints. Each call to this function appends a single varint to a list.
121069*/
121070static void fts3PutDeltaVarint(
121071  char **pp,                      /* IN/OUT: Output pointer */
121072  sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
121073  sqlite3_int64 iVal              /* Write this value to the list */
121074){
121075  assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
121076  *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
121077  *piPrev = iVal;
121078}
121079
121080/*
121081** When this function is called, *ppPoslist is assumed to point to the
121082** start of a position-list. After it returns, *ppPoslist points to the
121083** first byte after the position-list.
121084**
121085** A position list is list of positions (delta encoded) and columns for
121086** a single document record of a doclist.  So, in other words, this
121087** routine advances *ppPoslist so that it points to the next docid in
121088** the doclist, or to the first byte past the end of the doclist.
121089**
121090** If pp is not NULL, then the contents of the position list are copied
121091** to *pp. *pp is set to point to the first byte past the last byte copied
121092** before this function returns.
121093*/
121094static void fts3PoslistCopy(char **pp, char **ppPoslist){
121095  char *pEnd = *ppPoslist;
121096  char c = 0;
121097
121098  /* The end of a position list is marked by a zero encoded as an FTS3
121099  ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
121100  ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
121101  ** of some other, multi-byte, value.
121102  **
121103  ** The following while-loop moves pEnd to point to the first byte that is not
121104  ** immediately preceded by a byte with the 0x80 bit set. Then increments
121105  ** pEnd once more so that it points to the byte immediately following the
121106  ** last byte in the position-list.
121107  */
121108  while( *pEnd | c ){
121109    c = *pEnd++ & 0x80;
121110    testcase( c!=0 && (*pEnd)==0 );
121111  }
121112  pEnd++;  /* Advance past the POS_END terminator byte */
121113
121114  if( pp ){
121115    int n = (int)(pEnd - *ppPoslist);
121116    char *p = *pp;
121117    memcpy(p, *ppPoslist, n);
121118    p += n;
121119    *pp = p;
121120  }
121121  *ppPoslist = pEnd;
121122}
121123
121124/*
121125** When this function is called, *ppPoslist is assumed to point to the
121126** start of a column-list. After it returns, *ppPoslist points to the
121127** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
121128**
121129** A column-list is list of delta-encoded positions for a single column
121130** within a single document within a doclist.
121131**
121132** The column-list is terminated either by a POS_COLUMN varint (1) or
121133** a POS_END varint (0).  This routine leaves *ppPoslist pointing to
121134** the POS_COLUMN or POS_END that terminates the column-list.
121135**
121136** If pp is not NULL, then the contents of the column-list are copied
121137** to *pp. *pp is set to point to the first byte past the last byte copied
121138** before this function returns.  The POS_COLUMN or POS_END terminator
121139** is not copied into *pp.
121140*/
121141static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
121142  char *pEnd = *ppPoslist;
121143  char c = 0;
121144
121145  /* A column-list is terminated by either a 0x01 or 0x00 byte that is
121146  ** not part of a multi-byte varint.
121147  */
121148  while( 0xFE & (*pEnd | c) ){
121149    c = *pEnd++ & 0x80;
121150    testcase( c!=0 && ((*pEnd)&0xfe)==0 );
121151  }
121152  if( pp ){
121153    int n = (int)(pEnd - *ppPoslist);
121154    char *p = *pp;
121155    memcpy(p, *ppPoslist, n);
121156    p += n;
121157    *pp = p;
121158  }
121159  *ppPoslist = pEnd;
121160}
121161
121162/*
121163** Value used to signify the end of an position-list. This is safe because
121164** it is not possible to have a document with 2^31 terms.
121165*/
121166#define POSITION_LIST_END 0x7fffffff
121167
121168/*
121169** This function is used to help parse position-lists. When this function is
121170** called, *pp may point to the start of the next varint in the position-list
121171** being parsed, or it may point to 1 byte past the end of the position-list
121172** (in which case **pp will be a terminator bytes POS_END (0) or
121173** (1)).
121174**
121175** If *pp points past the end of the current position-list, set *pi to
121176** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
121177** increment the current value of *pi by the value read, and set *pp to
121178** point to the next value before returning.
121179**
121180** Before calling this routine *pi must be initialized to the value of
121181** the previous position, or zero if we are reading the first position
121182** in the position-list.  Because positions are delta-encoded, the value
121183** of the previous position is needed in order to compute the value of
121184** the next position.
121185*/
121186static void fts3ReadNextPos(
121187  char **pp,                    /* IN/OUT: Pointer into position-list buffer */
121188  sqlite3_int64 *pi             /* IN/OUT: Value read from position-list */
121189){
121190  if( (**pp)&0xFE ){
121191    fts3GetDeltaVarint(pp, pi);
121192    *pi -= 2;
121193  }else{
121194    *pi = POSITION_LIST_END;
121195  }
121196}
121197
121198/*
121199** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
121200** the value of iCol encoded as a varint to *pp.   This will start a new
121201** column list.
121202**
121203** Set *pp to point to the byte just after the last byte written before
121204** returning (do not modify it if iCol==0). Return the total number of bytes
121205** written (0 if iCol==0).
121206*/
121207static int fts3PutColNumber(char **pp, int iCol){
121208  int n = 0;                      /* Number of bytes written */
121209  if( iCol ){
121210    char *p = *pp;                /* Output pointer */
121211    n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
121212    *p = 0x01;
121213    *pp = &p[n];
121214  }
121215  return n;
121216}
121217
121218/*
121219** Compute the union of two position lists.  The output written
121220** into *pp contains all positions of both *pp1 and *pp2 in sorted
121221** order and with any duplicates removed.  All pointers are
121222** updated appropriately.   The caller is responsible for insuring
121223** that there is enough space in *pp to hold the complete output.
121224*/
121225static void fts3PoslistMerge(
121226  char **pp,                      /* Output buffer */
121227  char **pp1,                     /* Left input list */
121228  char **pp2                      /* Right input list */
121229){
121230  char *p = *pp;
121231  char *p1 = *pp1;
121232  char *p2 = *pp2;
121233
121234  while( *p1 || *p2 ){
121235    int iCol1;         /* The current column index in pp1 */
121236    int iCol2;         /* The current column index in pp2 */
121237
121238    if( *p1==POS_COLUMN ) sqlite3Fts3GetVarint32(&p1[1], &iCol1);
121239    else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
121240    else iCol1 = 0;
121241
121242    if( *p2==POS_COLUMN ) sqlite3Fts3GetVarint32(&p2[1], &iCol2);
121243    else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
121244    else iCol2 = 0;
121245
121246    if( iCol1==iCol2 ){
121247      sqlite3_int64 i1 = 0;       /* Last position from pp1 */
121248      sqlite3_int64 i2 = 0;       /* Last position from pp2 */
121249      sqlite3_int64 iPrev = 0;
121250      int n = fts3PutColNumber(&p, iCol1);
121251      p1 += n;
121252      p2 += n;
121253
121254      /* At this point, both p1 and p2 point to the start of column-lists
121255      ** for the same column (the column with index iCol1 and iCol2).
121256      ** A column-list is a list of non-negative delta-encoded varints, each
121257      ** incremented by 2 before being stored. Each list is terminated by a
121258      ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
121259      ** and writes the results to buffer p. p is left pointing to the byte
121260      ** after the list written. No terminator (POS_END or POS_COLUMN) is
121261      ** written to the output.
121262      */
121263      fts3GetDeltaVarint(&p1, &i1);
121264      fts3GetDeltaVarint(&p2, &i2);
121265      do {
121266        fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
121267        iPrev -= 2;
121268        if( i1==i2 ){
121269          fts3ReadNextPos(&p1, &i1);
121270          fts3ReadNextPos(&p2, &i2);
121271        }else if( i1<i2 ){
121272          fts3ReadNextPos(&p1, &i1);
121273        }else{
121274          fts3ReadNextPos(&p2, &i2);
121275        }
121276      }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
121277    }else if( iCol1<iCol2 ){
121278      p1 += fts3PutColNumber(&p, iCol1);
121279      fts3ColumnlistCopy(&p, &p1);
121280    }else{
121281      p2 += fts3PutColNumber(&p, iCol2);
121282      fts3ColumnlistCopy(&p, &p2);
121283    }
121284  }
121285
121286  *p++ = POS_END;
121287  *pp = p;
121288  *pp1 = p1 + 1;
121289  *pp2 = p2 + 1;
121290}
121291
121292/*
121293** This function is used to merge two position lists into one. When it is
121294** called, *pp1 and *pp2 must both point to position lists. A position-list is
121295** the part of a doclist that follows each document id. For example, if a row
121296** contains:
121297**
121298**     'a b c'|'x y z'|'a b b a'
121299**
121300** Then the position list for this row for token 'b' would consist of:
121301**
121302**     0x02 0x01 0x02 0x03 0x03 0x00
121303**
121304** When this function returns, both *pp1 and *pp2 are left pointing to the
121305** byte following the 0x00 terminator of their respective position lists.
121306**
121307** If isSaveLeft is 0, an entry is added to the output position list for
121308** each position in *pp2 for which there exists one or more positions in
121309** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
121310** when the *pp1 token appears before the *pp2 token, but not more than nToken
121311** slots before it.
121312**
121313** e.g. nToken==1 searches for adjacent positions.
121314*/
121315static int fts3PoslistPhraseMerge(
121316  char **pp,                      /* IN/OUT: Preallocated output buffer */
121317  int nToken,                     /* Maximum difference in token positions */
121318  int isSaveLeft,                 /* Save the left position */
121319  int isExact,                    /* If *pp1 is exactly nTokens before *pp2 */
121320  char **pp1,                     /* IN/OUT: Left input list */
121321  char **pp2                      /* IN/OUT: Right input list */
121322){
121323  char *p = *pp;
121324  char *p1 = *pp1;
121325  char *p2 = *pp2;
121326  int iCol1 = 0;
121327  int iCol2 = 0;
121328
121329  /* Never set both isSaveLeft and isExact for the same invocation. */
121330  assert( isSaveLeft==0 || isExact==0 );
121331
121332  assert( p!=0 && *p1!=0 && *p2!=0 );
121333  if( *p1==POS_COLUMN ){
121334    p1++;
121335    p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
121336  }
121337  if( *p2==POS_COLUMN ){
121338    p2++;
121339    p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
121340  }
121341
121342  while( 1 ){
121343    if( iCol1==iCol2 ){
121344      char *pSave = p;
121345      sqlite3_int64 iPrev = 0;
121346      sqlite3_int64 iPos1 = 0;
121347      sqlite3_int64 iPos2 = 0;
121348
121349      if( iCol1 ){
121350        *p++ = POS_COLUMN;
121351        p += sqlite3Fts3PutVarint(p, iCol1);
121352      }
121353
121354      assert( *p1!=POS_END && *p1!=POS_COLUMN );
121355      assert( *p2!=POS_END && *p2!=POS_COLUMN );
121356      fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
121357      fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
121358
121359      while( 1 ){
121360        if( iPos2==iPos1+nToken
121361         || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
121362        ){
121363          sqlite3_int64 iSave;
121364          iSave = isSaveLeft ? iPos1 : iPos2;
121365          fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
121366          pSave = 0;
121367          assert( p );
121368        }
121369        if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
121370          if( (*p2&0xFE)==0 ) break;
121371          fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
121372        }else{
121373          if( (*p1&0xFE)==0 ) break;
121374          fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
121375        }
121376      }
121377
121378      if( pSave ){
121379        assert( pp && p );
121380        p = pSave;
121381      }
121382
121383      fts3ColumnlistCopy(0, &p1);
121384      fts3ColumnlistCopy(0, &p2);
121385      assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
121386      if( 0==*p1 || 0==*p2 ) break;
121387
121388      p1++;
121389      p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
121390      p2++;
121391      p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
121392    }
121393
121394    /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
121395    ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
121396    ** end of the position list, or the 0x01 that precedes the next
121397    ** column-number in the position list.
121398    */
121399    else if( iCol1<iCol2 ){
121400      fts3ColumnlistCopy(0, &p1);
121401      if( 0==*p1 ) break;
121402      p1++;
121403      p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
121404    }else{
121405      fts3ColumnlistCopy(0, &p2);
121406      if( 0==*p2 ) break;
121407      p2++;
121408      p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
121409    }
121410  }
121411
121412  fts3PoslistCopy(0, &p2);
121413  fts3PoslistCopy(0, &p1);
121414  *pp1 = p1;
121415  *pp2 = p2;
121416  if( *pp==p ){
121417    return 0;
121418  }
121419  *p++ = 0x00;
121420  *pp = p;
121421  return 1;
121422}
121423
121424/*
121425** Merge two position-lists as required by the NEAR operator. The argument
121426** position lists correspond to the left and right phrases of an expression
121427** like:
121428**
121429**     "phrase 1" NEAR "phrase number 2"
121430**
121431** Position list *pp1 corresponds to the left-hand side of the NEAR
121432** expression and *pp2 to the right. As usual, the indexes in the position
121433** lists are the offsets of the last token in each phrase (tokens "1" and "2"
121434** in the example above).
121435**
121436** The output position list - written to *pp - is a copy of *pp2 with those
121437** entries that are not sufficiently NEAR entries in *pp1 removed.
121438*/
121439static int fts3PoslistNearMerge(
121440  char **pp,                      /* Output buffer */
121441  char *aTmp,                     /* Temporary buffer space */
121442  int nRight,                     /* Maximum difference in token positions */
121443  int nLeft,                      /* Maximum difference in token positions */
121444  char **pp1,                     /* IN/OUT: Left input list */
121445  char **pp2                      /* IN/OUT: Right input list */
121446){
121447  char *p1 = *pp1;
121448  char *p2 = *pp2;
121449
121450  char *pTmp1 = aTmp;
121451  char *pTmp2;
121452  char *aTmp2;
121453  int res = 1;
121454
121455  fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
121456  aTmp2 = pTmp2 = pTmp1;
121457  *pp1 = p1;
121458  *pp2 = p2;
121459  fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
121460  if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
121461    fts3PoslistMerge(pp, &aTmp, &aTmp2);
121462  }else if( pTmp1!=aTmp ){
121463    fts3PoslistCopy(pp, &aTmp);
121464  }else if( pTmp2!=aTmp2 ){
121465    fts3PoslistCopy(pp, &aTmp2);
121466  }else{
121467    res = 0;
121468  }
121469
121470  return res;
121471}
121472
121473/*
121474** An instance of this function is used to merge together the (potentially
121475** large number of) doclists for each term that matches a prefix query.
121476** See function fts3TermSelectMerge() for details.
121477*/
121478typedef struct TermSelect TermSelect;
121479struct TermSelect {
121480  char *aaOutput[16];             /* Malloc'd output buffers */
121481  int anOutput[16];               /* Size each output buffer in bytes */
121482};
121483
121484/*
121485** This function is used to read a single varint from a buffer. Parameter
121486** pEnd points 1 byte past the end of the buffer. When this function is
121487** called, if *pp points to pEnd or greater, then the end of the buffer
121488** has been reached. In this case *pp is set to 0 and the function returns.
121489**
121490** If *pp does not point to or past pEnd, then a single varint is read
121491** from *pp. *pp is then set to point 1 byte past the end of the read varint.
121492**
121493** If bDescIdx is false, the value read is added to *pVal before returning.
121494** If it is true, the value read is subtracted from *pVal before this
121495** function returns.
121496*/
121497static void fts3GetDeltaVarint3(
121498  char **pp,                      /* IN/OUT: Point to read varint from */
121499  char *pEnd,                     /* End of buffer */
121500  int bDescIdx,                   /* True if docids are descending */
121501  sqlite3_int64 *pVal             /* IN/OUT: Integer value */
121502){
121503  if( *pp>=pEnd ){
121504    *pp = 0;
121505  }else{
121506    sqlite3_int64 iVal;
121507    *pp += sqlite3Fts3GetVarint(*pp, &iVal);
121508    if( bDescIdx ){
121509      *pVal -= iVal;
121510    }else{
121511      *pVal += iVal;
121512    }
121513  }
121514}
121515
121516/*
121517** This function is used to write a single varint to a buffer. The varint
121518** is written to *pp. Before returning, *pp is set to point 1 byte past the
121519** end of the value written.
121520**
121521** If *pbFirst is zero when this function is called, the value written to
121522** the buffer is that of parameter iVal.
121523**
121524** If *pbFirst is non-zero when this function is called, then the value
121525** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
121526** (if bDescIdx is non-zero).
121527**
121528** Before returning, this function always sets *pbFirst to 1 and *piPrev
121529** to the value of parameter iVal.
121530*/
121531static void fts3PutDeltaVarint3(
121532  char **pp,                      /* IN/OUT: Output pointer */
121533  int bDescIdx,                   /* True for descending docids */
121534  sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
121535  int *pbFirst,                   /* IN/OUT: True after first int written */
121536  sqlite3_int64 iVal              /* Write this value to the list */
121537){
121538  sqlite3_int64 iWrite;
121539  if( bDescIdx==0 || *pbFirst==0 ){
121540    iWrite = iVal - *piPrev;
121541  }else{
121542    iWrite = *piPrev - iVal;
121543  }
121544  assert( *pbFirst || *piPrev==0 );
121545  assert( *pbFirst==0 || iWrite>0 );
121546  *pp += sqlite3Fts3PutVarint(*pp, iWrite);
121547  *piPrev = iVal;
121548  *pbFirst = 1;
121549}
121550
121551
121552/*
121553** This macro is used by various functions that merge doclists. The two
121554** arguments are 64-bit docid values. If the value of the stack variable
121555** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
121556** Otherwise, (i2-i1).
121557**
121558** Using this makes it easier to write code that can merge doclists that are
121559** sorted in either ascending or descending order.
121560*/
121561#define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
121562
121563/*
121564** This function does an "OR" merge of two doclists (output contains all
121565** positions contained in either argument doclist). If the docids in the
121566** input doclists are sorted in ascending order, parameter bDescDoclist
121567** should be false. If they are sorted in ascending order, it should be
121568** passed a non-zero value.
121569**
121570** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
121571** containing the output doclist and SQLITE_OK is returned. In this case
121572** *pnOut is set to the number of bytes in the output doclist.
121573**
121574** If an error occurs, an SQLite error code is returned. The output values
121575** are undefined in this case.
121576*/
121577static int fts3DoclistOrMerge(
121578  int bDescDoclist,               /* True if arguments are desc */
121579  char *a1, int n1,               /* First doclist */
121580  char *a2, int n2,               /* Second doclist */
121581  char **paOut, int *pnOut        /* OUT: Malloc'd doclist */
121582){
121583  sqlite3_int64 i1 = 0;
121584  sqlite3_int64 i2 = 0;
121585  sqlite3_int64 iPrev = 0;
121586  char *pEnd1 = &a1[n1];
121587  char *pEnd2 = &a2[n2];
121588  char *p1 = a1;
121589  char *p2 = a2;
121590  char *p;
121591  char *aOut;
121592  int bFirstOut = 0;
121593
121594  *paOut = 0;
121595  *pnOut = 0;
121596
121597  /* Allocate space for the output. Both the input and output doclists
121598  ** are delta encoded. If they are in ascending order (bDescDoclist==0),
121599  ** then the first docid in each list is simply encoded as a varint. For
121600  ** each subsequent docid, the varint stored is the difference between the
121601  ** current and previous docid (a positive number - since the list is in
121602  ** ascending order).
121603  **
121604  ** The first docid written to the output is therefore encoded using the
121605  ** same number of bytes as it is in whichever of the input lists it is
121606  ** read from. And each subsequent docid read from the same input list
121607  ** consumes either the same or less bytes as it did in the input (since
121608  ** the difference between it and the previous value in the output must
121609  ** be a positive value less than or equal to the delta value read from
121610  ** the input list). The same argument applies to all but the first docid
121611  ** read from the 'other' list. And to the contents of all position lists
121612  ** that will be copied and merged from the input to the output.
121613  **
121614  ** However, if the first docid copied to the output is a negative number,
121615  ** then the encoding of the first docid from the 'other' input list may
121616  ** be larger in the output than it was in the input (since the delta value
121617  ** may be a larger positive integer than the actual docid).
121618  **
121619  ** The space required to store the output is therefore the sum of the
121620  ** sizes of the two inputs, plus enough space for exactly one of the input
121621  ** docids to grow.
121622  **
121623  ** A symetric argument may be made if the doclists are in descending
121624  ** order.
121625  */
121626  aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
121627  if( !aOut ) return SQLITE_NOMEM;
121628
121629  p = aOut;
121630  fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
121631  fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
121632  while( p1 || p2 ){
121633    sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
121634
121635    if( p2 && p1 && iDiff==0 ){
121636      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
121637      fts3PoslistMerge(&p, &p1, &p2);
121638      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
121639      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
121640    }else if( !p2 || (p1 && iDiff<0) ){
121641      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
121642      fts3PoslistCopy(&p, &p1);
121643      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
121644    }else{
121645      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
121646      fts3PoslistCopy(&p, &p2);
121647      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
121648    }
121649  }
121650
121651  *paOut = aOut;
121652  *pnOut = (int)(p-aOut);
121653  assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
121654  return SQLITE_OK;
121655}
121656
121657/*
121658** This function does a "phrase" merge of two doclists. In a phrase merge,
121659** the output contains a copy of each position from the right-hand input
121660** doclist for which there is a position in the left-hand input doclist
121661** exactly nDist tokens before it.
121662**
121663** If the docids in the input doclists are sorted in ascending order,
121664** parameter bDescDoclist should be false. If they are sorted in ascending
121665** order, it should be passed a non-zero value.
121666**
121667** The right-hand input doclist is overwritten by this function.
121668*/
121669static void fts3DoclistPhraseMerge(
121670  int bDescDoclist,               /* True if arguments are desc */
121671  int nDist,                      /* Distance from left to right (1=adjacent) */
121672  char *aLeft, int nLeft,         /* Left doclist */
121673  char *aRight, int *pnRight      /* IN/OUT: Right/output doclist */
121674){
121675  sqlite3_int64 i1 = 0;
121676  sqlite3_int64 i2 = 0;
121677  sqlite3_int64 iPrev = 0;
121678  char *pEnd1 = &aLeft[nLeft];
121679  char *pEnd2 = &aRight[*pnRight];
121680  char *p1 = aLeft;
121681  char *p2 = aRight;
121682  char *p;
121683  int bFirstOut = 0;
121684  char *aOut = aRight;
121685
121686  assert( nDist>0 );
121687
121688  p = aOut;
121689  fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
121690  fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
121691
121692  while( p1 && p2 ){
121693    sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
121694    if( iDiff==0 ){
121695      char *pSave = p;
121696      sqlite3_int64 iPrevSave = iPrev;
121697      int bFirstOutSave = bFirstOut;
121698
121699      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
121700      if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
121701        p = pSave;
121702        iPrev = iPrevSave;
121703        bFirstOut = bFirstOutSave;
121704      }
121705      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
121706      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
121707    }else if( iDiff<0 ){
121708      fts3PoslistCopy(0, &p1);
121709      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
121710    }else{
121711      fts3PoslistCopy(0, &p2);
121712      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
121713    }
121714  }
121715
121716  *pnRight = (int)(p - aOut);
121717}
121718
121719/*
121720** Argument pList points to a position list nList bytes in size. This
121721** function checks to see if the position list contains any entries for
121722** a token in position 0 (of any column). If so, it writes argument iDelta
121723** to the output buffer pOut, followed by a position list consisting only
121724** of the entries from pList at position 0, and terminated by an 0x00 byte.
121725** The value returned is the number of bytes written to pOut (if any).
121726*/
121727SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
121728  sqlite3_int64 iDelta,           /* Varint that may be written to pOut */
121729  char *pList,                    /* Position list (no 0x00 term) */
121730  int nList,                      /* Size of pList in bytes */
121731  char *pOut                      /* Write output here */
121732){
121733  int nOut = 0;
121734  int bWritten = 0;               /* True once iDelta has been written */
121735  char *p = pList;
121736  char *pEnd = &pList[nList];
121737
121738  if( *p!=0x01 ){
121739    if( *p==0x02 ){
121740      nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
121741      pOut[nOut++] = 0x02;
121742      bWritten = 1;
121743    }
121744    fts3ColumnlistCopy(0, &p);
121745  }
121746
121747  while( p<pEnd && *p==0x01 ){
121748    sqlite3_int64 iCol;
121749    p++;
121750    p += sqlite3Fts3GetVarint(p, &iCol);
121751    if( *p==0x02 ){
121752      if( bWritten==0 ){
121753        nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
121754        bWritten = 1;
121755      }
121756      pOut[nOut++] = 0x01;
121757      nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
121758      pOut[nOut++] = 0x02;
121759    }
121760    fts3ColumnlistCopy(0, &p);
121761  }
121762  if( bWritten ){
121763    pOut[nOut++] = 0x00;
121764  }
121765
121766  return nOut;
121767}
121768
121769
121770/*
121771** Merge all doclists in the TermSelect.aaOutput[] array into a single
121772** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
121773** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
121774**
121775** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
121776** the responsibility of the caller to free any doclists left in the
121777** TermSelect.aaOutput[] array.
121778*/
121779static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
121780  char *aOut = 0;
121781  int nOut = 0;
121782  int i;
121783
121784  /* Loop through the doclists in the aaOutput[] array. Merge them all
121785  ** into a single doclist.
121786  */
121787  for(i=0; i<SizeofArray(pTS->aaOutput); i++){
121788    if( pTS->aaOutput[i] ){
121789      if( !aOut ){
121790        aOut = pTS->aaOutput[i];
121791        nOut = pTS->anOutput[i];
121792        pTS->aaOutput[i] = 0;
121793      }else{
121794        int nNew;
121795        char *aNew;
121796
121797        int rc = fts3DoclistOrMerge(p->bDescIdx,
121798            pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
121799        );
121800        if( rc!=SQLITE_OK ){
121801          sqlite3_free(aOut);
121802          return rc;
121803        }
121804
121805        sqlite3_free(pTS->aaOutput[i]);
121806        sqlite3_free(aOut);
121807        pTS->aaOutput[i] = 0;
121808        aOut = aNew;
121809        nOut = nNew;
121810      }
121811    }
121812  }
121813
121814  pTS->aaOutput[0] = aOut;
121815  pTS->anOutput[0] = nOut;
121816  return SQLITE_OK;
121817}
121818
121819/*
121820** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
121821** as the first argument. The merge is an "OR" merge (see function
121822** fts3DoclistOrMerge() for details).
121823**
121824** This function is called with the doclist for each term that matches
121825** a queried prefix. It merges all these doclists into one, the doclist
121826** for the specified prefix. Since there can be a very large number of
121827** doclists to merge, the merging is done pair-wise using the TermSelect
121828** object.
121829**
121830** This function returns SQLITE_OK if the merge is successful, or an
121831** SQLite error code (SQLITE_NOMEM) if an error occurs.
121832*/
121833static int fts3TermSelectMerge(
121834  Fts3Table *p,                   /* FTS table handle */
121835  TermSelect *pTS,                /* TermSelect object to merge into */
121836  char *aDoclist,                 /* Pointer to doclist */
121837  int nDoclist                    /* Size of aDoclist in bytes */
121838){
121839  if( pTS->aaOutput[0]==0 ){
121840    /* If this is the first term selected, copy the doclist to the output
121841    ** buffer using memcpy(). */
121842    pTS->aaOutput[0] = sqlite3_malloc(nDoclist);
121843    pTS->anOutput[0] = nDoclist;
121844    if( pTS->aaOutput[0] ){
121845      memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
121846    }else{
121847      return SQLITE_NOMEM;
121848    }
121849  }else{
121850    char *aMerge = aDoclist;
121851    int nMerge = nDoclist;
121852    int iOut;
121853
121854    for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
121855      if( pTS->aaOutput[iOut]==0 ){
121856        assert( iOut>0 );
121857        pTS->aaOutput[iOut] = aMerge;
121858        pTS->anOutput[iOut] = nMerge;
121859        break;
121860      }else{
121861        char *aNew;
121862        int nNew;
121863
121864        int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
121865            pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
121866        );
121867        if( rc!=SQLITE_OK ){
121868          if( aMerge!=aDoclist ) sqlite3_free(aMerge);
121869          return rc;
121870        }
121871
121872        if( aMerge!=aDoclist ) sqlite3_free(aMerge);
121873        sqlite3_free(pTS->aaOutput[iOut]);
121874        pTS->aaOutput[iOut] = 0;
121875
121876        aMerge = aNew;
121877        nMerge = nNew;
121878        if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
121879          pTS->aaOutput[iOut] = aMerge;
121880          pTS->anOutput[iOut] = nMerge;
121881        }
121882      }
121883    }
121884  }
121885  return SQLITE_OK;
121886}
121887
121888/*
121889** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
121890*/
121891static int fts3SegReaderCursorAppend(
121892  Fts3MultiSegReader *pCsr,
121893  Fts3SegReader *pNew
121894){
121895  if( (pCsr->nSegment%16)==0 ){
121896    Fts3SegReader **apNew;
121897    int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
121898    apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
121899    if( !apNew ){
121900      sqlite3Fts3SegReaderFree(pNew);
121901      return SQLITE_NOMEM;
121902    }
121903    pCsr->apSegment = apNew;
121904  }
121905  pCsr->apSegment[pCsr->nSegment++] = pNew;
121906  return SQLITE_OK;
121907}
121908
121909/*
121910** Add seg-reader objects to the Fts3MultiSegReader object passed as the
121911** 8th argument.
121912**
121913** This function returns SQLITE_OK if successful, or an SQLite error code
121914** otherwise.
121915*/
121916static int fts3SegReaderCursor(
121917  Fts3Table *p,                   /* FTS3 table handle */
121918  int iLangid,                    /* Language id */
121919  int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
121920  int iLevel,                     /* Level of segments to scan */
121921  const char *zTerm,              /* Term to query for */
121922  int nTerm,                      /* Size of zTerm in bytes */
121923  int isPrefix,                   /* True for a prefix search */
121924  int isScan,                     /* True to scan from zTerm to EOF */
121925  Fts3MultiSegReader *pCsr        /* Cursor object to populate */
121926){
121927  int rc = SQLITE_OK;             /* Error code */
121928  sqlite3_stmt *pStmt = 0;        /* Statement to iterate through segments */
121929  int rc2;                        /* Result of sqlite3_reset() */
121930
121931  /* If iLevel is less than 0 and this is not a scan, include a seg-reader
121932  ** for the pending-terms. If this is a scan, then this call must be being
121933  ** made by an fts4aux module, not an FTS table. In this case calling
121934  ** Fts3SegReaderPending might segfault, as the data structures used by
121935  ** fts4aux are not completely populated. So it's easiest to filter these
121936  ** calls out here.  */
121937  if( iLevel<0 && p->aIndex ){
121938    Fts3SegReader *pSeg = 0;
121939    rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix, &pSeg);
121940    if( rc==SQLITE_OK && pSeg ){
121941      rc = fts3SegReaderCursorAppend(pCsr, pSeg);
121942    }
121943  }
121944
121945  if( iLevel!=FTS3_SEGCURSOR_PENDING ){
121946    if( rc==SQLITE_OK ){
121947      rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
121948    }
121949
121950    while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
121951      Fts3SegReader *pSeg = 0;
121952
121953      /* Read the values returned by the SELECT into local variables. */
121954      sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
121955      sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
121956      sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
121957      int nRoot = sqlite3_column_bytes(pStmt, 4);
121958      char const *zRoot = sqlite3_column_blob(pStmt, 4);
121959
121960      /* If zTerm is not NULL, and this segment is not stored entirely on its
121961      ** root node, the range of leaves scanned can be reduced. Do this. */
121962      if( iStartBlock && zTerm ){
121963        sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
121964        rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
121965        if( rc!=SQLITE_OK ) goto finished;
121966        if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
121967      }
121968
121969      rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
121970          (isPrefix==0 && isScan==0),
121971          iStartBlock, iLeavesEndBlock,
121972          iEndBlock, zRoot, nRoot, &pSeg
121973      );
121974      if( rc!=SQLITE_OK ) goto finished;
121975      rc = fts3SegReaderCursorAppend(pCsr, pSeg);
121976    }
121977  }
121978
121979 finished:
121980  rc2 = sqlite3_reset(pStmt);
121981  if( rc==SQLITE_DONE ) rc = rc2;
121982
121983  return rc;
121984}
121985
121986/*
121987** Set up a cursor object for iterating through a full-text index or a
121988** single level therein.
121989*/
121990SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
121991  Fts3Table *p,                   /* FTS3 table handle */
121992  int iLangid,                    /* Language-id to search */
121993  int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
121994  int iLevel,                     /* Level of segments to scan */
121995  const char *zTerm,              /* Term to query for */
121996  int nTerm,                      /* Size of zTerm in bytes */
121997  int isPrefix,                   /* True for a prefix search */
121998  int isScan,                     /* True to scan from zTerm to EOF */
121999  Fts3MultiSegReader *pCsr       /* Cursor object to populate */
122000){
122001  assert( iIndex>=0 && iIndex<p->nIndex );
122002  assert( iLevel==FTS3_SEGCURSOR_ALL
122003      ||  iLevel==FTS3_SEGCURSOR_PENDING
122004      ||  iLevel>=0
122005  );
122006  assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
122007  assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
122008  assert( isPrefix==0 || isScan==0 );
122009
122010  memset(pCsr, 0, sizeof(Fts3MultiSegReader));
122011  return fts3SegReaderCursor(
122012      p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
122013  );
122014}
122015
122016/*
122017** In addition to its current configuration, have the Fts3MultiSegReader
122018** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
122019**
122020** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
122021*/
122022static int fts3SegReaderCursorAddZero(
122023  Fts3Table *p,                   /* FTS virtual table handle */
122024  int iLangid,
122025  const char *zTerm,              /* Term to scan doclist of */
122026  int nTerm,                      /* Number of bytes in zTerm */
122027  Fts3MultiSegReader *pCsr        /* Fts3MultiSegReader to modify */
122028){
122029  return fts3SegReaderCursor(p,
122030      iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
122031  );
122032}
122033
122034/*
122035** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
122036** if isPrefix is true, to scan the doclist for all terms for which
122037** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
122038** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
122039** an SQLite error code.
122040**
122041** It is the responsibility of the caller to free this object by eventually
122042** passing it to fts3SegReaderCursorFree()
122043**
122044** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
122045** Output parameter *ppSegcsr is set to 0 if an error occurs.
122046*/
122047static int fts3TermSegReaderCursor(
122048  Fts3Cursor *pCsr,               /* Virtual table cursor handle */
122049  const char *zTerm,              /* Term to query for */
122050  int nTerm,                      /* Size of zTerm in bytes */
122051  int isPrefix,                   /* True for a prefix search */
122052  Fts3MultiSegReader **ppSegcsr   /* OUT: Allocated seg-reader cursor */
122053){
122054  Fts3MultiSegReader *pSegcsr;    /* Object to allocate and return */
122055  int rc = SQLITE_NOMEM;          /* Return code */
122056
122057  pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
122058  if( pSegcsr ){
122059    int i;
122060    int bFound = 0;               /* True once an index has been found */
122061    Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
122062
122063    if( isPrefix ){
122064      for(i=1; bFound==0 && i<p->nIndex; i++){
122065        if( p->aIndex[i].nPrefix==nTerm ){
122066          bFound = 1;
122067          rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
122068              i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
122069          );
122070          pSegcsr->bLookup = 1;
122071        }
122072      }
122073
122074      for(i=1; bFound==0 && i<p->nIndex; i++){
122075        if( p->aIndex[i].nPrefix==nTerm+1 ){
122076          bFound = 1;
122077          rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
122078              i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
122079          );
122080          if( rc==SQLITE_OK ){
122081            rc = fts3SegReaderCursorAddZero(
122082                p, pCsr->iLangid, zTerm, nTerm, pSegcsr
122083            );
122084          }
122085        }
122086      }
122087    }
122088
122089    if( bFound==0 ){
122090      rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
122091          0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
122092      );
122093      pSegcsr->bLookup = !isPrefix;
122094    }
122095  }
122096
122097  *ppSegcsr = pSegcsr;
122098  return rc;
122099}
122100
122101/*
122102** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
122103*/
122104static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
122105  sqlite3Fts3SegReaderFinish(pSegcsr);
122106  sqlite3_free(pSegcsr);
122107}
122108
122109/*
122110** This function retrieves the doclist for the specified term (or term
122111** prefix) from the database.
122112*/
122113static int fts3TermSelect(
122114  Fts3Table *p,                   /* Virtual table handle */
122115  Fts3PhraseToken *pTok,          /* Token to query for */
122116  int iColumn,                    /* Column to query (or -ve for all columns) */
122117  int *pnOut,                     /* OUT: Size of buffer at *ppOut */
122118  char **ppOut                    /* OUT: Malloced result buffer */
122119){
122120  int rc;                         /* Return code */
122121  Fts3MultiSegReader *pSegcsr;    /* Seg-reader cursor for this term */
122122  TermSelect tsc;                 /* Object for pair-wise doclist merging */
122123  Fts3SegFilter filter;           /* Segment term filter configuration */
122124
122125  pSegcsr = pTok->pSegcsr;
122126  memset(&tsc, 0, sizeof(TermSelect));
122127
122128  filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
122129        | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
122130        | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
122131        | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
122132  filter.iCol = iColumn;
122133  filter.zTerm = pTok->z;
122134  filter.nTerm = pTok->n;
122135
122136  rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
122137  while( SQLITE_OK==rc
122138      && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
122139  ){
122140    rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
122141  }
122142
122143  if( rc==SQLITE_OK ){
122144    rc = fts3TermSelectFinishMerge(p, &tsc);
122145  }
122146  if( rc==SQLITE_OK ){
122147    *ppOut = tsc.aaOutput[0];
122148    *pnOut = tsc.anOutput[0];
122149  }else{
122150    int i;
122151    for(i=0; i<SizeofArray(tsc.aaOutput); i++){
122152      sqlite3_free(tsc.aaOutput[i]);
122153    }
122154  }
122155
122156  fts3SegReaderCursorFree(pSegcsr);
122157  pTok->pSegcsr = 0;
122158  return rc;
122159}
122160
122161/*
122162** This function counts the total number of docids in the doclist stored
122163** in buffer aList[], size nList bytes.
122164**
122165** If the isPoslist argument is true, then it is assumed that the doclist
122166** contains a position-list following each docid. Otherwise, it is assumed
122167** that the doclist is simply a list of docids stored as delta encoded
122168** varints.
122169*/
122170static int fts3DoclistCountDocids(char *aList, int nList){
122171  int nDoc = 0;                   /* Return value */
122172  if( aList ){
122173    char *aEnd = &aList[nList];   /* Pointer to one byte after EOF */
122174    char *p = aList;              /* Cursor */
122175    while( p<aEnd ){
122176      nDoc++;
122177      while( (*p++)&0x80 );     /* Skip docid varint */
122178      fts3PoslistCopy(0, &p);   /* Skip over position list */
122179    }
122180  }
122181
122182  return nDoc;
122183}
122184
122185/*
122186** Advance the cursor to the next row in the %_content table that
122187** matches the search criteria.  For a MATCH search, this will be
122188** the next row that matches. For a full-table scan, this will be
122189** simply the next row in the %_content table.  For a docid lookup,
122190** this routine simply sets the EOF flag.
122191**
122192** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
122193** even if we reach end-of-file.  The fts3EofMethod() will be called
122194** subsequently to determine whether or not an EOF was hit.
122195*/
122196static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
122197  int rc;
122198  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
122199  if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
122200    if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
122201      pCsr->isEof = 1;
122202      rc = sqlite3_reset(pCsr->pStmt);
122203    }else{
122204      pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
122205      rc = SQLITE_OK;
122206    }
122207  }else{
122208    rc = fts3EvalNext((Fts3Cursor *)pCursor);
122209  }
122210  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
122211  return rc;
122212}
122213
122214/*
122215** This is the xFilter interface for the virtual table.  See
122216** the virtual table xFilter method documentation for additional
122217** information.
122218**
122219** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
122220** the %_content table.
122221**
122222** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
122223** in the %_content table.
122224**
122225** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The
122226** column on the left-hand side of the MATCH operator is column
122227** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand
122228** side of the MATCH operator.
122229*/
122230static int fts3FilterMethod(
122231  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
122232  int idxNum,                     /* Strategy index */
122233  const char *idxStr,             /* Unused */
122234  int nVal,                       /* Number of elements in apVal */
122235  sqlite3_value **apVal           /* Arguments for the indexing scheme */
122236){
122237  int rc;
122238  char *zSql;                     /* SQL statement used to access %_content */
122239  Fts3Table *p = (Fts3Table *)pCursor->pVtab;
122240  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
122241
122242  UNUSED_PARAMETER(idxStr);
122243  UNUSED_PARAMETER(nVal);
122244
122245  assert( idxNum>=0 && idxNum<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
122246  assert( nVal==0 || nVal==1 || nVal==2 );
122247  assert( (nVal==0)==(idxNum==FTS3_FULLSCAN_SEARCH) );
122248  assert( p->pSegments==0 );
122249
122250  /* In case the cursor has been used before, clear it now. */
122251  sqlite3_finalize(pCsr->pStmt);
122252  sqlite3_free(pCsr->aDoclist);
122253  sqlite3Fts3ExprFree(pCsr->pExpr);
122254  memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
122255
122256  if( idxStr ){
122257    pCsr->bDesc = (idxStr[0]=='D');
122258  }else{
122259    pCsr->bDesc = p->bDescIdx;
122260  }
122261  pCsr->eSearch = (i16)idxNum;
122262
122263  if( idxNum!=FTS3_DOCID_SEARCH && idxNum!=FTS3_FULLSCAN_SEARCH ){
122264    int iCol = idxNum-FTS3_FULLTEXT_SEARCH;
122265    const char *zQuery = (const char *)sqlite3_value_text(apVal[0]);
122266
122267    if( zQuery==0 && sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
122268      return SQLITE_NOMEM;
122269    }
122270
122271    pCsr->iLangid = 0;
122272    if( nVal==2 ) pCsr->iLangid = sqlite3_value_int(apVal[1]);
122273
122274    assert( p->base.zErrMsg==0 );
122275    rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
122276        p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr,
122277        &p->base.zErrMsg
122278    );
122279    if( rc!=SQLITE_OK ){
122280      return rc;
122281    }
122282
122283    rc = sqlite3Fts3ReadLock(p);
122284    if( rc!=SQLITE_OK ) return rc;
122285
122286    rc = fts3EvalStart(pCsr);
122287
122288    sqlite3Fts3SegmentsClose(p);
122289    if( rc!=SQLITE_OK ) return rc;
122290    pCsr->pNextId = pCsr->aDoclist;
122291    pCsr->iPrevId = 0;
122292  }
122293
122294  /* Compile a SELECT statement for this cursor. For a full-table-scan, the
122295  ** statement loops through all rows of the %_content table. For a
122296  ** full-text query or docid lookup, the statement retrieves a single
122297  ** row by docid.
122298  */
122299  if( idxNum==FTS3_FULLSCAN_SEARCH ){
122300    zSql = sqlite3_mprintf(
122301        "SELECT %s ORDER BY rowid %s",
122302        p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
122303    );
122304    if( zSql ){
122305      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
122306      sqlite3_free(zSql);
122307    }else{
122308      rc = SQLITE_NOMEM;
122309    }
122310  }else if( idxNum==FTS3_DOCID_SEARCH ){
122311    rc = fts3CursorSeekStmt(pCsr, &pCsr->pStmt);
122312    if( rc==SQLITE_OK ){
122313      rc = sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
122314    }
122315  }
122316  if( rc!=SQLITE_OK ) return rc;
122317
122318  return fts3NextMethod(pCursor);
122319}
122320
122321/*
122322** This is the xEof method of the virtual table. SQLite calls this
122323** routine to find out if it has reached the end of a result set.
122324*/
122325static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
122326  return ((Fts3Cursor *)pCursor)->isEof;
122327}
122328
122329/*
122330** This is the xRowid method. The SQLite core calls this routine to
122331** retrieve the rowid for the current row of the result set. fts3
122332** exposes %_content.docid as the rowid for the virtual table. The
122333** rowid should be written to *pRowid.
122334*/
122335static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
122336  Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
122337  *pRowid = pCsr->iPrevId;
122338  return SQLITE_OK;
122339}
122340
122341/*
122342** This is the xColumn method, called by SQLite to request a value from
122343** the row that the supplied cursor currently points to.
122344**
122345** If:
122346**
122347**   (iCol <  p->nColumn)   -> The value of the iCol'th user column.
122348**   (iCol == p->nColumn)   -> Magic column with the same name as the table.
122349**   (iCol == p->nColumn+1) -> Docid column
122350**   (iCol == p->nColumn+2) -> Langid column
122351*/
122352static int fts3ColumnMethod(
122353  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
122354  sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
122355  int iCol                        /* Index of column to read value from */
122356){
122357  int rc = SQLITE_OK;             /* Return Code */
122358  Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
122359  Fts3Table *p = (Fts3Table *)pCursor->pVtab;
122360
122361  /* The column value supplied by SQLite must be in range. */
122362  assert( iCol>=0 && iCol<=p->nColumn+2 );
122363
122364  if( iCol==p->nColumn+1 ){
122365    /* This call is a request for the "docid" column. Since "docid" is an
122366    ** alias for "rowid", use the xRowid() method to obtain the value.
122367    */
122368    sqlite3_result_int64(pCtx, pCsr->iPrevId);
122369  }else if( iCol==p->nColumn ){
122370    /* The extra column whose name is the same as the table.
122371    ** Return a blob which is a pointer to the cursor.  */
122372    sqlite3_result_blob(pCtx, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
122373  }else if( iCol==p->nColumn+2 && pCsr->pExpr ){
122374    sqlite3_result_int64(pCtx, pCsr->iLangid);
122375  }else{
122376    /* The requested column is either a user column (one that contains
122377    ** indexed data), or the language-id column.  */
122378    rc = fts3CursorSeek(0, pCsr);
122379
122380    if( rc==SQLITE_OK ){
122381      if( iCol==p->nColumn+2 ){
122382        int iLangid = 0;
122383        if( p->zLanguageid ){
122384          iLangid = sqlite3_column_int(pCsr->pStmt, p->nColumn+1);
122385        }
122386        sqlite3_result_int(pCtx, iLangid);
122387      }else if( sqlite3_data_count(pCsr->pStmt)>(iCol+1) ){
122388        sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
122389      }
122390    }
122391  }
122392
122393  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
122394  return rc;
122395}
122396
122397/*
122398** This function is the implementation of the xUpdate callback used by
122399** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
122400** inserted, updated or deleted.
122401*/
122402static int fts3UpdateMethod(
122403  sqlite3_vtab *pVtab,            /* Virtual table handle */
122404  int nArg,                       /* Size of argument array */
122405  sqlite3_value **apVal,          /* Array of arguments */
122406  sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
122407){
122408  return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
122409}
122410
122411/*
122412** Implementation of xSync() method. Flush the contents of the pending-terms
122413** hash-table to the database.
122414*/
122415static int fts3SyncMethod(sqlite3_vtab *pVtab){
122416
122417  /* Following an incremental-merge operation, assuming that the input
122418  ** segments are not completely consumed (the usual case), they are updated
122419  ** in place to remove the entries that have already been merged. This
122420  ** involves updating the leaf block that contains the smallest unmerged
122421  ** entry and each block (if any) between the leaf and the root node. So
122422  ** if the height of the input segment b-trees is N, and input segments
122423  ** are merged eight at a time, updating the input segments at the end
122424  ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
122425  ** small - often between 0 and 2. So the overhead of the incremental
122426  ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
122427  ** dwarfing the actual productive work accomplished, the incremental merge
122428  ** is only attempted if it will write at least 64 leaf blocks. Hence
122429  ** nMinMerge.
122430  **
122431  ** Of course, updating the input segments also involves deleting a bunch
122432  ** of blocks from the segments table. But this is not considered overhead
122433  ** as it would also be required by a crisis-merge that used the same input
122434  ** segments.
122435  */
122436  const u32 nMinMerge = 64;       /* Minimum amount of incr-merge work to do */
122437
122438  Fts3Table *p = (Fts3Table*)pVtab;
122439  int rc = sqlite3Fts3PendingTermsFlush(p);
122440
122441  if( rc==SQLITE_OK && p->bAutoincrmerge==1 && p->nLeafAdd>(nMinMerge/16) ){
122442    int mxLevel = 0;              /* Maximum relative level value in db */
122443    int A;                        /* Incr-merge parameter A */
122444
122445    rc = sqlite3Fts3MaxLevel(p, &mxLevel);
122446    assert( rc==SQLITE_OK || mxLevel==0 );
122447    A = p->nLeafAdd * mxLevel;
122448    A += (A/2);
122449    if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, 8);
122450  }
122451  sqlite3Fts3SegmentsClose(p);
122452  return rc;
122453}
122454
122455/*
122456** Implementation of xBegin() method. This is a no-op.
122457*/
122458static int fts3BeginMethod(sqlite3_vtab *pVtab){
122459  Fts3Table *p = (Fts3Table*)pVtab;
122460  UNUSED_PARAMETER(pVtab);
122461  assert( p->pSegments==0 );
122462  assert( p->nPendingData==0 );
122463  assert( p->inTransaction!=1 );
122464  TESTONLY( p->inTransaction = 1 );
122465  TESTONLY( p->mxSavepoint = -1; );
122466  p->nLeafAdd = 0;
122467  return SQLITE_OK;
122468}
122469
122470/*
122471** Implementation of xCommit() method. This is a no-op. The contents of
122472** the pending-terms hash-table have already been flushed into the database
122473** by fts3SyncMethod().
122474*/
122475static int fts3CommitMethod(sqlite3_vtab *pVtab){
122476  TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
122477  UNUSED_PARAMETER(pVtab);
122478  assert( p->nPendingData==0 );
122479  assert( p->inTransaction!=0 );
122480  assert( p->pSegments==0 );
122481  TESTONLY( p->inTransaction = 0 );
122482  TESTONLY( p->mxSavepoint = -1; );
122483  return SQLITE_OK;
122484}
122485
122486/*
122487** Implementation of xRollback(). Discard the contents of the pending-terms
122488** hash-table. Any changes made to the database are reverted by SQLite.
122489*/
122490static int fts3RollbackMethod(sqlite3_vtab *pVtab){
122491  Fts3Table *p = (Fts3Table*)pVtab;
122492  sqlite3Fts3PendingTermsClear(p);
122493  assert( p->inTransaction!=0 );
122494  TESTONLY( p->inTransaction = 0 );
122495  TESTONLY( p->mxSavepoint = -1; );
122496  return SQLITE_OK;
122497}
122498
122499/*
122500** When called, *ppPoslist must point to the byte immediately following the
122501** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
122502** moves *ppPoslist so that it instead points to the first byte of the
122503** same position list.
122504*/
122505static void fts3ReversePoslist(char *pStart, char **ppPoslist){
122506  char *p = &(*ppPoslist)[-2];
122507  char c = 0;
122508
122509  while( p>pStart && (c=*p--)==0 );
122510  while( p>pStart && (*p & 0x80) | c ){
122511    c = *p--;
122512  }
122513  if( p>pStart ){ p = &p[2]; }
122514  while( *p++&0x80 );
122515  *ppPoslist = p;
122516}
122517
122518/*
122519** Helper function used by the implementation of the overloaded snippet(),
122520** offsets() and optimize() SQL functions.
122521**
122522** If the value passed as the third argument is a blob of size
122523** sizeof(Fts3Cursor*), then the blob contents are copied to the
122524** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
122525** message is written to context pContext and SQLITE_ERROR returned. The
122526** string passed via zFunc is used as part of the error message.
122527*/
122528static int fts3FunctionArg(
122529  sqlite3_context *pContext,      /* SQL function call context */
122530  const char *zFunc,              /* Function name */
122531  sqlite3_value *pVal,            /* argv[0] passed to function */
122532  Fts3Cursor **ppCsr              /* OUT: Store cursor handle here */
122533){
122534  Fts3Cursor *pRet;
122535  if( sqlite3_value_type(pVal)!=SQLITE_BLOB
122536   || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
122537  ){
122538    char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
122539    sqlite3_result_error(pContext, zErr, -1);
122540    sqlite3_free(zErr);
122541    return SQLITE_ERROR;
122542  }
122543  memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
122544  *ppCsr = pRet;
122545  return SQLITE_OK;
122546}
122547
122548/*
122549** Implementation of the snippet() function for FTS3
122550*/
122551static void fts3SnippetFunc(
122552  sqlite3_context *pContext,      /* SQLite function call context */
122553  int nVal,                       /* Size of apVal[] array */
122554  sqlite3_value **apVal           /* Array of arguments */
122555){
122556  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
122557  const char *zStart = "<b>";
122558  const char *zEnd = "</b>";
122559  const char *zEllipsis = "<b>...</b>";
122560  int iCol = -1;
122561  int nToken = 15;                /* Default number of tokens in snippet */
122562
122563  /* There must be at least one argument passed to this function (otherwise
122564  ** the non-overloaded version would have been called instead of this one).
122565  */
122566  assert( nVal>=1 );
122567
122568  if( nVal>6 ){
122569    sqlite3_result_error(pContext,
122570        "wrong number of arguments to function snippet()", -1);
122571    return;
122572  }
122573  if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
122574
122575  switch( nVal ){
122576    case 6: nToken = sqlite3_value_int(apVal[5]);
122577    case 5: iCol = sqlite3_value_int(apVal[4]);
122578    case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
122579    case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
122580    case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
122581  }
122582  if( !zEllipsis || !zEnd || !zStart ){
122583    sqlite3_result_error_nomem(pContext);
122584  }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
122585    sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
122586  }
122587}
122588
122589/*
122590** Implementation of the offsets() function for FTS3
122591*/
122592static void fts3OffsetsFunc(
122593  sqlite3_context *pContext,      /* SQLite function call context */
122594  int nVal,                       /* Size of argument array */
122595  sqlite3_value **apVal           /* Array of arguments */
122596){
122597  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
122598
122599  UNUSED_PARAMETER(nVal);
122600
122601  assert( nVal==1 );
122602  if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
122603  assert( pCsr );
122604  if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
122605    sqlite3Fts3Offsets(pContext, pCsr);
122606  }
122607}
122608
122609/*
122610** Implementation of the special optimize() function for FTS3. This
122611** function merges all segments in the database to a single segment.
122612** Example usage is:
122613**
122614**   SELECT optimize(t) FROM t LIMIT 1;
122615**
122616** where 't' is the name of an FTS3 table.
122617*/
122618static void fts3OptimizeFunc(
122619  sqlite3_context *pContext,      /* SQLite function call context */
122620  int nVal,                       /* Size of argument array */
122621  sqlite3_value **apVal           /* Array of arguments */
122622){
122623  int rc;                         /* Return code */
122624  Fts3Table *p;                   /* Virtual table handle */
122625  Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */
122626
122627  UNUSED_PARAMETER(nVal);
122628
122629  assert( nVal==1 );
122630  if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
122631  p = (Fts3Table *)pCursor->base.pVtab;
122632  assert( p );
122633
122634  rc = sqlite3Fts3Optimize(p);
122635
122636  switch( rc ){
122637    case SQLITE_OK:
122638      sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
122639      break;
122640    case SQLITE_DONE:
122641      sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
122642      break;
122643    default:
122644      sqlite3_result_error_code(pContext, rc);
122645      break;
122646  }
122647}
122648
122649/*
122650** Implementation of the matchinfo() function for FTS3
122651*/
122652static void fts3MatchinfoFunc(
122653  sqlite3_context *pContext,      /* SQLite function call context */
122654  int nVal,                       /* Size of argument array */
122655  sqlite3_value **apVal           /* Array of arguments */
122656){
122657  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
122658  assert( nVal==1 || nVal==2 );
122659  if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
122660    const char *zArg = 0;
122661    if( nVal>1 ){
122662      zArg = (const char *)sqlite3_value_text(apVal[1]);
122663    }
122664    sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
122665  }
122666}
122667
122668/*
122669** This routine implements the xFindFunction method for the FTS3
122670** virtual table.
122671*/
122672static int fts3FindFunctionMethod(
122673  sqlite3_vtab *pVtab,            /* Virtual table handle */
122674  int nArg,                       /* Number of SQL function arguments */
122675  const char *zName,              /* Name of SQL function */
122676  void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
122677  void **ppArg                    /* Unused */
122678){
122679  struct Overloaded {
122680    const char *zName;
122681    void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
122682  } aOverload[] = {
122683    { "snippet", fts3SnippetFunc },
122684    { "offsets", fts3OffsetsFunc },
122685    { "optimize", fts3OptimizeFunc },
122686    { "matchinfo", fts3MatchinfoFunc },
122687  };
122688  int i;                          /* Iterator variable */
122689
122690  UNUSED_PARAMETER(pVtab);
122691  UNUSED_PARAMETER(nArg);
122692  UNUSED_PARAMETER(ppArg);
122693
122694  for(i=0; i<SizeofArray(aOverload); i++){
122695    if( strcmp(zName, aOverload[i].zName)==0 ){
122696      *pxFunc = aOverload[i].xFunc;
122697      return 1;
122698    }
122699  }
122700
122701  /* No function of the specified name was found. Return 0. */
122702  return 0;
122703}
122704
122705/*
122706** Implementation of FTS3 xRename method. Rename an fts3 table.
122707*/
122708static int fts3RenameMethod(
122709  sqlite3_vtab *pVtab,            /* Virtual table handle */
122710  const char *zName               /* New name of table */
122711){
122712  Fts3Table *p = (Fts3Table *)pVtab;
122713  sqlite3 *db = p->db;            /* Database connection */
122714  int rc;                         /* Return Code */
122715
122716  /* As it happens, the pending terms table is always empty here. This is
122717  ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
122718  ** always opens a savepoint transaction. And the xSavepoint() method
122719  ** flushes the pending terms table. But leave the (no-op) call to
122720  ** PendingTermsFlush() in in case that changes.
122721  */
122722  assert( p->nPendingData==0 );
122723  rc = sqlite3Fts3PendingTermsFlush(p);
122724
122725  if( p->zContentTbl==0 ){
122726    fts3DbExec(&rc, db,
122727      "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';",
122728      p->zDb, p->zName, zName
122729    );
122730  }
122731
122732  if( p->bHasDocsize ){
122733    fts3DbExec(&rc, db,
122734      "ALTER TABLE %Q.'%q_docsize'  RENAME TO '%q_docsize';",
122735      p->zDb, p->zName, zName
122736    );
122737  }
122738  if( p->bHasStat ){
122739    fts3DbExec(&rc, db,
122740      "ALTER TABLE %Q.'%q_stat'  RENAME TO '%q_stat';",
122741      p->zDb, p->zName, zName
122742    );
122743  }
122744  fts3DbExec(&rc, db,
122745    "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
122746    p->zDb, p->zName, zName
122747  );
122748  fts3DbExec(&rc, db,
122749    "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';",
122750    p->zDb, p->zName, zName
122751  );
122752  return rc;
122753}
122754
122755/*
122756** The xSavepoint() method.
122757**
122758** Flush the contents of the pending-terms table to disk.
122759*/
122760static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
122761  int rc = SQLITE_OK;
122762  UNUSED_PARAMETER(iSavepoint);
122763  assert( ((Fts3Table *)pVtab)->inTransaction );
122764  assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
122765  TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
122766  if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
122767    rc = fts3SyncMethod(pVtab);
122768  }
122769  return rc;
122770}
122771
122772/*
122773** The xRelease() method.
122774**
122775** This is a no-op.
122776*/
122777static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
122778  TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
122779  UNUSED_PARAMETER(iSavepoint);
122780  UNUSED_PARAMETER(pVtab);
122781  assert( p->inTransaction );
122782  assert( p->mxSavepoint >= iSavepoint );
122783  TESTONLY( p->mxSavepoint = iSavepoint-1 );
122784  return SQLITE_OK;
122785}
122786
122787/*
122788** The xRollbackTo() method.
122789**
122790** Discard the contents of the pending terms table.
122791*/
122792static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
122793  Fts3Table *p = (Fts3Table*)pVtab;
122794  UNUSED_PARAMETER(iSavepoint);
122795  assert( p->inTransaction );
122796  assert( p->mxSavepoint >= iSavepoint );
122797  TESTONLY( p->mxSavepoint = iSavepoint );
122798  sqlite3Fts3PendingTermsClear(p);
122799  return SQLITE_OK;
122800}
122801
122802static const sqlite3_module fts3Module = {
122803  /* iVersion      */ 2,
122804  /* xCreate       */ fts3CreateMethod,
122805  /* xConnect      */ fts3ConnectMethod,
122806  /* xBestIndex    */ fts3BestIndexMethod,
122807  /* xDisconnect   */ fts3DisconnectMethod,
122808  /* xDestroy      */ fts3DestroyMethod,
122809  /* xOpen         */ fts3OpenMethod,
122810  /* xClose        */ fts3CloseMethod,
122811  /* xFilter       */ fts3FilterMethod,
122812  /* xNext         */ fts3NextMethod,
122813  /* xEof          */ fts3EofMethod,
122814  /* xColumn       */ fts3ColumnMethod,
122815  /* xRowid        */ fts3RowidMethod,
122816  /* xUpdate       */ fts3UpdateMethod,
122817  /* xBegin        */ fts3BeginMethod,
122818  /* xSync         */ fts3SyncMethod,
122819  /* xCommit       */ fts3CommitMethod,
122820  /* xRollback     */ fts3RollbackMethod,
122821  /* xFindFunction */ fts3FindFunctionMethod,
122822  /* xRename */       fts3RenameMethod,
122823  /* xSavepoint    */ fts3SavepointMethod,
122824  /* xRelease      */ fts3ReleaseMethod,
122825  /* xRollbackTo   */ fts3RollbackToMethod,
122826};
122827
122828/*
122829** This function is registered as the module destructor (called when an
122830** FTS3 enabled database connection is closed). It frees the memory
122831** allocated for the tokenizer hash table.
122832*/
122833static void hashDestroy(void *p){
122834  Fts3Hash *pHash = (Fts3Hash *)p;
122835  sqlite3Fts3HashClear(pHash);
122836  sqlite3_free(pHash);
122837}
122838
122839/*
122840** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
122841** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
122842** respectively. The following three forward declarations are for functions
122843** declared in these files used to retrieve the respective implementations.
122844**
122845** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
122846** to by the argument to point to the "simple" tokenizer implementation.
122847** And so on.
122848*/
122849SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
122850SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
122851#ifdef SQLITE_ENABLE_FTS4_UNICODE61
122852SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
122853#endif
122854#ifdef SQLITE_ENABLE_ICU
122855SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
122856#endif
122857
122858/*
122859** Initialize the fts3 extension. If this extension is built as part
122860** of the sqlite library, then this function is called directly by
122861** SQLite. If fts3 is built as a dynamically loadable extension, this
122862** function is called by the sqlite3_extension_init() entry point.
122863*/
122864SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
122865  int rc = SQLITE_OK;
122866  Fts3Hash *pHash = 0;
122867  const sqlite3_tokenizer_module *pSimple = 0;
122868  const sqlite3_tokenizer_module *pPorter = 0;
122869#ifdef SQLITE_ENABLE_FTS4_UNICODE61
122870  const sqlite3_tokenizer_module *pUnicode = 0;
122871#endif
122872
122873#ifdef SQLITE_ENABLE_ICU
122874  const sqlite3_tokenizer_module *pIcu = 0;
122875  sqlite3Fts3IcuTokenizerModule(&pIcu);
122876#endif
122877
122878#ifdef SQLITE_ENABLE_FTS4_UNICODE61
122879  sqlite3Fts3UnicodeTokenizer(&pUnicode);
122880#endif
122881
122882#ifdef SQLITE_TEST
122883  rc = sqlite3Fts3InitTerm(db);
122884  if( rc!=SQLITE_OK ) return rc;
122885#endif
122886
122887  rc = sqlite3Fts3InitAux(db);
122888  if( rc!=SQLITE_OK ) return rc;
122889
122890  sqlite3Fts3SimpleTokenizerModule(&pSimple);
122891  sqlite3Fts3PorterTokenizerModule(&pPorter);
122892
122893  /* Allocate and initialize the hash-table used to store tokenizers. */
122894  pHash = sqlite3_malloc(sizeof(Fts3Hash));
122895  if( !pHash ){
122896    rc = SQLITE_NOMEM;
122897  }else{
122898    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
122899  }
122900
122901  /* Load the built-in tokenizers into the hash table */
122902  if( rc==SQLITE_OK ){
122903    if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
122904     || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
122905
122906#ifdef SQLITE_ENABLE_FTS4_UNICODE61
122907     || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode)
122908#endif
122909#ifdef SQLITE_ENABLE_ICU
122910     || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
122911#endif
122912    ){
122913      rc = SQLITE_NOMEM;
122914    }
122915  }
122916
122917#ifdef SQLITE_TEST
122918  if( rc==SQLITE_OK ){
122919    rc = sqlite3Fts3ExprInitTestInterface(db);
122920  }
122921#endif
122922
122923  /* Create the virtual table wrapper around the hash-table and overload
122924  ** the two scalar functions. If this is successful, register the
122925  ** module with sqlite.
122926  */
122927  if( SQLITE_OK==rc
122928   && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
122929   && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
122930   && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
122931   && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
122932   && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
122933   && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
122934  ){
122935    rc = sqlite3_create_module_v2(
122936        db, "fts3", &fts3Module, (void *)pHash, hashDestroy
122937    );
122938    if( rc==SQLITE_OK ){
122939      rc = sqlite3_create_module_v2(
122940          db, "fts4", &fts3Module, (void *)pHash, 0
122941      );
122942    }
122943    if( rc==SQLITE_OK ){
122944      rc = sqlite3Fts3InitTok(db, (void *)pHash);
122945    }
122946    return rc;
122947  }
122948
122949
122950  /* An error has occurred. Delete the hash table and return the error code. */
122951  assert( rc!=SQLITE_OK );
122952  if( pHash ){
122953    sqlite3Fts3HashClear(pHash);
122954    sqlite3_free(pHash);
122955  }
122956  return rc;
122957}
122958
122959/*
122960** Allocate an Fts3MultiSegReader for each token in the expression headed
122961** by pExpr.
122962**
122963** An Fts3SegReader object is a cursor that can seek or scan a range of
122964** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
122965** Fts3SegReader objects internally to provide an interface to seek or scan
122966** within the union of all segments of a b-tree. Hence the name.
122967**
122968** If the allocated Fts3MultiSegReader just seeks to a single entry in a
122969** segment b-tree (if the term is not a prefix or it is a prefix for which
122970** there exists prefix b-tree of the right length) then it may be traversed
122971** and merged incrementally. Otherwise, it has to be merged into an in-memory
122972** doclist and then traversed.
122973*/
122974static void fts3EvalAllocateReaders(
122975  Fts3Cursor *pCsr,               /* FTS cursor handle */
122976  Fts3Expr *pExpr,                /* Allocate readers for this expression */
122977  int *pnToken,                   /* OUT: Total number of tokens in phrase. */
122978  int *pnOr,                      /* OUT: Total number of OR nodes in expr. */
122979  int *pRc                        /* IN/OUT: Error code */
122980){
122981  if( pExpr && SQLITE_OK==*pRc ){
122982    if( pExpr->eType==FTSQUERY_PHRASE ){
122983      int i;
122984      int nToken = pExpr->pPhrase->nToken;
122985      *pnToken += nToken;
122986      for(i=0; i<nToken; i++){
122987        Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
122988        int rc = fts3TermSegReaderCursor(pCsr,
122989            pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
122990        );
122991        if( rc!=SQLITE_OK ){
122992          *pRc = rc;
122993          return;
122994        }
122995      }
122996      assert( pExpr->pPhrase->iDoclistToken==0 );
122997      pExpr->pPhrase->iDoclistToken = -1;
122998    }else{
122999      *pnOr += (pExpr->eType==FTSQUERY_OR);
123000      fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
123001      fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
123002    }
123003  }
123004}
123005
123006/*
123007** Arguments pList/nList contain the doclist for token iToken of phrase p.
123008** It is merged into the main doclist stored in p->doclist.aAll/nAll.
123009**
123010** This function assumes that pList points to a buffer allocated using
123011** sqlite3_malloc(). This function takes responsibility for eventually
123012** freeing the buffer.
123013*/
123014static void fts3EvalPhraseMergeToken(
123015  Fts3Table *pTab,                /* FTS Table pointer */
123016  Fts3Phrase *p,                  /* Phrase to merge pList/nList into */
123017  int iToken,                     /* Token pList/nList corresponds to */
123018  char *pList,                    /* Pointer to doclist */
123019  int nList                       /* Number of bytes in pList */
123020){
123021  assert( iToken!=p->iDoclistToken );
123022
123023  if( pList==0 ){
123024    sqlite3_free(p->doclist.aAll);
123025    p->doclist.aAll = 0;
123026    p->doclist.nAll = 0;
123027  }
123028
123029  else if( p->iDoclistToken<0 ){
123030    p->doclist.aAll = pList;
123031    p->doclist.nAll = nList;
123032  }
123033
123034  else if( p->doclist.aAll==0 ){
123035    sqlite3_free(pList);
123036  }
123037
123038  else {
123039    char *pLeft;
123040    char *pRight;
123041    int nLeft;
123042    int nRight;
123043    int nDiff;
123044
123045    if( p->iDoclistToken<iToken ){
123046      pLeft = p->doclist.aAll;
123047      nLeft = p->doclist.nAll;
123048      pRight = pList;
123049      nRight = nList;
123050      nDiff = iToken - p->iDoclistToken;
123051    }else{
123052      pRight = p->doclist.aAll;
123053      nRight = p->doclist.nAll;
123054      pLeft = pList;
123055      nLeft = nList;
123056      nDiff = p->iDoclistToken - iToken;
123057    }
123058
123059    fts3DoclistPhraseMerge(pTab->bDescIdx, nDiff, pLeft, nLeft, pRight,&nRight);
123060    sqlite3_free(pLeft);
123061    p->doclist.aAll = pRight;
123062    p->doclist.nAll = nRight;
123063  }
123064
123065  if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
123066}
123067
123068/*
123069** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
123070** does not take deferred tokens into account.
123071**
123072** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
123073*/
123074static int fts3EvalPhraseLoad(
123075  Fts3Cursor *pCsr,               /* FTS Cursor handle */
123076  Fts3Phrase *p                   /* Phrase object */
123077){
123078  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
123079  int iToken;
123080  int rc = SQLITE_OK;
123081
123082  for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
123083    Fts3PhraseToken *pToken = &p->aToken[iToken];
123084    assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
123085
123086    if( pToken->pSegcsr ){
123087      int nThis = 0;
123088      char *pThis = 0;
123089      rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
123090      if( rc==SQLITE_OK ){
123091        fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
123092      }
123093    }
123094    assert( pToken->pSegcsr==0 );
123095  }
123096
123097  return rc;
123098}
123099
123100/*
123101** This function is called on each phrase after the position lists for
123102** any deferred tokens have been loaded into memory. It updates the phrases
123103** current position list to include only those positions that are really
123104** instances of the phrase (after considering deferred tokens). If this
123105** means that the phrase does not appear in the current row, doclist.pList
123106** and doclist.nList are both zeroed.
123107**
123108** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
123109*/
123110static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
123111  int iToken;                     /* Used to iterate through phrase tokens */
123112  char *aPoslist = 0;             /* Position list for deferred tokens */
123113  int nPoslist = 0;               /* Number of bytes in aPoslist */
123114  int iPrev = -1;                 /* Token number of previous deferred token */
123115
123116  assert( pPhrase->doclist.bFreeList==0 );
123117
123118  for(iToken=0; iToken<pPhrase->nToken; iToken++){
123119    Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
123120    Fts3DeferredToken *pDeferred = pToken->pDeferred;
123121
123122    if( pDeferred ){
123123      char *pList;
123124      int nList;
123125      int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
123126      if( rc!=SQLITE_OK ) return rc;
123127
123128      if( pList==0 ){
123129        sqlite3_free(aPoslist);
123130        pPhrase->doclist.pList = 0;
123131        pPhrase->doclist.nList = 0;
123132        return SQLITE_OK;
123133
123134      }else if( aPoslist==0 ){
123135        aPoslist = pList;
123136        nPoslist = nList;
123137
123138      }else{
123139        char *aOut = pList;
123140        char *p1 = aPoslist;
123141        char *p2 = aOut;
123142
123143        assert( iPrev>=0 );
123144        fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
123145        sqlite3_free(aPoslist);
123146        aPoslist = pList;
123147        nPoslist = (int)(aOut - aPoslist);
123148        if( nPoslist==0 ){
123149          sqlite3_free(aPoslist);
123150          pPhrase->doclist.pList = 0;
123151          pPhrase->doclist.nList = 0;
123152          return SQLITE_OK;
123153        }
123154      }
123155      iPrev = iToken;
123156    }
123157  }
123158
123159  if( iPrev>=0 ){
123160    int nMaxUndeferred = pPhrase->iDoclistToken;
123161    if( nMaxUndeferred<0 ){
123162      pPhrase->doclist.pList = aPoslist;
123163      pPhrase->doclist.nList = nPoslist;
123164      pPhrase->doclist.iDocid = pCsr->iPrevId;
123165      pPhrase->doclist.bFreeList = 1;
123166    }else{
123167      int nDistance;
123168      char *p1;
123169      char *p2;
123170      char *aOut;
123171
123172      if( nMaxUndeferred>iPrev ){
123173        p1 = aPoslist;
123174        p2 = pPhrase->doclist.pList;
123175        nDistance = nMaxUndeferred - iPrev;
123176      }else{
123177        p1 = pPhrase->doclist.pList;
123178        p2 = aPoslist;
123179        nDistance = iPrev - nMaxUndeferred;
123180      }
123181
123182      aOut = (char *)sqlite3_malloc(nPoslist+8);
123183      if( !aOut ){
123184        sqlite3_free(aPoslist);
123185        return SQLITE_NOMEM;
123186      }
123187
123188      pPhrase->doclist.pList = aOut;
123189      if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
123190        pPhrase->doclist.bFreeList = 1;
123191        pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
123192      }else{
123193        sqlite3_free(aOut);
123194        pPhrase->doclist.pList = 0;
123195        pPhrase->doclist.nList = 0;
123196      }
123197      sqlite3_free(aPoslist);
123198    }
123199  }
123200
123201  return SQLITE_OK;
123202}
123203
123204/*
123205** This function is called for each Fts3Phrase in a full-text query
123206** expression to initialize the mechanism for returning rows. Once this
123207** function has been called successfully on an Fts3Phrase, it may be
123208** used with fts3EvalPhraseNext() to iterate through the matching docids.
123209**
123210** If parameter bOptOk is true, then the phrase may (or may not) use the
123211** incremental loading strategy. Otherwise, the entire doclist is loaded into
123212** memory within this call.
123213**
123214** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
123215*/
123216static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
123217  int rc;                         /* Error code */
123218  Fts3PhraseToken *pFirst = &p->aToken[0];
123219  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
123220
123221  if( pCsr->bDesc==pTab->bDescIdx
123222   && bOptOk==1
123223   && p->nToken==1
123224   && pFirst->pSegcsr
123225   && pFirst->pSegcsr->bLookup
123226   && pFirst->bFirst==0
123227  ){
123228    /* Use the incremental approach. */
123229    int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
123230    rc = sqlite3Fts3MsrIncrStart(
123231        pTab, pFirst->pSegcsr, iCol, pFirst->z, pFirst->n);
123232    p->bIncr = 1;
123233
123234  }else{
123235    /* Load the full doclist for the phrase into memory. */
123236    rc = fts3EvalPhraseLoad(pCsr, p);
123237    p->bIncr = 0;
123238  }
123239
123240  assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
123241  return rc;
123242}
123243
123244/*
123245** This function is used to iterate backwards (from the end to start)
123246** through doclists. It is used by this module to iterate through phrase
123247** doclists in reverse and by the fts3_write.c module to iterate through
123248** pending-terms lists when writing to databases with "order=desc".
123249**
123250** The doclist may be sorted in ascending (parameter bDescIdx==0) or
123251** descending (parameter bDescIdx==1) order of docid. Regardless, this
123252** function iterates from the end of the doclist to the beginning.
123253*/
123254SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
123255  int bDescIdx,                   /* True if the doclist is desc */
123256  char *aDoclist,                 /* Pointer to entire doclist */
123257  int nDoclist,                   /* Length of aDoclist in bytes */
123258  char **ppIter,                  /* IN/OUT: Iterator pointer */
123259  sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
123260  int *pnList,                    /* OUT: List length pointer */
123261  u8 *pbEof                       /* OUT: End-of-file flag */
123262){
123263  char *p = *ppIter;
123264
123265  assert( nDoclist>0 );
123266  assert( *pbEof==0 );
123267  assert( p || *piDocid==0 );
123268  assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
123269
123270  if( p==0 ){
123271    sqlite3_int64 iDocid = 0;
123272    char *pNext = 0;
123273    char *pDocid = aDoclist;
123274    char *pEnd = &aDoclist[nDoclist];
123275    int iMul = 1;
123276
123277    while( pDocid<pEnd ){
123278      sqlite3_int64 iDelta;
123279      pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
123280      iDocid += (iMul * iDelta);
123281      pNext = pDocid;
123282      fts3PoslistCopy(0, &pDocid);
123283      while( pDocid<pEnd && *pDocid==0 ) pDocid++;
123284      iMul = (bDescIdx ? -1 : 1);
123285    }
123286
123287    *pnList = (int)(pEnd - pNext);
123288    *ppIter = pNext;
123289    *piDocid = iDocid;
123290  }else{
123291    int iMul = (bDescIdx ? -1 : 1);
123292    sqlite3_int64 iDelta;
123293    fts3GetReverseVarint(&p, aDoclist, &iDelta);
123294    *piDocid -= (iMul * iDelta);
123295
123296    if( p==aDoclist ){
123297      *pbEof = 1;
123298    }else{
123299      char *pSave = p;
123300      fts3ReversePoslist(aDoclist, &p);
123301      *pnList = (int)(pSave - p);
123302    }
123303    *ppIter = p;
123304  }
123305}
123306
123307/*
123308** Iterate forwards through a doclist.
123309*/
123310SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
123311  int bDescIdx,                   /* True if the doclist is desc */
123312  char *aDoclist,                 /* Pointer to entire doclist */
123313  int nDoclist,                   /* Length of aDoclist in bytes */
123314  char **ppIter,                  /* IN/OUT: Iterator pointer */
123315  sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
123316  u8 *pbEof                       /* OUT: End-of-file flag */
123317){
123318  char *p = *ppIter;
123319
123320  assert( nDoclist>0 );
123321  assert( *pbEof==0 );
123322  assert( p || *piDocid==0 );
123323  assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
123324
123325  if( p==0 ){
123326    p = aDoclist;
123327    p += sqlite3Fts3GetVarint(p, piDocid);
123328  }else{
123329    fts3PoslistCopy(0, &p);
123330    if( p>=&aDoclist[nDoclist] ){
123331      *pbEof = 1;
123332    }else{
123333      sqlite3_int64 iVar;
123334      p += sqlite3Fts3GetVarint(p, &iVar);
123335      *piDocid += ((bDescIdx ? -1 : 1) * iVar);
123336    }
123337  }
123338
123339  *ppIter = p;
123340}
123341
123342/*
123343** Attempt to move the phrase iterator to point to the next matching docid.
123344** If an error occurs, return an SQLite error code. Otherwise, return
123345** SQLITE_OK.
123346**
123347** If there is no "next" entry and no error occurs, then *pbEof is set to
123348** 1 before returning. Otherwise, if no error occurs and the iterator is
123349** successfully advanced, *pbEof is set to 0.
123350*/
123351static int fts3EvalPhraseNext(
123352  Fts3Cursor *pCsr,               /* FTS Cursor handle */
123353  Fts3Phrase *p,                  /* Phrase object to advance to next docid */
123354  u8 *pbEof                       /* OUT: Set to 1 if EOF */
123355){
123356  int rc = SQLITE_OK;
123357  Fts3Doclist *pDL = &p->doclist;
123358  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
123359
123360  if( p->bIncr ){
123361    assert( p->nToken==1 );
123362    assert( pDL->pNextDocid==0 );
123363    rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
123364        &pDL->iDocid, &pDL->pList, &pDL->nList
123365    );
123366    if( rc==SQLITE_OK && !pDL->pList ){
123367      *pbEof = 1;
123368    }
123369  }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
123370    sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
123371        &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
123372    );
123373    pDL->pList = pDL->pNextDocid;
123374  }else{
123375    char *pIter;                            /* Used to iterate through aAll */
123376    char *pEnd = &pDL->aAll[pDL->nAll];     /* 1 byte past end of aAll */
123377    if( pDL->pNextDocid ){
123378      pIter = pDL->pNextDocid;
123379    }else{
123380      pIter = pDL->aAll;
123381    }
123382
123383    if( pIter>=pEnd ){
123384      /* We have already reached the end of this doclist. EOF. */
123385      *pbEof = 1;
123386    }else{
123387      sqlite3_int64 iDelta;
123388      pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
123389      if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
123390        pDL->iDocid += iDelta;
123391      }else{
123392        pDL->iDocid -= iDelta;
123393      }
123394      pDL->pList = pIter;
123395      fts3PoslistCopy(0, &pIter);
123396      pDL->nList = (int)(pIter - pDL->pList);
123397
123398      /* pIter now points just past the 0x00 that terminates the position-
123399      ** list for document pDL->iDocid. However, if this position-list was
123400      ** edited in place by fts3EvalNearTrim(), then pIter may not actually
123401      ** point to the start of the next docid value. The following line deals
123402      ** with this case by advancing pIter past the zero-padding added by
123403      ** fts3EvalNearTrim().  */
123404      while( pIter<pEnd && *pIter==0 ) pIter++;
123405
123406      pDL->pNextDocid = pIter;
123407      assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
123408      *pbEof = 0;
123409    }
123410  }
123411
123412  return rc;
123413}
123414
123415/*
123416**
123417** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
123418** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
123419** expression. Also the Fts3Expr.bDeferred variable is set to true for any
123420** expressions for which all descendent tokens are deferred.
123421**
123422** If parameter bOptOk is zero, then it is guaranteed that the
123423** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
123424** each phrase in the expression (subject to deferred token processing).
123425** Or, if bOptOk is non-zero, then one or more tokens within the expression
123426** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
123427**
123428** If an error occurs within this function, *pRc is set to an SQLite error
123429** code before returning.
123430*/
123431static void fts3EvalStartReaders(
123432  Fts3Cursor *pCsr,               /* FTS Cursor handle */
123433  Fts3Expr *pExpr,                /* Expression to initialize phrases in */
123434  int bOptOk,                     /* True to enable incremental loading */
123435  int *pRc                        /* IN/OUT: Error code */
123436){
123437  if( pExpr && SQLITE_OK==*pRc ){
123438    if( pExpr->eType==FTSQUERY_PHRASE ){
123439      int i;
123440      int nToken = pExpr->pPhrase->nToken;
123441      for(i=0; i<nToken; i++){
123442        if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
123443      }
123444      pExpr->bDeferred = (i==nToken);
123445      *pRc = fts3EvalPhraseStart(pCsr, bOptOk, pExpr->pPhrase);
123446    }else{
123447      fts3EvalStartReaders(pCsr, pExpr->pLeft, bOptOk, pRc);
123448      fts3EvalStartReaders(pCsr, pExpr->pRight, bOptOk, pRc);
123449      pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
123450    }
123451  }
123452}
123453
123454/*
123455** An array of the following structures is assembled as part of the process
123456** of selecting tokens to defer before the query starts executing (as part
123457** of the xFilter() method). There is one element in the array for each
123458** token in the FTS expression.
123459**
123460** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
123461** to phrases that are connected only by AND and NEAR operators (not OR or
123462** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
123463** separately. The root of a tokens AND/NEAR cluster is stored in
123464** Fts3TokenAndCost.pRoot.
123465*/
123466typedef struct Fts3TokenAndCost Fts3TokenAndCost;
123467struct Fts3TokenAndCost {
123468  Fts3Phrase *pPhrase;            /* The phrase the token belongs to */
123469  int iToken;                     /* Position of token in phrase */
123470  Fts3PhraseToken *pToken;        /* The token itself */
123471  Fts3Expr *pRoot;                /* Root of NEAR/AND cluster */
123472  int nOvfl;                      /* Number of overflow pages to load doclist */
123473  int iCol;                       /* The column the token must match */
123474};
123475
123476/*
123477** This function is used to populate an allocated Fts3TokenAndCost array.
123478**
123479** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
123480** Otherwise, if an error occurs during execution, *pRc is set to an
123481** SQLite error code.
123482*/
123483static void fts3EvalTokenCosts(
123484  Fts3Cursor *pCsr,               /* FTS Cursor handle */
123485  Fts3Expr *pRoot,                /* Root of current AND/NEAR cluster */
123486  Fts3Expr *pExpr,                /* Expression to consider */
123487  Fts3TokenAndCost **ppTC,        /* Write new entries to *(*ppTC)++ */
123488  Fts3Expr ***ppOr,               /* Write new OR root to *(*ppOr)++ */
123489  int *pRc                        /* IN/OUT: Error code */
123490){
123491  if( *pRc==SQLITE_OK ){
123492    if( pExpr->eType==FTSQUERY_PHRASE ){
123493      Fts3Phrase *pPhrase = pExpr->pPhrase;
123494      int i;
123495      for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
123496        Fts3TokenAndCost *pTC = (*ppTC)++;
123497        pTC->pPhrase = pPhrase;
123498        pTC->iToken = i;
123499        pTC->pRoot = pRoot;
123500        pTC->pToken = &pPhrase->aToken[i];
123501        pTC->iCol = pPhrase->iColumn;
123502        *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
123503      }
123504    }else if( pExpr->eType!=FTSQUERY_NOT ){
123505      assert( pExpr->eType==FTSQUERY_OR
123506           || pExpr->eType==FTSQUERY_AND
123507           || pExpr->eType==FTSQUERY_NEAR
123508      );
123509      assert( pExpr->pLeft && pExpr->pRight );
123510      if( pExpr->eType==FTSQUERY_OR ){
123511        pRoot = pExpr->pLeft;
123512        **ppOr = pRoot;
123513        (*ppOr)++;
123514      }
123515      fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
123516      if( pExpr->eType==FTSQUERY_OR ){
123517        pRoot = pExpr->pRight;
123518        **ppOr = pRoot;
123519        (*ppOr)++;
123520      }
123521      fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
123522    }
123523  }
123524}
123525
123526/*
123527** Determine the average document (row) size in pages. If successful,
123528** write this value to *pnPage and return SQLITE_OK. Otherwise, return
123529** an SQLite error code.
123530**
123531** The average document size in pages is calculated by first calculating
123532** determining the average size in bytes, B. If B is less than the amount
123533** of data that will fit on a single leaf page of an intkey table in
123534** this database, then the average docsize is 1. Otherwise, it is 1 plus
123535** the number of overflow pages consumed by a record B bytes in size.
123536*/
123537static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
123538  if( pCsr->nRowAvg==0 ){
123539    /* The average document size, which is required to calculate the cost
123540    ** of each doclist, has not yet been determined. Read the required
123541    ** data from the %_stat table to calculate it.
123542    **
123543    ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
123544    ** varints, where nCol is the number of columns in the FTS3 table.
123545    ** The first varint is the number of documents currently stored in
123546    ** the table. The following nCol varints contain the total amount of
123547    ** data stored in all rows of each column of the table, from left
123548    ** to right.
123549    */
123550    int rc;
123551    Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
123552    sqlite3_stmt *pStmt;
123553    sqlite3_int64 nDoc = 0;
123554    sqlite3_int64 nByte = 0;
123555    const char *pEnd;
123556    const char *a;
123557
123558    rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
123559    if( rc!=SQLITE_OK ) return rc;
123560    a = sqlite3_column_blob(pStmt, 0);
123561    assert( a );
123562
123563    pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
123564    a += sqlite3Fts3GetVarint(a, &nDoc);
123565    while( a<pEnd ){
123566      a += sqlite3Fts3GetVarint(a, &nByte);
123567    }
123568    if( nDoc==0 || nByte==0 ){
123569      sqlite3_reset(pStmt);
123570      return FTS_CORRUPT_VTAB;
123571    }
123572
123573    pCsr->nDoc = nDoc;
123574    pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
123575    assert( pCsr->nRowAvg>0 );
123576    rc = sqlite3_reset(pStmt);
123577    if( rc!=SQLITE_OK ) return rc;
123578  }
123579
123580  *pnPage = pCsr->nRowAvg;
123581  return SQLITE_OK;
123582}
123583
123584/*
123585** This function is called to select the tokens (if any) that will be
123586** deferred. The array aTC[] has already been populated when this is
123587** called.
123588**
123589** This function is called once for each AND/NEAR cluster in the
123590** expression. Each invocation determines which tokens to defer within
123591** the cluster with root node pRoot. See comments above the definition
123592** of struct Fts3TokenAndCost for more details.
123593**
123594** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
123595** called on each token to defer. Otherwise, an SQLite error code is
123596** returned.
123597*/
123598static int fts3EvalSelectDeferred(
123599  Fts3Cursor *pCsr,               /* FTS Cursor handle */
123600  Fts3Expr *pRoot,                /* Consider tokens with this root node */
123601  Fts3TokenAndCost *aTC,          /* Array of expression tokens and costs */
123602  int nTC                         /* Number of entries in aTC[] */
123603){
123604  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
123605  int nDocSize = 0;               /* Number of pages per doc loaded */
123606  int rc = SQLITE_OK;             /* Return code */
123607  int ii;                         /* Iterator variable for various purposes */
123608  int nOvfl = 0;                  /* Total overflow pages used by doclists */
123609  int nToken = 0;                 /* Total number of tokens in cluster */
123610
123611  int nMinEst = 0;                /* The minimum count for any phrase so far. */
123612  int nLoad4 = 1;                 /* (Phrases that will be loaded)^4. */
123613
123614  /* Tokens are never deferred for FTS tables created using the content=xxx
123615  ** option. The reason being that it is not guaranteed that the content
123616  ** table actually contains the same data as the index. To prevent this from
123617  ** causing any problems, the deferred token optimization is completely
123618  ** disabled for content=xxx tables. */
123619  if( pTab->zContentTbl ){
123620    return SQLITE_OK;
123621  }
123622
123623  /* Count the tokens in this AND/NEAR cluster. If none of the doclists
123624  ** associated with the tokens spill onto overflow pages, or if there is
123625  ** only 1 token, exit early. No tokens to defer in this case. */
123626  for(ii=0; ii<nTC; ii++){
123627    if( aTC[ii].pRoot==pRoot ){
123628      nOvfl += aTC[ii].nOvfl;
123629      nToken++;
123630    }
123631  }
123632  if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
123633
123634  /* Obtain the average docsize (in pages). */
123635  rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
123636  assert( rc!=SQLITE_OK || nDocSize>0 );
123637
123638
123639  /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
123640  ** of the number of overflow pages that will be loaded by the pager layer
123641  ** to retrieve the entire doclist for the token from the full-text index.
123642  ** Load the doclists for tokens that are either:
123643  **
123644  **   a. The cheapest token in the entire query (i.e. the one visited by the
123645  **      first iteration of this loop), or
123646  **
123647  **   b. Part of a multi-token phrase.
123648  **
123649  ** After each token doclist is loaded, merge it with the others from the
123650  ** same phrase and count the number of documents that the merged doclist
123651  ** contains. Set variable "nMinEst" to the smallest number of documents in
123652  ** any phrase doclist for which 1 or more token doclists have been loaded.
123653  ** Let nOther be the number of other phrases for which it is certain that
123654  ** one or more tokens will not be deferred.
123655  **
123656  ** Then, for each token, defer it if loading the doclist would result in
123657  ** loading N or more overflow pages into memory, where N is computed as:
123658  **
123659  **    (nMinEst + 4^nOther - 1) / (4^nOther)
123660  */
123661  for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
123662    int iTC;                      /* Used to iterate through aTC[] array. */
123663    Fts3TokenAndCost *pTC = 0;    /* Set to cheapest remaining token. */
123664
123665    /* Set pTC to point to the cheapest remaining token. */
123666    for(iTC=0; iTC<nTC; iTC++){
123667      if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
123668       && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
123669      ){
123670        pTC = &aTC[iTC];
123671      }
123672    }
123673    assert( pTC );
123674
123675    if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
123676      /* The number of overflow pages to load for this (and therefore all
123677      ** subsequent) tokens is greater than the estimated number of pages
123678      ** that will be loaded if all subsequent tokens are deferred.
123679      */
123680      Fts3PhraseToken *pToken = pTC->pToken;
123681      rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
123682      fts3SegReaderCursorFree(pToken->pSegcsr);
123683      pToken->pSegcsr = 0;
123684    }else{
123685      /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
123686      ** for-loop. Except, limit the value to 2^24 to prevent it from
123687      ** overflowing the 32-bit integer it is stored in. */
123688      if( ii<12 ) nLoad4 = nLoad4*4;
123689
123690      if( ii==0 || pTC->pPhrase->nToken>1 ){
123691        /* Either this is the cheapest token in the entire query, or it is
123692        ** part of a multi-token phrase. Either way, the entire doclist will
123693        ** (eventually) be loaded into memory. It may as well be now. */
123694        Fts3PhraseToken *pToken = pTC->pToken;
123695        int nList = 0;
123696        char *pList = 0;
123697        rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
123698        assert( rc==SQLITE_OK || pList==0 );
123699        if( rc==SQLITE_OK ){
123700          int nCount;
123701          fts3EvalPhraseMergeToken(pTab, pTC->pPhrase, pTC->iToken,pList,nList);
123702          nCount = fts3DoclistCountDocids(
123703              pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
123704          );
123705          if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
123706        }
123707      }
123708    }
123709    pTC->pToken = 0;
123710  }
123711
123712  return rc;
123713}
123714
123715/*
123716** This function is called from within the xFilter method. It initializes
123717** the full-text query currently stored in pCsr->pExpr. To iterate through
123718** the results of a query, the caller does:
123719**
123720**    fts3EvalStart(pCsr);
123721**    while( 1 ){
123722**      fts3EvalNext(pCsr);
123723**      if( pCsr->bEof ) break;
123724**      ... return row pCsr->iPrevId to the caller ...
123725**    }
123726*/
123727static int fts3EvalStart(Fts3Cursor *pCsr){
123728  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
123729  int rc = SQLITE_OK;
123730  int nToken = 0;
123731  int nOr = 0;
123732
123733  /* Allocate a MultiSegReader for each token in the expression. */
123734  fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
123735
123736  /* Determine which, if any, tokens in the expression should be deferred. */
123737#ifndef SQLITE_DISABLE_FTS4_DEFERRED
123738  if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
123739    Fts3TokenAndCost *aTC;
123740    Fts3Expr **apOr;
123741    aTC = (Fts3TokenAndCost *)sqlite3_malloc(
123742        sizeof(Fts3TokenAndCost) * nToken
123743      + sizeof(Fts3Expr *) * nOr * 2
123744    );
123745    apOr = (Fts3Expr **)&aTC[nToken];
123746
123747    if( !aTC ){
123748      rc = SQLITE_NOMEM;
123749    }else{
123750      int ii;
123751      Fts3TokenAndCost *pTC = aTC;
123752      Fts3Expr **ppOr = apOr;
123753
123754      fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
123755      nToken = (int)(pTC-aTC);
123756      nOr = (int)(ppOr-apOr);
123757
123758      if( rc==SQLITE_OK ){
123759        rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
123760        for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
123761          rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
123762        }
123763      }
123764
123765      sqlite3_free(aTC);
123766    }
123767  }
123768#endif
123769
123770  fts3EvalStartReaders(pCsr, pCsr->pExpr, 1, &rc);
123771  return rc;
123772}
123773
123774/*
123775** Invalidate the current position list for phrase pPhrase.
123776*/
123777static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
123778  if( pPhrase->doclist.bFreeList ){
123779    sqlite3_free(pPhrase->doclist.pList);
123780  }
123781  pPhrase->doclist.pList = 0;
123782  pPhrase->doclist.nList = 0;
123783  pPhrase->doclist.bFreeList = 0;
123784}
123785
123786/*
123787** This function is called to edit the position list associated with
123788** the phrase object passed as the fifth argument according to a NEAR
123789** condition. For example:
123790**
123791**     abc NEAR/5 "def ghi"
123792**
123793** Parameter nNear is passed the NEAR distance of the expression (5 in
123794** the example above). When this function is called, *paPoslist points to
123795** the position list, and *pnToken is the number of phrase tokens in, the
123796** phrase on the other side of the NEAR operator to pPhrase. For example,
123797** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
123798** the position list associated with phrase "abc".
123799**
123800** All positions in the pPhrase position list that are not sufficiently
123801** close to a position in the *paPoslist position list are removed. If this
123802** leaves 0 positions, zero is returned. Otherwise, non-zero.
123803**
123804** Before returning, *paPoslist is set to point to the position lsit
123805** associated with pPhrase. And *pnToken is set to the number of tokens in
123806** pPhrase.
123807*/
123808static int fts3EvalNearTrim(
123809  int nNear,                      /* NEAR distance. As in "NEAR/nNear". */
123810  char *aTmp,                     /* Temporary space to use */
123811  char **paPoslist,               /* IN/OUT: Position list */
123812  int *pnToken,                   /* IN/OUT: Tokens in phrase of *paPoslist */
123813  Fts3Phrase *pPhrase             /* The phrase object to trim the doclist of */
123814){
123815  int nParam1 = nNear + pPhrase->nToken;
123816  int nParam2 = nNear + *pnToken;
123817  int nNew;
123818  char *p2;
123819  char *pOut;
123820  int res;
123821
123822  assert( pPhrase->doclist.pList );
123823
123824  p2 = pOut = pPhrase->doclist.pList;
123825  res = fts3PoslistNearMerge(
123826    &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
123827  );
123828  if( res ){
123829    nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
123830    assert( pPhrase->doclist.pList[nNew]=='\0' );
123831    assert( nNew<=pPhrase->doclist.nList && nNew>0 );
123832    memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
123833    pPhrase->doclist.nList = nNew;
123834    *paPoslist = pPhrase->doclist.pList;
123835    *pnToken = pPhrase->nToken;
123836  }
123837
123838  return res;
123839}
123840
123841/*
123842** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
123843** Otherwise, it advances the expression passed as the second argument to
123844** point to the next matching row in the database. Expressions iterate through
123845** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
123846** or descending if it is non-zero.
123847**
123848** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
123849** successful, the following variables in pExpr are set:
123850**
123851**   Fts3Expr.bEof                (non-zero if EOF - there is no next row)
123852**   Fts3Expr.iDocid              (valid if bEof==0. The docid of the next row)
123853**
123854** If the expression is of type FTSQUERY_PHRASE, and the expression is not
123855** at EOF, then the following variables are populated with the position list
123856** for the phrase for the visited row:
123857**
123858**   FTs3Expr.pPhrase->doclist.nList        (length of pList in bytes)
123859**   FTs3Expr.pPhrase->doclist.pList        (pointer to position list)
123860**
123861** It says above that this function advances the expression to the next
123862** matching row. This is usually true, but there are the following exceptions:
123863**
123864**   1. Deferred tokens are not taken into account. If a phrase consists
123865**      entirely of deferred tokens, it is assumed to match every row in
123866**      the db. In this case the position-list is not populated at all.
123867**
123868**      Or, if a phrase contains one or more deferred tokens and one or
123869**      more non-deferred tokens, then the expression is advanced to the
123870**      next possible match, considering only non-deferred tokens. In other
123871**      words, if the phrase is "A B C", and "B" is deferred, the expression
123872**      is advanced to the next row that contains an instance of "A * C",
123873**      where "*" may match any single token. The position list in this case
123874**      is populated as for "A * C" before returning.
123875**
123876**   2. NEAR is treated as AND. If the expression is "x NEAR y", it is
123877**      advanced to point to the next row that matches "x AND y".
123878**
123879** See fts3EvalTestDeferredAndNear() for details on testing if a row is
123880** really a match, taking into account deferred tokens and NEAR operators.
123881*/
123882static void fts3EvalNextRow(
123883  Fts3Cursor *pCsr,               /* FTS Cursor handle */
123884  Fts3Expr *pExpr,                /* Expr. to advance to next matching row */
123885  int *pRc                        /* IN/OUT: Error code */
123886){
123887  if( *pRc==SQLITE_OK ){
123888    int bDescDoclist = pCsr->bDesc;         /* Used by DOCID_CMP() macro */
123889    assert( pExpr->bEof==0 );
123890    pExpr->bStart = 1;
123891
123892    switch( pExpr->eType ){
123893      case FTSQUERY_NEAR:
123894      case FTSQUERY_AND: {
123895        Fts3Expr *pLeft = pExpr->pLeft;
123896        Fts3Expr *pRight = pExpr->pRight;
123897        assert( !pLeft->bDeferred || !pRight->bDeferred );
123898
123899        if( pLeft->bDeferred ){
123900          /* LHS is entirely deferred. So we assume it matches every row.
123901          ** Advance the RHS iterator to find the next row visited. */
123902          fts3EvalNextRow(pCsr, pRight, pRc);
123903          pExpr->iDocid = pRight->iDocid;
123904          pExpr->bEof = pRight->bEof;
123905        }else if( pRight->bDeferred ){
123906          /* RHS is entirely deferred. So we assume it matches every row.
123907          ** Advance the LHS iterator to find the next row visited. */
123908          fts3EvalNextRow(pCsr, pLeft, pRc);
123909          pExpr->iDocid = pLeft->iDocid;
123910          pExpr->bEof = pLeft->bEof;
123911        }else{
123912          /* Neither the RHS or LHS are deferred. */
123913          fts3EvalNextRow(pCsr, pLeft, pRc);
123914          fts3EvalNextRow(pCsr, pRight, pRc);
123915          while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
123916            sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
123917            if( iDiff==0 ) break;
123918            if( iDiff<0 ){
123919              fts3EvalNextRow(pCsr, pLeft, pRc);
123920            }else{
123921              fts3EvalNextRow(pCsr, pRight, pRc);
123922            }
123923          }
123924          pExpr->iDocid = pLeft->iDocid;
123925          pExpr->bEof = (pLeft->bEof || pRight->bEof);
123926        }
123927        break;
123928      }
123929
123930      case FTSQUERY_OR: {
123931        Fts3Expr *pLeft = pExpr->pLeft;
123932        Fts3Expr *pRight = pExpr->pRight;
123933        sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
123934
123935        assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
123936        assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
123937
123938        if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
123939          fts3EvalNextRow(pCsr, pLeft, pRc);
123940        }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){
123941          fts3EvalNextRow(pCsr, pRight, pRc);
123942        }else{
123943          fts3EvalNextRow(pCsr, pLeft, pRc);
123944          fts3EvalNextRow(pCsr, pRight, pRc);
123945        }
123946
123947        pExpr->bEof = (pLeft->bEof && pRight->bEof);
123948        iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
123949        if( pRight->bEof || (pLeft->bEof==0 &&  iCmp<0) ){
123950          pExpr->iDocid = pLeft->iDocid;
123951        }else{
123952          pExpr->iDocid = pRight->iDocid;
123953        }
123954
123955        break;
123956      }
123957
123958      case FTSQUERY_NOT: {
123959        Fts3Expr *pLeft = pExpr->pLeft;
123960        Fts3Expr *pRight = pExpr->pRight;
123961
123962        if( pRight->bStart==0 ){
123963          fts3EvalNextRow(pCsr, pRight, pRc);
123964          assert( *pRc!=SQLITE_OK || pRight->bStart );
123965        }
123966
123967        fts3EvalNextRow(pCsr, pLeft, pRc);
123968        if( pLeft->bEof==0 ){
123969          while( !*pRc
123970              && !pRight->bEof
123971              && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
123972          ){
123973            fts3EvalNextRow(pCsr, pRight, pRc);
123974          }
123975        }
123976        pExpr->iDocid = pLeft->iDocid;
123977        pExpr->bEof = pLeft->bEof;
123978        break;
123979      }
123980
123981      default: {
123982        Fts3Phrase *pPhrase = pExpr->pPhrase;
123983        fts3EvalInvalidatePoslist(pPhrase);
123984        *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
123985        pExpr->iDocid = pPhrase->doclist.iDocid;
123986        break;
123987      }
123988    }
123989  }
123990}
123991
123992/*
123993** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
123994** cluster, then this function returns 1 immediately.
123995**
123996** Otherwise, it checks if the current row really does match the NEAR
123997** expression, using the data currently stored in the position lists
123998** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
123999**
124000** If the current row is a match, the position list associated with each
124001** phrase in the NEAR expression is edited in place to contain only those
124002** phrase instances sufficiently close to their peers to satisfy all NEAR
124003** constraints. In this case it returns 1. If the NEAR expression does not
124004** match the current row, 0 is returned. The position lists may or may not
124005** be edited if 0 is returned.
124006*/
124007static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
124008  int res = 1;
124009
124010  /* The following block runs if pExpr is the root of a NEAR query.
124011  ** For example, the query:
124012  **
124013  **         "w" NEAR "x" NEAR "y" NEAR "z"
124014  **
124015  ** which is represented in tree form as:
124016  **
124017  **                               |
124018  **                          +--NEAR--+      <-- root of NEAR query
124019  **                          |        |
124020  **                     +--NEAR--+   "z"
124021  **                     |        |
124022  **                +--NEAR--+   "y"
124023  **                |        |
124024  **               "w"      "x"
124025  **
124026  ** The right-hand child of a NEAR node is always a phrase. The
124027  ** left-hand child may be either a phrase or a NEAR node. There are
124028  ** no exceptions to this - it's the way the parser in fts3_expr.c works.
124029  */
124030  if( *pRc==SQLITE_OK
124031   && pExpr->eType==FTSQUERY_NEAR
124032   && pExpr->bEof==0
124033   && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
124034  ){
124035    Fts3Expr *p;
124036    int nTmp = 0;                 /* Bytes of temp space */
124037    char *aTmp;                   /* Temp space for PoslistNearMerge() */
124038
124039    /* Allocate temporary working space. */
124040    for(p=pExpr; p->pLeft; p=p->pLeft){
124041      nTmp += p->pRight->pPhrase->doclist.nList;
124042    }
124043    nTmp += p->pPhrase->doclist.nList;
124044    if( nTmp==0 ){
124045      res = 0;
124046    }else{
124047      aTmp = sqlite3_malloc(nTmp*2);
124048      if( !aTmp ){
124049        *pRc = SQLITE_NOMEM;
124050        res = 0;
124051      }else{
124052        char *aPoslist = p->pPhrase->doclist.pList;
124053        int nToken = p->pPhrase->nToken;
124054
124055        for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
124056          Fts3Phrase *pPhrase = p->pRight->pPhrase;
124057          int nNear = p->nNear;
124058          res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
124059        }
124060
124061        aPoslist = pExpr->pRight->pPhrase->doclist.pList;
124062        nToken = pExpr->pRight->pPhrase->nToken;
124063        for(p=pExpr->pLeft; p && res; p=p->pLeft){
124064          int nNear;
124065          Fts3Phrase *pPhrase;
124066          assert( p->pParent && p->pParent->pLeft==p );
124067          nNear = p->pParent->nNear;
124068          pPhrase = (
124069              p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
124070              );
124071          res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
124072        }
124073      }
124074
124075      sqlite3_free(aTmp);
124076    }
124077  }
124078
124079  return res;
124080}
124081
124082/*
124083** This function is a helper function for fts3EvalTestDeferredAndNear().
124084** Assuming no error occurs or has occurred, It returns non-zero if the
124085** expression passed as the second argument matches the row that pCsr
124086** currently points to, or zero if it does not.
124087**
124088** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
124089** If an error occurs during execution of this function, *pRc is set to
124090** the appropriate SQLite error code. In this case the returned value is
124091** undefined.
124092*/
124093static int fts3EvalTestExpr(
124094  Fts3Cursor *pCsr,               /* FTS cursor handle */
124095  Fts3Expr *pExpr,                /* Expr to test. May or may not be root. */
124096  int *pRc                        /* IN/OUT: Error code */
124097){
124098  int bHit = 1;                   /* Return value */
124099  if( *pRc==SQLITE_OK ){
124100    switch( pExpr->eType ){
124101      case FTSQUERY_NEAR:
124102      case FTSQUERY_AND:
124103        bHit = (
124104            fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
124105         && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
124106         && fts3EvalNearTest(pExpr, pRc)
124107        );
124108
124109        /* If the NEAR expression does not match any rows, zero the doclist for
124110        ** all phrases involved in the NEAR. This is because the snippet(),
124111        ** offsets() and matchinfo() functions are not supposed to recognize
124112        ** any instances of phrases that are part of unmatched NEAR queries.
124113        ** For example if this expression:
124114        **
124115        **    ... MATCH 'a OR (b NEAR c)'
124116        **
124117        ** is matched against a row containing:
124118        **
124119        **        'a b d e'
124120        **
124121        ** then any snippet() should ony highlight the "a" term, not the "b"
124122        ** (as "b" is part of a non-matching NEAR clause).
124123        */
124124        if( bHit==0
124125         && pExpr->eType==FTSQUERY_NEAR
124126         && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
124127        ){
124128          Fts3Expr *p;
124129          for(p=pExpr; p->pPhrase==0; p=p->pLeft){
124130            if( p->pRight->iDocid==pCsr->iPrevId ){
124131              fts3EvalInvalidatePoslist(p->pRight->pPhrase);
124132            }
124133          }
124134          if( p->iDocid==pCsr->iPrevId ){
124135            fts3EvalInvalidatePoslist(p->pPhrase);
124136          }
124137        }
124138
124139        break;
124140
124141      case FTSQUERY_OR: {
124142        int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
124143        int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
124144        bHit = bHit1 || bHit2;
124145        break;
124146      }
124147
124148      case FTSQUERY_NOT:
124149        bHit = (
124150            fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
124151         && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
124152        );
124153        break;
124154
124155      default: {
124156#ifndef SQLITE_DISABLE_FTS4_DEFERRED
124157        if( pCsr->pDeferred
124158         && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
124159        ){
124160          Fts3Phrase *pPhrase = pExpr->pPhrase;
124161          assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
124162          if( pExpr->bDeferred ){
124163            fts3EvalInvalidatePoslist(pPhrase);
124164          }
124165          *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
124166          bHit = (pPhrase->doclist.pList!=0);
124167          pExpr->iDocid = pCsr->iPrevId;
124168        }else
124169#endif
124170        {
124171          bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
124172        }
124173        break;
124174      }
124175    }
124176  }
124177  return bHit;
124178}
124179
124180/*
124181** This function is called as the second part of each xNext operation when
124182** iterating through the results of a full-text query. At this point the
124183** cursor points to a row that matches the query expression, with the
124184** following caveats:
124185**
124186**   * Up until this point, "NEAR" operators in the expression have been
124187**     treated as "AND".
124188**
124189**   * Deferred tokens have not yet been considered.
124190**
124191** If *pRc is not SQLITE_OK when this function is called, it immediately
124192** returns 0. Otherwise, it tests whether or not after considering NEAR
124193** operators and deferred tokens the current row is still a match for the
124194** expression. It returns 1 if both of the following are true:
124195**
124196**   1. *pRc is SQLITE_OK when this function returns, and
124197**
124198**   2. After scanning the current FTS table row for the deferred tokens,
124199**      it is determined that the row does *not* match the query.
124200**
124201** Or, if no error occurs and it seems the current row does match the FTS
124202** query, return 0.
124203*/
124204static int fts3EvalTestDeferredAndNear(Fts3Cursor *pCsr, int *pRc){
124205  int rc = *pRc;
124206  int bMiss = 0;
124207  if( rc==SQLITE_OK ){
124208
124209    /* If there are one or more deferred tokens, load the current row into
124210    ** memory and scan it to determine the position list for each deferred
124211    ** token. Then, see if this row is really a match, considering deferred
124212    ** tokens and NEAR operators (neither of which were taken into account
124213    ** earlier, by fts3EvalNextRow()).
124214    */
124215    if( pCsr->pDeferred ){
124216      rc = fts3CursorSeek(0, pCsr);
124217      if( rc==SQLITE_OK ){
124218        rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
124219      }
124220    }
124221    bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
124222
124223    /* Free the position-lists accumulated for each deferred token above. */
124224    sqlite3Fts3FreeDeferredDoclists(pCsr);
124225    *pRc = rc;
124226  }
124227  return (rc==SQLITE_OK && bMiss);
124228}
124229
124230/*
124231** Advance to the next document that matches the FTS expression in
124232** Fts3Cursor.pExpr.
124233*/
124234static int fts3EvalNext(Fts3Cursor *pCsr){
124235  int rc = SQLITE_OK;             /* Return Code */
124236  Fts3Expr *pExpr = pCsr->pExpr;
124237  assert( pCsr->isEof==0 );
124238  if( pExpr==0 ){
124239    pCsr->isEof = 1;
124240  }else{
124241    do {
124242      if( pCsr->isRequireSeek==0 ){
124243        sqlite3_reset(pCsr->pStmt);
124244      }
124245      assert( sqlite3_data_count(pCsr->pStmt)==0 );
124246      fts3EvalNextRow(pCsr, pExpr, &rc);
124247      pCsr->isEof = pExpr->bEof;
124248      pCsr->isRequireSeek = 1;
124249      pCsr->isMatchinfoNeeded = 1;
124250      pCsr->iPrevId = pExpr->iDocid;
124251    }while( pCsr->isEof==0 && fts3EvalTestDeferredAndNear(pCsr, &rc) );
124252  }
124253  return rc;
124254}
124255
124256/*
124257** Restart interation for expression pExpr so that the next call to
124258** fts3EvalNext() visits the first row. Do not allow incremental
124259** loading or merging of phrase doclists for this iteration.
124260**
124261** If *pRc is other than SQLITE_OK when this function is called, it is
124262** a no-op. If an error occurs within this function, *pRc is set to an
124263** SQLite error code before returning.
124264*/
124265static void fts3EvalRestart(
124266  Fts3Cursor *pCsr,
124267  Fts3Expr *pExpr,
124268  int *pRc
124269){
124270  if( pExpr && *pRc==SQLITE_OK ){
124271    Fts3Phrase *pPhrase = pExpr->pPhrase;
124272
124273    if( pPhrase ){
124274      fts3EvalInvalidatePoslist(pPhrase);
124275      if( pPhrase->bIncr ){
124276        assert( pPhrase->nToken==1 );
124277        assert( pPhrase->aToken[0].pSegcsr );
124278        sqlite3Fts3MsrIncrRestart(pPhrase->aToken[0].pSegcsr);
124279        *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
124280      }
124281
124282      pPhrase->doclist.pNextDocid = 0;
124283      pPhrase->doclist.iDocid = 0;
124284    }
124285
124286    pExpr->iDocid = 0;
124287    pExpr->bEof = 0;
124288    pExpr->bStart = 0;
124289
124290    fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
124291    fts3EvalRestart(pCsr, pExpr->pRight, pRc);
124292  }
124293}
124294
124295/*
124296** After allocating the Fts3Expr.aMI[] array for each phrase in the
124297** expression rooted at pExpr, the cursor iterates through all rows matched
124298** by pExpr, calling this function for each row. This function increments
124299** the values in Fts3Expr.aMI[] according to the position-list currently
124300** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
124301** expression nodes.
124302*/
124303static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
124304  if( pExpr ){
124305    Fts3Phrase *pPhrase = pExpr->pPhrase;
124306    if( pPhrase && pPhrase->doclist.pList ){
124307      int iCol = 0;
124308      char *p = pPhrase->doclist.pList;
124309
124310      assert( *p );
124311      while( 1 ){
124312        u8 c = 0;
124313        int iCnt = 0;
124314        while( 0xFE & (*p | c) ){
124315          if( (c&0x80)==0 ) iCnt++;
124316          c = *p++ & 0x80;
124317        }
124318
124319        /* aMI[iCol*3 + 1] = Number of occurrences
124320        ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
124321        */
124322        pExpr->aMI[iCol*3 + 1] += iCnt;
124323        pExpr->aMI[iCol*3 + 2] += (iCnt>0);
124324        if( *p==0x00 ) break;
124325        p++;
124326        p += sqlite3Fts3GetVarint32(p, &iCol);
124327      }
124328    }
124329
124330    fts3EvalUpdateCounts(pExpr->pLeft);
124331    fts3EvalUpdateCounts(pExpr->pRight);
124332  }
124333}
124334
124335/*
124336** Expression pExpr must be of type FTSQUERY_PHRASE.
124337**
124338** If it is not already allocated and populated, this function allocates and
124339** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
124340** of a NEAR expression, then it also allocates and populates the same array
124341** for all other phrases that are part of the NEAR expression.
124342**
124343** SQLITE_OK is returned if the aMI[] array is successfully allocated and
124344** populated. Otherwise, if an error occurs, an SQLite error code is returned.
124345*/
124346static int fts3EvalGatherStats(
124347  Fts3Cursor *pCsr,               /* Cursor object */
124348  Fts3Expr *pExpr                 /* FTSQUERY_PHRASE expression */
124349){
124350  int rc = SQLITE_OK;             /* Return code */
124351
124352  assert( pExpr->eType==FTSQUERY_PHRASE );
124353  if( pExpr->aMI==0 ){
124354    Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
124355    Fts3Expr *pRoot;                /* Root of NEAR expression */
124356    Fts3Expr *p;                    /* Iterator used for several purposes */
124357
124358    sqlite3_int64 iPrevId = pCsr->iPrevId;
124359    sqlite3_int64 iDocid;
124360    u8 bEof;
124361
124362    /* Find the root of the NEAR expression */
124363    pRoot = pExpr;
124364    while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
124365      pRoot = pRoot->pParent;
124366    }
124367    iDocid = pRoot->iDocid;
124368    bEof = pRoot->bEof;
124369    assert( pRoot->bStart );
124370
124371    /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
124372    for(p=pRoot; p; p=p->pLeft){
124373      Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
124374      assert( pE->aMI==0 );
124375      pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
124376      if( !pE->aMI ) return SQLITE_NOMEM;
124377      memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
124378    }
124379
124380    fts3EvalRestart(pCsr, pRoot, &rc);
124381
124382    while( pCsr->isEof==0 && rc==SQLITE_OK ){
124383
124384      do {
124385        /* Ensure the %_content statement is reset. */
124386        if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
124387        assert( sqlite3_data_count(pCsr->pStmt)==0 );
124388
124389        /* Advance to the next document */
124390        fts3EvalNextRow(pCsr, pRoot, &rc);
124391        pCsr->isEof = pRoot->bEof;
124392        pCsr->isRequireSeek = 1;
124393        pCsr->isMatchinfoNeeded = 1;
124394        pCsr->iPrevId = pRoot->iDocid;
124395      }while( pCsr->isEof==0
124396           && pRoot->eType==FTSQUERY_NEAR
124397           && fts3EvalTestDeferredAndNear(pCsr, &rc)
124398      );
124399
124400      if( rc==SQLITE_OK && pCsr->isEof==0 ){
124401        fts3EvalUpdateCounts(pRoot);
124402      }
124403    }
124404
124405    pCsr->isEof = 0;
124406    pCsr->iPrevId = iPrevId;
124407
124408    if( bEof ){
124409      pRoot->bEof = bEof;
124410    }else{
124411      /* Caution: pRoot may iterate through docids in ascending or descending
124412      ** order. For this reason, even though it seems more defensive, the
124413      ** do loop can not be written:
124414      **
124415      **   do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
124416      */
124417      fts3EvalRestart(pCsr, pRoot, &rc);
124418      do {
124419        fts3EvalNextRow(pCsr, pRoot, &rc);
124420        assert( pRoot->bEof==0 );
124421      }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
124422      fts3EvalTestDeferredAndNear(pCsr, &rc);
124423    }
124424  }
124425  return rc;
124426}
124427
124428/*
124429** This function is used by the matchinfo() module to query a phrase
124430** expression node for the following information:
124431**
124432**   1. The total number of occurrences of the phrase in each column of
124433**      the FTS table (considering all rows), and
124434**
124435**   2. For each column, the number of rows in the table for which the
124436**      column contains at least one instance of the phrase.
124437**
124438** If no error occurs, SQLITE_OK is returned and the values for each column
124439** written into the array aiOut as follows:
124440**
124441**   aiOut[iCol*3 + 1] = Number of occurrences
124442**   aiOut[iCol*3 + 2] = Number of rows containing at least one instance
124443**
124444** Caveats:
124445**
124446**   * If a phrase consists entirely of deferred tokens, then all output
124447**     values are set to the number of documents in the table. In other
124448**     words we assume that very common tokens occur exactly once in each
124449**     column of each row of the table.
124450**
124451**   * If a phrase contains some deferred tokens (and some non-deferred
124452**     tokens), count the potential occurrence identified by considering
124453**     the non-deferred tokens instead of actual phrase occurrences.
124454**
124455**   * If the phrase is part of a NEAR expression, then only phrase instances
124456**     that meet the NEAR constraint are included in the counts.
124457*/
124458SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
124459  Fts3Cursor *pCsr,               /* FTS cursor handle */
124460  Fts3Expr *pExpr,                /* Phrase expression */
124461  u32 *aiOut                      /* Array to write results into (see above) */
124462){
124463  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
124464  int rc = SQLITE_OK;
124465  int iCol;
124466
124467  if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
124468    assert( pCsr->nDoc>0 );
124469    for(iCol=0; iCol<pTab->nColumn; iCol++){
124470      aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
124471      aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
124472    }
124473  }else{
124474    rc = fts3EvalGatherStats(pCsr, pExpr);
124475    if( rc==SQLITE_OK ){
124476      assert( pExpr->aMI );
124477      for(iCol=0; iCol<pTab->nColumn; iCol++){
124478        aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
124479        aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
124480      }
124481    }
124482  }
124483
124484  return rc;
124485}
124486
124487/*
124488** The expression pExpr passed as the second argument to this function
124489** must be of type FTSQUERY_PHRASE.
124490**
124491** The returned value is either NULL or a pointer to a buffer containing
124492** a position-list indicating the occurrences of the phrase in column iCol
124493** of the current row.
124494**
124495** More specifically, the returned buffer contains 1 varint for each
124496** occurrence of the phrase in the column, stored using the normal (delta+2)
124497** compression and is terminated by either an 0x01 or 0x00 byte. For example,
124498** if the requested column contains "a b X c d X X" and the position-list
124499** for 'X' is requested, the buffer returned may contain:
124500**
124501**     0x04 0x05 0x03 0x01   or   0x04 0x05 0x03 0x00
124502**
124503** This function works regardless of whether or not the phrase is deferred,
124504** incremental, or neither.
124505*/
124506SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
124507  Fts3Cursor *pCsr,               /* FTS3 cursor object */
124508  Fts3Expr *pExpr,                /* Phrase to return doclist for */
124509  int iCol,                       /* Column to return position list for */
124510  char **ppOut                    /* OUT: Pointer to position list */
124511){
124512  Fts3Phrase *pPhrase = pExpr->pPhrase;
124513  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
124514  char *pIter;
124515  int iThis;
124516  sqlite3_int64 iDocid;
124517
124518  /* If this phrase is applies specifically to some column other than
124519  ** column iCol, return a NULL pointer.  */
124520  *ppOut = 0;
124521  assert( iCol>=0 && iCol<pTab->nColumn );
124522  if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
124523    return SQLITE_OK;
124524  }
124525
124526  iDocid = pExpr->iDocid;
124527  pIter = pPhrase->doclist.pList;
124528  if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
124529    int bDescDoclist = pTab->bDescIdx;      /* For DOCID_CMP macro */
124530    int bOr = 0;
124531    u8 bEof = 0;
124532    Fts3Expr *p;
124533
124534    /* Check if this phrase descends from an OR expression node. If not,
124535    ** return NULL. Otherwise, the entry that corresponds to docid
124536    ** pCsr->iPrevId may lie earlier in the doclist buffer. */
124537    for(p=pExpr->pParent; p; p=p->pParent){
124538      if( p->eType==FTSQUERY_OR ) bOr = 1;
124539    }
124540    if( bOr==0 ) return SQLITE_OK;
124541
124542    /* This is the descendent of an OR node. In this case we cannot use
124543    ** an incremental phrase. Load the entire doclist for the phrase
124544    ** into memory in this case.  */
124545    if( pPhrase->bIncr ){
124546      int rc = SQLITE_OK;
124547      int bEofSave = pExpr->bEof;
124548      fts3EvalRestart(pCsr, pExpr, &rc);
124549      while( rc==SQLITE_OK && !pExpr->bEof ){
124550        fts3EvalNextRow(pCsr, pExpr, &rc);
124551        if( bEofSave==0 && pExpr->iDocid==iDocid ) break;
124552      }
124553      pIter = pPhrase->doclist.pList;
124554      assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
124555      if( rc!=SQLITE_OK ) return rc;
124556    }
124557
124558    if( pExpr->bEof ){
124559      pIter = 0;
124560      iDocid = 0;
124561    }
124562    bEof = (pPhrase->doclist.nAll==0);
124563    assert( bDescDoclist==0 || bDescDoclist==1 );
124564    assert( pCsr->bDesc==0 || pCsr->bDesc==1 );
124565
124566    if( pCsr->bDesc==bDescDoclist ){
124567      int dummy;
124568      while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
124569        sqlite3Fts3DoclistPrev(
124570            bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll,
124571            &pIter, &iDocid, &dummy, &bEof
124572        );
124573      }
124574    }else{
124575      while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
124576        sqlite3Fts3DoclistNext(
124577            bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll,
124578            &pIter, &iDocid, &bEof
124579        );
124580      }
124581    }
124582
124583    if( bEof || iDocid!=pCsr->iPrevId ) pIter = 0;
124584  }
124585  if( pIter==0 ) return SQLITE_OK;
124586
124587  if( *pIter==0x01 ){
124588    pIter++;
124589    pIter += sqlite3Fts3GetVarint32(pIter, &iThis);
124590  }else{
124591    iThis = 0;
124592  }
124593  while( iThis<iCol ){
124594    fts3ColumnlistCopy(0, &pIter);
124595    if( *pIter==0x00 ) return 0;
124596    pIter++;
124597    pIter += sqlite3Fts3GetVarint32(pIter, &iThis);
124598  }
124599
124600  *ppOut = ((iCol==iThis)?pIter:0);
124601  return SQLITE_OK;
124602}
124603
124604/*
124605** Free all components of the Fts3Phrase structure that were allocated by
124606** the eval module. Specifically, this means to free:
124607**
124608**   * the contents of pPhrase->doclist, and
124609**   * any Fts3MultiSegReader objects held by phrase tokens.
124610*/
124611SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
124612  if( pPhrase ){
124613    int i;
124614    sqlite3_free(pPhrase->doclist.aAll);
124615    fts3EvalInvalidatePoslist(pPhrase);
124616    memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
124617    for(i=0; i<pPhrase->nToken; i++){
124618      fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
124619      pPhrase->aToken[i].pSegcsr = 0;
124620    }
124621  }
124622}
124623
124624
124625/*
124626** Return SQLITE_CORRUPT_VTAB.
124627*/
124628#ifdef SQLITE_DEBUG
124629SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
124630  return SQLITE_CORRUPT_VTAB;
124631}
124632#endif
124633
124634#if !SQLITE_CORE
124635/*
124636** Initialize API pointer table, if required.
124637*/
124638SQLITE_API int sqlite3_extension_init(
124639  sqlite3 *db,
124640  char **pzErrMsg,
124641  const sqlite3_api_routines *pApi
124642){
124643  SQLITE_EXTENSION_INIT2(pApi)
124644  return sqlite3Fts3Init(db);
124645}
124646#endif
124647
124648#endif
124649
124650/************** End of fts3.c ************************************************/
124651/************** Begin file fts3_aux.c ****************************************/
124652/*
124653** 2011 Jan 27
124654**
124655** The author disclaims copyright to this source code.  In place of
124656** a legal notice, here is a blessing:
124657**
124658**    May you do good and not evil.
124659**    May you find forgiveness for yourself and forgive others.
124660**    May you share freely, never taking more than you give.
124661**
124662******************************************************************************
124663**
124664*/
124665#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
124666
124667/* #include <string.h> */
124668/* #include <assert.h> */
124669
124670typedef struct Fts3auxTable Fts3auxTable;
124671typedef struct Fts3auxCursor Fts3auxCursor;
124672
124673struct Fts3auxTable {
124674  sqlite3_vtab base;              /* Base class used by SQLite core */
124675  Fts3Table *pFts3Tab;
124676};
124677
124678struct Fts3auxCursor {
124679  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
124680  Fts3MultiSegReader csr;        /* Must be right after "base" */
124681  Fts3SegFilter filter;
124682  char *zStop;
124683  int nStop;                      /* Byte-length of string zStop */
124684  int isEof;                      /* True if cursor is at EOF */
124685  sqlite3_int64 iRowid;           /* Current rowid */
124686
124687  int iCol;                       /* Current value of 'col' column */
124688  int nStat;                      /* Size of aStat[] array */
124689  struct Fts3auxColstats {
124690    sqlite3_int64 nDoc;           /* 'documents' values for current csr row */
124691    sqlite3_int64 nOcc;           /* 'occurrences' values for current csr row */
124692  } *aStat;
124693};
124694
124695/*
124696** Schema of the terms table.
124697*/
124698#define FTS3_TERMS_SCHEMA "CREATE TABLE x(term, col, documents, occurrences)"
124699
124700/*
124701** This function does all the work for both the xConnect and xCreate methods.
124702** These tables have no persistent representation of their own, so xConnect
124703** and xCreate are identical operations.
124704*/
124705static int fts3auxConnectMethod(
124706  sqlite3 *db,                    /* Database connection */
124707  void *pUnused,                  /* Unused */
124708  int argc,                       /* Number of elements in argv array */
124709  const char * const *argv,       /* xCreate/xConnect argument array */
124710  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
124711  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
124712){
124713  char const *zDb;                /* Name of database (e.g. "main") */
124714  char const *zFts3;              /* Name of fts3 table */
124715  int nDb;                        /* Result of strlen(zDb) */
124716  int nFts3;                      /* Result of strlen(zFts3) */
124717  int nByte;                      /* Bytes of space to allocate here */
124718  int rc;                         /* value returned by declare_vtab() */
124719  Fts3auxTable *p;                /* Virtual table object to return */
124720
124721  UNUSED_PARAMETER(pUnused);
124722
124723  /* The user should invoke this in one of two forms:
124724  **
124725  **     CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table);
124726  **     CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table);
124727  */
124728  if( argc!=4 && argc!=5 ) goto bad_args;
124729
124730  zDb = argv[1];
124731  nDb = (int)strlen(zDb);
124732  if( argc==5 ){
124733    if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){
124734      zDb = argv[3];
124735      nDb = (int)strlen(zDb);
124736      zFts3 = argv[4];
124737    }else{
124738      goto bad_args;
124739    }
124740  }else{
124741    zFts3 = argv[3];
124742  }
124743  nFts3 = (int)strlen(zFts3);
124744
124745  rc = sqlite3_declare_vtab(db, FTS3_TERMS_SCHEMA);
124746  if( rc!=SQLITE_OK ) return rc;
124747
124748  nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
124749  p = (Fts3auxTable *)sqlite3_malloc(nByte);
124750  if( !p ) return SQLITE_NOMEM;
124751  memset(p, 0, nByte);
124752
124753  p->pFts3Tab = (Fts3Table *)&p[1];
124754  p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
124755  p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
124756  p->pFts3Tab->db = db;
124757  p->pFts3Tab->nIndex = 1;
124758
124759  memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
124760  memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
124761  sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
124762
124763  *ppVtab = (sqlite3_vtab *)p;
124764  return SQLITE_OK;
124765
124766 bad_args:
124767  *pzErr = sqlite3_mprintf("invalid arguments to fts4aux constructor");
124768  return SQLITE_ERROR;
124769}
124770
124771/*
124772** This function does the work for both the xDisconnect and xDestroy methods.
124773** These tables have no persistent representation of their own, so xDisconnect
124774** and xDestroy are identical operations.
124775*/
124776static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
124777  Fts3auxTable *p = (Fts3auxTable *)pVtab;
124778  Fts3Table *pFts3 = p->pFts3Tab;
124779  int i;
124780
124781  /* Free any prepared statements held */
124782  for(i=0; i<SizeofArray(pFts3->aStmt); i++){
124783    sqlite3_finalize(pFts3->aStmt[i]);
124784  }
124785  sqlite3_free(pFts3->zSegmentsTbl);
124786  sqlite3_free(p);
124787  return SQLITE_OK;
124788}
124789
124790#define FTS4AUX_EQ_CONSTRAINT 1
124791#define FTS4AUX_GE_CONSTRAINT 2
124792#define FTS4AUX_LE_CONSTRAINT 4
124793
124794/*
124795** xBestIndex - Analyze a WHERE and ORDER BY clause.
124796*/
124797static int fts3auxBestIndexMethod(
124798  sqlite3_vtab *pVTab,
124799  sqlite3_index_info *pInfo
124800){
124801  int i;
124802  int iEq = -1;
124803  int iGe = -1;
124804  int iLe = -1;
124805
124806  UNUSED_PARAMETER(pVTab);
124807
124808  /* This vtab delivers always results in "ORDER BY term ASC" order. */
124809  if( pInfo->nOrderBy==1
124810   && pInfo->aOrderBy[0].iColumn==0
124811   && pInfo->aOrderBy[0].desc==0
124812  ){
124813    pInfo->orderByConsumed = 1;
124814  }
124815
124816  /* Search for equality and range constraints on the "term" column. */
124817  for(i=0; i<pInfo->nConstraint; i++){
124818    if( pInfo->aConstraint[i].usable && pInfo->aConstraint[i].iColumn==0 ){
124819      int op = pInfo->aConstraint[i].op;
124820      if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
124821      if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
124822      if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
124823      if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
124824      if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
124825    }
124826  }
124827
124828  if( iEq>=0 ){
124829    pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
124830    pInfo->aConstraintUsage[iEq].argvIndex = 1;
124831    pInfo->estimatedCost = 5;
124832  }else{
124833    pInfo->idxNum = 0;
124834    pInfo->estimatedCost = 20000;
124835    if( iGe>=0 ){
124836      pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
124837      pInfo->aConstraintUsage[iGe].argvIndex = 1;
124838      pInfo->estimatedCost /= 2;
124839    }
124840    if( iLe>=0 ){
124841      pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
124842      pInfo->aConstraintUsage[iLe].argvIndex = 1 + (iGe>=0);
124843      pInfo->estimatedCost /= 2;
124844    }
124845  }
124846
124847  return SQLITE_OK;
124848}
124849
124850/*
124851** xOpen - Open a cursor.
124852*/
124853static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
124854  Fts3auxCursor *pCsr;            /* Pointer to cursor object to return */
124855
124856  UNUSED_PARAMETER(pVTab);
124857
124858  pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
124859  if( !pCsr ) return SQLITE_NOMEM;
124860  memset(pCsr, 0, sizeof(Fts3auxCursor));
124861
124862  *ppCsr = (sqlite3_vtab_cursor *)pCsr;
124863  return SQLITE_OK;
124864}
124865
124866/*
124867** xClose - Close a cursor.
124868*/
124869static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
124870  Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
124871  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
124872
124873  sqlite3Fts3SegmentsClose(pFts3);
124874  sqlite3Fts3SegReaderFinish(&pCsr->csr);
124875  sqlite3_free((void *)pCsr->filter.zTerm);
124876  sqlite3_free(pCsr->zStop);
124877  sqlite3_free(pCsr->aStat);
124878  sqlite3_free(pCsr);
124879  return SQLITE_OK;
124880}
124881
124882static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
124883  if( nSize>pCsr->nStat ){
124884    struct Fts3auxColstats *aNew;
124885    aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat,
124886        sizeof(struct Fts3auxColstats) * nSize
124887    );
124888    if( aNew==0 ) return SQLITE_NOMEM;
124889    memset(&aNew[pCsr->nStat], 0,
124890        sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
124891    );
124892    pCsr->aStat = aNew;
124893    pCsr->nStat = nSize;
124894  }
124895  return SQLITE_OK;
124896}
124897
124898/*
124899** xNext - Advance the cursor to the next row, if any.
124900*/
124901static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
124902  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
124903  Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
124904  int rc;
124905
124906  /* Increment our pretend rowid value. */
124907  pCsr->iRowid++;
124908
124909  for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
124910    if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
124911  }
124912
124913  rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
124914  if( rc==SQLITE_ROW ){
124915    int i = 0;
124916    int nDoclist = pCsr->csr.nDoclist;
124917    char *aDoclist = pCsr->csr.aDoclist;
124918    int iCol;
124919
124920    int eState = 0;
124921
124922    if( pCsr->zStop ){
124923      int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
124924      int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
124925      if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
124926        pCsr->isEof = 1;
124927        return SQLITE_OK;
124928      }
124929    }
124930
124931    if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
124932    memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
124933    iCol = 0;
124934
124935    while( i<nDoclist ){
124936      sqlite3_int64 v = 0;
124937
124938      i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
124939      switch( eState ){
124940        /* State 0. In this state the integer just read was a docid. */
124941        case 0:
124942          pCsr->aStat[0].nDoc++;
124943          eState = 1;
124944          iCol = 0;
124945          break;
124946
124947        /* State 1. In this state we are expecting either a 1, indicating
124948        ** that the following integer will be a column number, or the
124949        ** start of a position list for column 0.
124950        **
124951        ** The only difference between state 1 and state 2 is that if the
124952        ** integer encountered in state 1 is not 0 or 1, then we need to
124953        ** increment the column 0 "nDoc" count for this term.
124954        */
124955        case 1:
124956          assert( iCol==0 );
124957          if( v>1 ){
124958            pCsr->aStat[1].nDoc++;
124959          }
124960          eState = 2;
124961          /* fall through */
124962
124963        case 2:
124964          if( v==0 ){       /* 0x00. Next integer will be a docid. */
124965            eState = 0;
124966          }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
124967            eState = 3;
124968          }else{            /* 2 or greater. A position. */
124969            pCsr->aStat[iCol+1].nOcc++;
124970            pCsr->aStat[0].nOcc++;
124971          }
124972          break;
124973
124974        /* State 3. The integer just read is a column number. */
124975        default: assert( eState==3 );
124976          iCol = (int)v;
124977          if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
124978          pCsr->aStat[iCol+1].nDoc++;
124979          eState = 2;
124980          break;
124981      }
124982    }
124983
124984    pCsr->iCol = 0;
124985    rc = SQLITE_OK;
124986  }else{
124987    pCsr->isEof = 1;
124988  }
124989  return rc;
124990}
124991
124992/*
124993** xFilter - Initialize a cursor to point at the start of its data.
124994*/
124995static int fts3auxFilterMethod(
124996  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
124997  int idxNum,                     /* Strategy index */
124998  const char *idxStr,             /* Unused */
124999  int nVal,                       /* Number of elements in apVal */
125000  sqlite3_value **apVal           /* Arguments for the indexing scheme */
125001){
125002  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
125003  Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
125004  int rc;
125005  int isScan;
125006
125007  UNUSED_PARAMETER(nVal);
125008  UNUSED_PARAMETER(idxStr);
125009
125010  assert( idxStr==0 );
125011  assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
125012       || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
125013       || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
125014  );
125015  isScan = (idxNum!=FTS4AUX_EQ_CONSTRAINT);
125016
125017  /* In case this cursor is being reused, close and zero it. */
125018  testcase(pCsr->filter.zTerm);
125019  sqlite3Fts3SegReaderFinish(&pCsr->csr);
125020  sqlite3_free((void *)pCsr->filter.zTerm);
125021  sqlite3_free(pCsr->aStat);
125022  memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
125023
125024  pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
125025  if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
125026
125027  if( idxNum&(FTS4AUX_EQ_CONSTRAINT|FTS4AUX_GE_CONSTRAINT) ){
125028    const unsigned char *zStr = sqlite3_value_text(apVal[0]);
125029    if( zStr ){
125030      pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
125031      pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
125032      if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
125033    }
125034  }
125035  if( idxNum&FTS4AUX_LE_CONSTRAINT ){
125036    int iIdx = (idxNum&FTS4AUX_GE_CONSTRAINT) ? 1 : 0;
125037    pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iIdx]));
125038    pCsr->nStop = sqlite3_value_bytes(apVal[iIdx]);
125039    if( pCsr->zStop==0 ) return SQLITE_NOMEM;
125040  }
125041
125042  rc = sqlite3Fts3SegReaderCursor(pFts3, 0, 0, FTS3_SEGCURSOR_ALL,
125043      pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
125044  );
125045  if( rc==SQLITE_OK ){
125046    rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
125047  }
125048
125049  if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
125050  return rc;
125051}
125052
125053/*
125054** xEof - Return true if the cursor is at EOF, or false otherwise.
125055*/
125056static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
125057  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
125058  return pCsr->isEof;
125059}
125060
125061/*
125062** xColumn - Return a column value.
125063*/
125064static int fts3auxColumnMethod(
125065  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
125066  sqlite3_context *pContext,      /* Context for sqlite3_result_xxx() calls */
125067  int iCol                        /* Index of column to read value from */
125068){
125069  Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
125070
125071  assert( p->isEof==0 );
125072  if( iCol==0 ){        /* Column "term" */
125073    sqlite3_result_text(pContext, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
125074  }else if( iCol==1 ){  /* Column "col" */
125075    if( p->iCol ){
125076      sqlite3_result_int(pContext, p->iCol-1);
125077    }else{
125078      sqlite3_result_text(pContext, "*", -1, SQLITE_STATIC);
125079    }
125080  }else if( iCol==2 ){  /* Column "documents" */
125081    sqlite3_result_int64(pContext, p->aStat[p->iCol].nDoc);
125082  }else{                /* Column "occurrences" */
125083    sqlite3_result_int64(pContext, p->aStat[p->iCol].nOcc);
125084  }
125085
125086  return SQLITE_OK;
125087}
125088
125089/*
125090** xRowid - Return the current rowid for the cursor.
125091*/
125092static int fts3auxRowidMethod(
125093  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
125094  sqlite_int64 *pRowid            /* OUT: Rowid value */
125095){
125096  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
125097  *pRowid = pCsr->iRowid;
125098  return SQLITE_OK;
125099}
125100
125101/*
125102** Register the fts3aux module with database connection db. Return SQLITE_OK
125103** if successful or an error code if sqlite3_create_module() fails.
125104*/
125105SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
125106  static const sqlite3_module fts3aux_module = {
125107     0,                           /* iVersion      */
125108     fts3auxConnectMethod,        /* xCreate       */
125109     fts3auxConnectMethod,        /* xConnect      */
125110     fts3auxBestIndexMethod,      /* xBestIndex    */
125111     fts3auxDisconnectMethod,     /* xDisconnect   */
125112     fts3auxDisconnectMethod,     /* xDestroy      */
125113     fts3auxOpenMethod,           /* xOpen         */
125114     fts3auxCloseMethod,          /* xClose        */
125115     fts3auxFilterMethod,         /* xFilter       */
125116     fts3auxNextMethod,           /* xNext         */
125117     fts3auxEofMethod,            /* xEof          */
125118     fts3auxColumnMethod,         /* xColumn       */
125119     fts3auxRowidMethod,          /* xRowid        */
125120     0,                           /* xUpdate       */
125121     0,                           /* xBegin        */
125122     0,                           /* xSync         */
125123     0,                           /* xCommit       */
125124     0,                           /* xRollback     */
125125     0,                           /* xFindFunction */
125126     0,                           /* xRename       */
125127     0,                           /* xSavepoint    */
125128     0,                           /* xRelease      */
125129     0                            /* xRollbackTo   */
125130  };
125131  int rc;                         /* Return code */
125132
125133  rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
125134  return rc;
125135}
125136
125137#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
125138
125139/************** End of fts3_aux.c ********************************************/
125140/************** Begin file fts3_expr.c ***************************************/
125141/*
125142** 2008 Nov 28
125143**
125144** The author disclaims copyright to this source code.  In place of
125145** a legal notice, here is a blessing:
125146**
125147**    May you do good and not evil.
125148**    May you find forgiveness for yourself and forgive others.
125149**    May you share freely, never taking more than you give.
125150**
125151******************************************************************************
125152**
125153** This module contains code that implements a parser for fts3 query strings
125154** (the right-hand argument to the MATCH operator). Because the supported
125155** syntax is relatively simple, the whole tokenizer/parser system is
125156** hand-coded.
125157*/
125158#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
125159
125160/*
125161** By default, this module parses the legacy syntax that has been
125162** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
125163** is defined, then it uses the new syntax. The differences between
125164** the new and the old syntaxes are:
125165**
125166**  a) The new syntax supports parenthesis. The old does not.
125167**
125168**  b) The new syntax supports the AND and NOT operators. The old does not.
125169**
125170**  c) The old syntax supports the "-" token qualifier. This is not
125171**     supported by the new syntax (it is replaced by the NOT operator).
125172**
125173**  d) When using the old syntax, the OR operator has a greater precedence
125174**     than an implicit AND. When using the new, both implicity and explicit
125175**     AND operators have a higher precedence than OR.
125176**
125177** If compiled with SQLITE_TEST defined, then this module exports the
125178** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
125179** to zero causes the module to use the old syntax. If it is set to
125180** non-zero the new syntax is activated. This is so both syntaxes can
125181** be tested using a single build of testfixture.
125182**
125183** The following describes the syntax supported by the fts3 MATCH
125184** operator in a similar format to that used by the lemon parser
125185** generator. This module does not use actually lemon, it uses a
125186** custom parser.
125187**
125188**   query ::= andexpr (OR andexpr)*.
125189**
125190**   andexpr ::= notexpr (AND? notexpr)*.
125191**
125192**   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
125193**   notexpr ::= LP query RP.
125194**
125195**   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
125196**
125197**   distance_opt ::= .
125198**   distance_opt ::= / INTEGER.
125199**
125200**   phrase ::= TOKEN.
125201**   phrase ::= COLUMN:TOKEN.
125202**   phrase ::= "TOKEN TOKEN TOKEN...".
125203*/
125204
125205#ifdef SQLITE_TEST
125206SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
125207#else
125208# ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
125209#  define sqlite3_fts3_enable_parentheses 1
125210# else
125211#  define sqlite3_fts3_enable_parentheses 0
125212# endif
125213#endif
125214
125215/*
125216** Default span for NEAR operators.
125217*/
125218#define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
125219
125220/* #include <string.h> */
125221/* #include <assert.h> */
125222
125223/*
125224** isNot:
125225**   This variable is used by function getNextNode(). When getNextNode() is
125226**   called, it sets ParseContext.isNot to true if the 'next node' is a
125227**   FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
125228**   FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
125229**   zero.
125230*/
125231typedef struct ParseContext ParseContext;
125232struct ParseContext {
125233  sqlite3_tokenizer *pTokenizer;      /* Tokenizer module */
125234  int iLangid;                        /* Language id used with tokenizer */
125235  const char **azCol;                 /* Array of column names for fts3 table */
125236  int bFts4;                          /* True to allow FTS4-only syntax */
125237  int nCol;                           /* Number of entries in azCol[] */
125238  int iDefaultCol;                    /* Default column to query */
125239  int isNot;                          /* True if getNextNode() sees a unary - */
125240  sqlite3_context *pCtx;              /* Write error message here */
125241  int nNest;                          /* Number of nested brackets */
125242};
125243
125244/*
125245** This function is equivalent to the standard isspace() function.
125246**
125247** The standard isspace() can be awkward to use safely, because although it
125248** is defined to accept an argument of type int, its behavior when passed
125249** an integer that falls outside of the range of the unsigned char type
125250** is undefined (and sometimes, "undefined" means segfault). This wrapper
125251** is defined to accept an argument of type char, and always returns 0 for
125252** any values that fall outside of the range of the unsigned char type (i.e.
125253** negative values).
125254*/
125255static int fts3isspace(char c){
125256  return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
125257}
125258
125259/*
125260** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
125261** zero the memory before returning a pointer to it. If unsuccessful,
125262** return NULL.
125263*/
125264static void *fts3MallocZero(int nByte){
125265  void *pRet = sqlite3_malloc(nByte);
125266  if( pRet ) memset(pRet, 0, nByte);
125267  return pRet;
125268}
125269
125270SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
125271  sqlite3_tokenizer *pTokenizer,
125272  int iLangid,
125273  const char *z,
125274  int n,
125275  sqlite3_tokenizer_cursor **ppCsr
125276){
125277  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
125278  sqlite3_tokenizer_cursor *pCsr = 0;
125279  int rc;
125280
125281  rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
125282  assert( rc==SQLITE_OK || pCsr==0 );
125283  if( rc==SQLITE_OK ){
125284    pCsr->pTokenizer = pTokenizer;
125285    if( pModule->iVersion>=1 ){
125286      rc = pModule->xLanguageid(pCsr, iLangid);
125287      if( rc!=SQLITE_OK ){
125288        pModule->xClose(pCsr);
125289        pCsr = 0;
125290      }
125291    }
125292  }
125293  *ppCsr = pCsr;
125294  return rc;
125295}
125296
125297
125298/*
125299** Extract the next token from buffer z (length n) using the tokenizer
125300** and other information (column names etc.) in pParse. Create an Fts3Expr
125301** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
125302** single token and set *ppExpr to point to it. If the end of the buffer is
125303** reached before a token is found, set *ppExpr to zero. It is the
125304** responsibility of the caller to eventually deallocate the allocated
125305** Fts3Expr structure (if any) by passing it to sqlite3_free().
125306**
125307** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
125308** fails.
125309*/
125310static int getNextToken(
125311  ParseContext *pParse,                   /* fts3 query parse context */
125312  int iCol,                               /* Value for Fts3Phrase.iColumn */
125313  const char *z, int n,                   /* Input string */
125314  Fts3Expr **ppExpr,                      /* OUT: expression */
125315  int *pnConsumed                         /* OUT: Number of bytes consumed */
125316){
125317  sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
125318  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
125319  int rc;
125320  sqlite3_tokenizer_cursor *pCursor;
125321  Fts3Expr *pRet = 0;
125322  int nConsumed = 0;
125323
125324  rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, n, &pCursor);
125325  if( rc==SQLITE_OK ){
125326    const char *zToken;
125327    int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
125328    int nByte;                               /* total space to allocate */
125329
125330    rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
125331    if( rc==SQLITE_OK ){
125332      nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
125333      pRet = (Fts3Expr *)fts3MallocZero(nByte);
125334      if( !pRet ){
125335        rc = SQLITE_NOMEM;
125336      }else{
125337        pRet->eType = FTSQUERY_PHRASE;
125338        pRet->pPhrase = (Fts3Phrase *)&pRet[1];
125339        pRet->pPhrase->nToken = 1;
125340        pRet->pPhrase->iColumn = iCol;
125341        pRet->pPhrase->aToken[0].n = nToken;
125342        pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
125343        memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
125344
125345        if( iEnd<n && z[iEnd]=='*' ){
125346          pRet->pPhrase->aToken[0].isPrefix = 1;
125347          iEnd++;
125348        }
125349
125350        while( 1 ){
125351          if( !sqlite3_fts3_enable_parentheses
125352           && iStart>0 && z[iStart-1]=='-'
125353          ){
125354            pParse->isNot = 1;
125355            iStart--;
125356          }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
125357            pRet->pPhrase->aToken[0].bFirst = 1;
125358            iStart--;
125359          }else{
125360            break;
125361          }
125362        }
125363
125364      }
125365      nConsumed = iEnd;
125366    }
125367
125368    pModule->xClose(pCursor);
125369  }
125370
125371  *pnConsumed = nConsumed;
125372  *ppExpr = pRet;
125373  return rc;
125374}
125375
125376
125377/*
125378** Enlarge a memory allocation.  If an out-of-memory allocation occurs,
125379** then free the old allocation.
125380*/
125381static void *fts3ReallocOrFree(void *pOrig, int nNew){
125382  void *pRet = sqlite3_realloc(pOrig, nNew);
125383  if( !pRet ){
125384    sqlite3_free(pOrig);
125385  }
125386  return pRet;
125387}
125388
125389/*
125390** Buffer zInput, length nInput, contains the contents of a quoted string
125391** that appeared as part of an fts3 query expression. Neither quote character
125392** is included in the buffer. This function attempts to tokenize the entire
125393** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
125394** containing the results.
125395**
125396** If successful, SQLITE_OK is returned and *ppExpr set to point at the
125397** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
125398** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
125399** to 0.
125400*/
125401static int getNextString(
125402  ParseContext *pParse,                   /* fts3 query parse context */
125403  const char *zInput, int nInput,         /* Input string */
125404  Fts3Expr **ppExpr                       /* OUT: expression */
125405){
125406  sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
125407  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
125408  int rc;
125409  Fts3Expr *p = 0;
125410  sqlite3_tokenizer_cursor *pCursor = 0;
125411  char *zTemp = 0;
125412  int nTemp = 0;
125413
125414  const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
125415  int nToken = 0;
125416
125417  /* The final Fts3Expr data structure, including the Fts3Phrase,
125418  ** Fts3PhraseToken structures token buffers are all stored as a single
125419  ** allocation so that the expression can be freed with a single call to
125420  ** sqlite3_free(). Setting this up requires a two pass approach.
125421  **
125422  ** The first pass, in the block below, uses a tokenizer cursor to iterate
125423  ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
125424  ** to assemble data in two dynamic buffers:
125425  **
125426  **   Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
125427  **             structure, followed by the array of Fts3PhraseToken
125428  **             structures. This pass only populates the Fts3PhraseToken array.
125429  **
125430  **   Buffer zTemp: Contains copies of all tokens.
125431  **
125432  ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
125433  ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
125434  ** structures.
125435  */
125436  rc = sqlite3Fts3OpenTokenizer(
125437      pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
125438  if( rc==SQLITE_OK ){
125439    int ii;
125440    for(ii=0; rc==SQLITE_OK; ii++){
125441      const char *zByte;
125442      int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
125443      rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
125444      if( rc==SQLITE_OK ){
125445        Fts3PhraseToken *pToken;
125446
125447        p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
125448        if( !p ) goto no_mem;
125449
125450        zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
125451        if( !zTemp ) goto no_mem;
125452
125453        assert( nToken==ii );
125454        pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
125455        memset(pToken, 0, sizeof(Fts3PhraseToken));
125456
125457        memcpy(&zTemp[nTemp], zByte, nByte);
125458        nTemp += nByte;
125459
125460        pToken->n = nByte;
125461        pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
125462        pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
125463        nToken = ii+1;
125464      }
125465    }
125466
125467    pModule->xClose(pCursor);
125468    pCursor = 0;
125469  }
125470
125471  if( rc==SQLITE_DONE ){
125472    int jj;
125473    char *zBuf = 0;
125474
125475    p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
125476    if( !p ) goto no_mem;
125477    memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
125478    p->eType = FTSQUERY_PHRASE;
125479    p->pPhrase = (Fts3Phrase *)&p[1];
125480    p->pPhrase->iColumn = pParse->iDefaultCol;
125481    p->pPhrase->nToken = nToken;
125482
125483    zBuf = (char *)&p->pPhrase->aToken[nToken];
125484    if( zTemp ){
125485      memcpy(zBuf, zTemp, nTemp);
125486      sqlite3_free(zTemp);
125487    }else{
125488      assert( nTemp==0 );
125489    }
125490
125491    for(jj=0; jj<p->pPhrase->nToken; jj++){
125492      p->pPhrase->aToken[jj].z = zBuf;
125493      zBuf += p->pPhrase->aToken[jj].n;
125494    }
125495    rc = SQLITE_OK;
125496  }
125497
125498  *ppExpr = p;
125499  return rc;
125500no_mem:
125501
125502  if( pCursor ){
125503    pModule->xClose(pCursor);
125504  }
125505  sqlite3_free(zTemp);
125506  sqlite3_free(p);
125507  *ppExpr = 0;
125508  return SQLITE_NOMEM;
125509}
125510
125511/*
125512** Function getNextNode(), which is called by fts3ExprParse(), may itself
125513** call fts3ExprParse(). So this forward declaration is required.
125514*/
125515static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
125516
125517/*
125518** The output variable *ppExpr is populated with an allocated Fts3Expr
125519** structure, or set to 0 if the end of the input buffer is reached.
125520**
125521** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
125522** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
125523** If SQLITE_ERROR is returned, pContext is populated with an error message.
125524*/
125525static int getNextNode(
125526  ParseContext *pParse,                   /* fts3 query parse context */
125527  const char *z, int n,                   /* Input string */
125528  Fts3Expr **ppExpr,                      /* OUT: expression */
125529  int *pnConsumed                         /* OUT: Number of bytes consumed */
125530){
125531  static const struct Fts3Keyword {
125532    char *z;                              /* Keyword text */
125533    unsigned char n;                      /* Length of the keyword */
125534    unsigned char parenOnly;              /* Only valid in paren mode */
125535    unsigned char eType;                  /* Keyword code */
125536  } aKeyword[] = {
125537    { "OR" ,  2, 0, FTSQUERY_OR   },
125538    { "AND",  3, 1, FTSQUERY_AND  },
125539    { "NOT",  3, 1, FTSQUERY_NOT  },
125540    { "NEAR", 4, 0, FTSQUERY_NEAR }
125541  };
125542  int ii;
125543  int iCol;
125544  int iColLen;
125545  int rc;
125546  Fts3Expr *pRet = 0;
125547
125548  const char *zInput = z;
125549  int nInput = n;
125550
125551  pParse->isNot = 0;
125552
125553  /* Skip over any whitespace before checking for a keyword, an open or
125554  ** close bracket, or a quoted string.
125555  */
125556  while( nInput>0 && fts3isspace(*zInput) ){
125557    nInput--;
125558    zInput++;
125559  }
125560  if( nInput==0 ){
125561    return SQLITE_DONE;
125562  }
125563
125564  /* See if we are dealing with a keyword. */
125565  for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
125566    const struct Fts3Keyword *pKey = &aKeyword[ii];
125567
125568    if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
125569      continue;
125570    }
125571
125572    if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
125573      int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
125574      int nKey = pKey->n;
125575      char cNext;
125576
125577      /* If this is a "NEAR" keyword, check for an explicit nearness. */
125578      if( pKey->eType==FTSQUERY_NEAR ){
125579        assert( nKey==4 );
125580        if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
125581          nNear = 0;
125582          for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
125583            nNear = nNear * 10 + (zInput[nKey] - '0');
125584          }
125585        }
125586      }
125587
125588      /* At this point this is probably a keyword. But for that to be true,
125589      ** the next byte must contain either whitespace, an open or close
125590      ** parenthesis, a quote character, or EOF.
125591      */
125592      cNext = zInput[nKey];
125593      if( fts3isspace(cNext)
125594       || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
125595      ){
125596        pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
125597        if( !pRet ){
125598          return SQLITE_NOMEM;
125599        }
125600        pRet->eType = pKey->eType;
125601        pRet->nNear = nNear;
125602        *ppExpr = pRet;
125603        *pnConsumed = (int)((zInput - z) + nKey);
125604        return SQLITE_OK;
125605      }
125606
125607      /* Turns out that wasn't a keyword after all. This happens if the
125608      ** user has supplied a token such as "ORacle". Continue.
125609      */
125610    }
125611  }
125612
125613  /* Check for an open bracket. */
125614  if( sqlite3_fts3_enable_parentheses ){
125615    if( *zInput=='(' ){
125616      int nConsumed;
125617      pParse->nNest++;
125618      rc = fts3ExprParse(pParse, &zInput[1], nInput-1, ppExpr, &nConsumed);
125619      if( rc==SQLITE_OK && !*ppExpr ){
125620        rc = SQLITE_DONE;
125621      }
125622      *pnConsumed = (int)((zInput - z) + 1 + nConsumed);
125623      return rc;
125624    }
125625
125626    /* Check for a close bracket. */
125627    if( *zInput==')' ){
125628      pParse->nNest--;
125629      *pnConsumed = (int)((zInput - z) + 1);
125630      return SQLITE_DONE;
125631    }
125632  }
125633
125634  /* See if we are dealing with a quoted phrase. If this is the case, then
125635  ** search for the closing quote and pass the whole string to getNextString()
125636  ** for processing. This is easy to do, as fts3 has no syntax for escaping
125637  ** a quote character embedded in a string.
125638  */
125639  if( *zInput=='"' ){
125640    for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
125641    *pnConsumed = (int)((zInput - z) + ii + 1);
125642    if( ii==nInput ){
125643      return SQLITE_ERROR;
125644    }
125645    return getNextString(pParse, &zInput[1], ii-1, ppExpr);
125646  }
125647
125648
125649  /* If control flows to this point, this must be a regular token, or
125650  ** the end of the input. Read a regular token using the sqlite3_tokenizer
125651  ** interface. Before doing so, figure out if there is an explicit
125652  ** column specifier for the token.
125653  **
125654  ** TODO: Strangely, it is not possible to associate a column specifier
125655  ** with a quoted phrase, only with a single token. Not sure if this was
125656  ** an implementation artifact or an intentional decision when fts3 was
125657  ** first implemented. Whichever it was, this module duplicates the
125658  ** limitation.
125659  */
125660  iCol = pParse->iDefaultCol;
125661  iColLen = 0;
125662  for(ii=0; ii<pParse->nCol; ii++){
125663    const char *zStr = pParse->azCol[ii];
125664    int nStr = (int)strlen(zStr);
125665    if( nInput>nStr && zInput[nStr]==':'
125666     && sqlite3_strnicmp(zStr, zInput, nStr)==0
125667    ){
125668      iCol = ii;
125669      iColLen = (int)((zInput - z) + nStr + 1);
125670      break;
125671    }
125672  }
125673  rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
125674  *pnConsumed += iColLen;
125675  return rc;
125676}
125677
125678/*
125679** The argument is an Fts3Expr structure for a binary operator (any type
125680** except an FTSQUERY_PHRASE). Return an integer value representing the
125681** precedence of the operator. Lower values have a higher precedence (i.e.
125682** group more tightly). For example, in the C language, the == operator
125683** groups more tightly than ||, and would therefore have a higher precedence.
125684**
125685** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
125686** is defined), the order of the operators in precedence from highest to
125687** lowest is:
125688**
125689**   NEAR
125690**   NOT
125691**   AND (including implicit ANDs)
125692**   OR
125693**
125694** Note that when using the old query syntax, the OR operator has a higher
125695** precedence than the AND operator.
125696*/
125697static int opPrecedence(Fts3Expr *p){
125698  assert( p->eType!=FTSQUERY_PHRASE );
125699  if( sqlite3_fts3_enable_parentheses ){
125700    return p->eType;
125701  }else if( p->eType==FTSQUERY_NEAR ){
125702    return 1;
125703  }else if( p->eType==FTSQUERY_OR ){
125704    return 2;
125705  }
125706  assert( p->eType==FTSQUERY_AND );
125707  return 3;
125708}
125709
125710/*
125711** Argument ppHead contains a pointer to the current head of a query
125712** expression tree being parsed. pPrev is the expression node most recently
125713** inserted into the tree. This function adds pNew, which is always a binary
125714** operator node, into the expression tree based on the relative precedence
125715** of pNew and the existing nodes of the tree. This may result in the head
125716** of the tree changing, in which case *ppHead is set to the new root node.
125717*/
125718static void insertBinaryOperator(
125719  Fts3Expr **ppHead,       /* Pointer to the root node of a tree */
125720  Fts3Expr *pPrev,         /* Node most recently inserted into the tree */
125721  Fts3Expr *pNew           /* New binary node to insert into expression tree */
125722){
125723  Fts3Expr *pSplit = pPrev;
125724  while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
125725    pSplit = pSplit->pParent;
125726  }
125727
125728  if( pSplit->pParent ){
125729    assert( pSplit->pParent->pRight==pSplit );
125730    pSplit->pParent->pRight = pNew;
125731    pNew->pParent = pSplit->pParent;
125732  }else{
125733    *ppHead = pNew;
125734  }
125735  pNew->pLeft = pSplit;
125736  pSplit->pParent = pNew;
125737}
125738
125739/*
125740** Parse the fts3 query expression found in buffer z, length n. This function
125741** returns either when the end of the buffer is reached or an unmatched
125742** closing bracket - ')' - is encountered.
125743**
125744** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
125745** parsed form of the expression and *pnConsumed is set to the number of
125746** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
125747** (out of memory error) or SQLITE_ERROR (parse error) is returned.
125748*/
125749static int fts3ExprParse(
125750  ParseContext *pParse,                   /* fts3 query parse context */
125751  const char *z, int n,                   /* Text of MATCH query */
125752  Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */
125753  int *pnConsumed                         /* OUT: Number of bytes consumed */
125754){
125755  Fts3Expr *pRet = 0;
125756  Fts3Expr *pPrev = 0;
125757  Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */
125758  int nIn = n;
125759  const char *zIn = z;
125760  int rc = SQLITE_OK;
125761  int isRequirePhrase = 1;
125762
125763  while( rc==SQLITE_OK ){
125764    Fts3Expr *p = 0;
125765    int nByte = 0;
125766    rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
125767    if( rc==SQLITE_OK ){
125768      int isPhrase;
125769
125770      if( !sqlite3_fts3_enable_parentheses
125771       && p->eType==FTSQUERY_PHRASE && pParse->isNot
125772      ){
125773        /* Create an implicit NOT operator. */
125774        Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
125775        if( !pNot ){
125776          sqlite3Fts3ExprFree(p);
125777          rc = SQLITE_NOMEM;
125778          goto exprparse_out;
125779        }
125780        pNot->eType = FTSQUERY_NOT;
125781        pNot->pRight = p;
125782        p->pParent = pNot;
125783        if( pNotBranch ){
125784          pNot->pLeft = pNotBranch;
125785          pNotBranch->pParent = pNot;
125786        }
125787        pNotBranch = pNot;
125788        p = pPrev;
125789      }else{
125790        int eType = p->eType;
125791        isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
125792
125793        /* The isRequirePhrase variable is set to true if a phrase or
125794        ** an expression contained in parenthesis is required. If a
125795        ** binary operator (AND, OR, NOT or NEAR) is encounted when
125796        ** isRequirePhrase is set, this is a syntax error.
125797        */
125798        if( !isPhrase && isRequirePhrase ){
125799          sqlite3Fts3ExprFree(p);
125800          rc = SQLITE_ERROR;
125801          goto exprparse_out;
125802        }
125803
125804        if( isPhrase && !isRequirePhrase ){
125805          /* Insert an implicit AND operator. */
125806          Fts3Expr *pAnd;
125807          assert( pRet && pPrev );
125808          pAnd = fts3MallocZero(sizeof(Fts3Expr));
125809          if( !pAnd ){
125810            sqlite3Fts3ExprFree(p);
125811            rc = SQLITE_NOMEM;
125812            goto exprparse_out;
125813          }
125814          pAnd->eType = FTSQUERY_AND;
125815          insertBinaryOperator(&pRet, pPrev, pAnd);
125816          pPrev = pAnd;
125817        }
125818
125819        /* This test catches attempts to make either operand of a NEAR
125820        ** operator something other than a phrase. For example, either of
125821        ** the following:
125822        **
125823        **    (bracketed expression) NEAR phrase
125824        **    phrase NEAR (bracketed expression)
125825        **
125826        ** Return an error in either case.
125827        */
125828        if( pPrev && (
125829            (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
125830         || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
125831        )){
125832          sqlite3Fts3ExprFree(p);
125833          rc = SQLITE_ERROR;
125834          goto exprparse_out;
125835        }
125836
125837        if( isPhrase ){
125838          if( pRet ){
125839            assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
125840            pPrev->pRight = p;
125841            p->pParent = pPrev;
125842          }else{
125843            pRet = p;
125844          }
125845        }else{
125846          insertBinaryOperator(&pRet, pPrev, p);
125847        }
125848        isRequirePhrase = !isPhrase;
125849      }
125850      assert( nByte>0 );
125851    }
125852    assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
125853    nIn -= nByte;
125854    zIn += nByte;
125855    pPrev = p;
125856  }
125857
125858  if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
125859    rc = SQLITE_ERROR;
125860  }
125861
125862  if( rc==SQLITE_DONE ){
125863    rc = SQLITE_OK;
125864    if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
125865      if( !pRet ){
125866        rc = SQLITE_ERROR;
125867      }else{
125868        Fts3Expr *pIter = pNotBranch;
125869        while( pIter->pLeft ){
125870          pIter = pIter->pLeft;
125871        }
125872        pIter->pLeft = pRet;
125873        pRet->pParent = pIter;
125874        pRet = pNotBranch;
125875      }
125876    }
125877  }
125878  *pnConsumed = n - nIn;
125879
125880exprparse_out:
125881  if( rc!=SQLITE_OK ){
125882    sqlite3Fts3ExprFree(pRet);
125883    sqlite3Fts3ExprFree(pNotBranch);
125884    pRet = 0;
125885  }
125886  *ppExpr = pRet;
125887  return rc;
125888}
125889
125890/*
125891** Return SQLITE_ERROR if the maximum depth of the expression tree passed
125892** as the only argument is more than nMaxDepth.
125893*/
125894static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){
125895  int rc = SQLITE_OK;
125896  if( p ){
125897    if( nMaxDepth<0 ){
125898      rc = SQLITE_TOOBIG;
125899    }else{
125900      rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1);
125901      if( rc==SQLITE_OK ){
125902        rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1);
125903      }
125904    }
125905  }
125906  return rc;
125907}
125908
125909/*
125910** This function attempts to transform the expression tree at (*pp) to
125911** an equivalent but more balanced form. The tree is modified in place.
125912** If successful, SQLITE_OK is returned and (*pp) set to point to the
125913** new root expression node.
125914**
125915** nMaxDepth is the maximum allowable depth of the balanced sub-tree.
125916**
125917** Otherwise, if an error occurs, an SQLite error code is returned and
125918** expression (*pp) freed.
125919*/
125920static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
125921  int rc = SQLITE_OK;             /* Return code */
125922  Fts3Expr *pRoot = *pp;          /* Initial root node */
125923  Fts3Expr *pFree = 0;            /* List of free nodes. Linked by pParent. */
125924  int eType = pRoot->eType;       /* Type of node in this tree */
125925
125926  if( nMaxDepth==0 ){
125927    rc = SQLITE_ERROR;
125928  }
125929
125930  if( rc==SQLITE_OK && (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){
125931    Fts3Expr **apLeaf;
125932    apLeaf = (Fts3Expr **)sqlite3_malloc(sizeof(Fts3Expr *) * nMaxDepth);
125933    if( 0==apLeaf ){
125934      rc = SQLITE_NOMEM;
125935    }else{
125936      memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth);
125937    }
125938
125939    if( rc==SQLITE_OK ){
125940      int i;
125941      Fts3Expr *p;
125942
125943      /* Set $p to point to the left-most leaf in the tree of eType nodes. */
125944      for(p=pRoot; p->eType==eType; p=p->pLeft){
125945        assert( p->pParent==0 || p->pParent->pLeft==p );
125946        assert( p->pLeft && p->pRight );
125947      }
125948
125949      /* This loop runs once for each leaf in the tree of eType nodes. */
125950      while( 1 ){
125951        int iLvl;
125952        Fts3Expr *pParent = p->pParent;     /* Current parent of p */
125953
125954        assert( pParent==0 || pParent->pLeft==p );
125955        p->pParent = 0;
125956        if( pParent ){
125957          pParent->pLeft = 0;
125958        }else{
125959          pRoot = 0;
125960        }
125961        rc = fts3ExprBalance(&p, nMaxDepth-1);
125962        if( rc!=SQLITE_OK ) break;
125963
125964        for(iLvl=0; p && iLvl<nMaxDepth; iLvl++){
125965          if( apLeaf[iLvl]==0 ){
125966            apLeaf[iLvl] = p;
125967            p = 0;
125968          }else{
125969            assert( pFree );
125970            pFree->pLeft = apLeaf[iLvl];
125971            pFree->pRight = p;
125972            pFree->pLeft->pParent = pFree;
125973            pFree->pRight->pParent = pFree;
125974
125975            p = pFree;
125976            pFree = pFree->pParent;
125977            p->pParent = 0;
125978            apLeaf[iLvl] = 0;
125979          }
125980        }
125981        if( p ){
125982          sqlite3Fts3ExprFree(p);
125983          rc = SQLITE_TOOBIG;
125984          break;
125985        }
125986
125987        /* If that was the last leaf node, break out of the loop */
125988        if( pParent==0 ) break;
125989
125990        /* Set $p to point to the next leaf in the tree of eType nodes */
125991        for(p=pParent->pRight; p->eType==eType; p=p->pLeft);
125992
125993        /* Remove pParent from the original tree. */
125994        assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent );
125995        pParent->pRight->pParent = pParent->pParent;
125996        if( pParent->pParent ){
125997          pParent->pParent->pLeft = pParent->pRight;
125998        }else{
125999          assert( pParent==pRoot );
126000          pRoot = pParent->pRight;
126001        }
126002
126003        /* Link pParent into the free node list. It will be used as an
126004        ** internal node of the new tree.  */
126005        pParent->pParent = pFree;
126006        pFree = pParent;
126007      }
126008
126009      if( rc==SQLITE_OK ){
126010        p = 0;
126011        for(i=0; i<nMaxDepth; i++){
126012          if( apLeaf[i] ){
126013            if( p==0 ){
126014              p = apLeaf[i];
126015              p->pParent = 0;
126016            }else{
126017              assert( pFree!=0 );
126018              pFree->pRight = p;
126019              pFree->pLeft = apLeaf[i];
126020              pFree->pLeft->pParent = pFree;
126021              pFree->pRight->pParent = pFree;
126022
126023              p = pFree;
126024              pFree = pFree->pParent;
126025              p->pParent = 0;
126026            }
126027          }
126028        }
126029        pRoot = p;
126030      }else{
126031        /* An error occurred. Delete the contents of the apLeaf[] array
126032        ** and pFree list. Everything else is cleaned up by the call to
126033        ** sqlite3Fts3ExprFree(pRoot) below.  */
126034        Fts3Expr *pDel;
126035        for(i=0; i<nMaxDepth; i++){
126036          sqlite3Fts3ExprFree(apLeaf[i]);
126037        }
126038        while( (pDel=pFree)!=0 ){
126039          pFree = pDel->pParent;
126040          sqlite3_free(pDel);
126041        }
126042      }
126043
126044      assert( pFree==0 );
126045      sqlite3_free( apLeaf );
126046    }
126047  }
126048
126049  if( rc!=SQLITE_OK ){
126050    sqlite3Fts3ExprFree(pRoot);
126051    pRoot = 0;
126052  }
126053  *pp = pRoot;
126054  return rc;
126055}
126056
126057/*
126058** This function is similar to sqlite3Fts3ExprParse(), with the following
126059** differences:
126060**
126061**   1. It does not do expression rebalancing.
126062**   2. It does not check that the expression does not exceed the
126063**      maximum allowable depth.
126064**   3. Even if it fails, *ppExpr may still be set to point to an
126065**      expression tree. It should be deleted using sqlite3Fts3ExprFree()
126066**      in this case.
126067*/
126068static int fts3ExprParseUnbalanced(
126069  sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
126070  int iLangid,                        /* Language id for tokenizer */
126071  char **azCol,                       /* Array of column names for fts3 table */
126072  int bFts4,                          /* True to allow FTS4-only syntax */
126073  int nCol,                           /* Number of entries in azCol[] */
126074  int iDefaultCol,                    /* Default column to query */
126075  const char *z, int n,               /* Text of MATCH query */
126076  Fts3Expr **ppExpr                   /* OUT: Parsed query structure */
126077){
126078  int nParsed;
126079  int rc;
126080  ParseContext sParse;
126081
126082  memset(&sParse, 0, sizeof(ParseContext));
126083  sParse.pTokenizer = pTokenizer;
126084  sParse.iLangid = iLangid;
126085  sParse.azCol = (const char **)azCol;
126086  sParse.nCol = nCol;
126087  sParse.iDefaultCol = iDefaultCol;
126088  sParse.bFts4 = bFts4;
126089  if( z==0 ){
126090    *ppExpr = 0;
126091    return SQLITE_OK;
126092  }
126093  if( n<0 ){
126094    n = (int)strlen(z);
126095  }
126096  rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
126097  assert( rc==SQLITE_OK || *ppExpr==0 );
126098
126099  /* Check for mismatched parenthesis */
126100  if( rc==SQLITE_OK && sParse.nNest ){
126101    rc = SQLITE_ERROR;
126102  }
126103
126104  return rc;
126105}
126106
126107/*
126108** Parameters z and n contain a pointer to and length of a buffer containing
126109** an fts3 query expression, respectively. This function attempts to parse the
126110** query expression and create a tree of Fts3Expr structures representing the
126111** parsed expression. If successful, *ppExpr is set to point to the head
126112** of the parsed expression tree and SQLITE_OK is returned. If an error
126113** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
126114** error) is returned and *ppExpr is set to 0.
126115**
126116** If parameter n is a negative number, then z is assumed to point to a
126117** nul-terminated string and the length is determined using strlen().
126118**
126119** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
126120** use to normalize query tokens while parsing the expression. The azCol[]
126121** array, which is assumed to contain nCol entries, should contain the names
126122** of each column in the target fts3 table, in order from left to right.
126123** Column names must be nul-terminated strings.
126124**
126125** The iDefaultCol parameter should be passed the index of the table column
126126** that appears on the left-hand-side of the MATCH operator (the default
126127** column to match against for tokens for which a column name is not explicitly
126128** specified as part of the query string), or -1 if tokens may by default
126129** match any table column.
126130*/
126131SQLITE_PRIVATE int sqlite3Fts3ExprParse(
126132  sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
126133  int iLangid,                        /* Language id for tokenizer */
126134  char **azCol,                       /* Array of column names for fts3 table */
126135  int bFts4,                          /* True to allow FTS4-only syntax */
126136  int nCol,                           /* Number of entries in azCol[] */
126137  int iDefaultCol,                    /* Default column to query */
126138  const char *z, int n,               /* Text of MATCH query */
126139  Fts3Expr **ppExpr,                  /* OUT: Parsed query structure */
126140  char **pzErr                        /* OUT: Error message (sqlite3_malloc) */
126141){
126142  static const int MAX_EXPR_DEPTH = 12;
126143  int rc = fts3ExprParseUnbalanced(
126144      pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
126145  );
126146
126147  /* Rebalance the expression. And check that its depth does not exceed
126148  ** MAX_EXPR_DEPTH.  */
126149  if( rc==SQLITE_OK && *ppExpr ){
126150    rc = fts3ExprBalance(ppExpr, MAX_EXPR_DEPTH);
126151    if( rc==SQLITE_OK ){
126152      rc = fts3ExprCheckDepth(*ppExpr, MAX_EXPR_DEPTH);
126153    }
126154  }
126155
126156  if( rc!=SQLITE_OK ){
126157    sqlite3Fts3ExprFree(*ppExpr);
126158    *ppExpr = 0;
126159    if( rc==SQLITE_TOOBIG ){
126160      *pzErr = sqlite3_mprintf(
126161          "FTS expression tree is too large (maximum depth %d)", MAX_EXPR_DEPTH
126162      );
126163      rc = SQLITE_ERROR;
126164    }else if( rc==SQLITE_ERROR ){
126165      *pzErr = sqlite3_mprintf("malformed MATCH expression: [%s]", z);
126166    }
126167  }
126168
126169  return rc;
126170}
126171
126172/*
126173** Free a single node of an expression tree.
126174*/
126175static void fts3FreeExprNode(Fts3Expr *p){
126176  assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
126177  sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
126178  sqlite3_free(p->aMI);
126179  sqlite3_free(p);
126180}
126181
126182/*
126183** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
126184**
126185** This function would be simpler if it recursively called itself. But
126186** that would mean passing a sufficiently large expression to ExprParse()
126187** could cause a stack overflow.
126188*/
126189SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){
126190  Fts3Expr *p;
126191  assert( pDel==0 || pDel->pParent==0 );
126192  for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){
126193    assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft );
126194  }
126195  while( p ){
126196    Fts3Expr *pParent = p->pParent;
126197    fts3FreeExprNode(p);
126198    if( pParent && p==pParent->pLeft && pParent->pRight ){
126199      p = pParent->pRight;
126200      while( p && (p->pLeft || p->pRight) ){
126201        assert( p==p->pParent->pRight || p==p->pParent->pLeft );
126202        p = (p->pLeft ? p->pLeft : p->pRight);
126203      }
126204    }else{
126205      p = pParent;
126206    }
126207  }
126208}
126209
126210/****************************************************************************
126211*****************************************************************************
126212** Everything after this point is just test code.
126213*/
126214
126215#ifdef SQLITE_TEST
126216
126217/* #include <stdio.h> */
126218
126219/*
126220** Function to query the hash-table of tokenizers (see README.tokenizers).
126221*/
126222static int queryTestTokenizer(
126223  sqlite3 *db,
126224  const char *zName,
126225  const sqlite3_tokenizer_module **pp
126226){
126227  int rc;
126228  sqlite3_stmt *pStmt;
126229  const char zSql[] = "SELECT fts3_tokenizer(?)";
126230
126231  *pp = 0;
126232  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
126233  if( rc!=SQLITE_OK ){
126234    return rc;
126235  }
126236
126237  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
126238  if( SQLITE_ROW==sqlite3_step(pStmt) ){
126239    if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
126240      memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
126241    }
126242  }
126243
126244  return sqlite3_finalize(pStmt);
126245}
126246
126247/*
126248** Return a pointer to a buffer containing a text representation of the
126249** expression passed as the first argument. The buffer is obtained from
126250** sqlite3_malloc(). It is the responsibility of the caller to use
126251** sqlite3_free() to release the memory. If an OOM condition is encountered,
126252** NULL is returned.
126253**
126254** If the second argument is not NULL, then its contents are prepended to
126255** the returned expression text and then freed using sqlite3_free().
126256*/
126257static char *exprToString(Fts3Expr *pExpr, char *zBuf){
126258  if( pExpr==0 ){
126259    return sqlite3_mprintf("");
126260  }
126261  switch( pExpr->eType ){
126262    case FTSQUERY_PHRASE: {
126263      Fts3Phrase *pPhrase = pExpr->pPhrase;
126264      int i;
126265      zBuf = sqlite3_mprintf(
126266          "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
126267      for(i=0; zBuf && i<pPhrase->nToken; i++){
126268        zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
126269            pPhrase->aToken[i].n, pPhrase->aToken[i].z,
126270            (pPhrase->aToken[i].isPrefix?"+":"")
126271        );
126272      }
126273      return zBuf;
126274    }
126275
126276    case FTSQUERY_NEAR:
126277      zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
126278      break;
126279    case FTSQUERY_NOT:
126280      zBuf = sqlite3_mprintf("%zNOT ", zBuf);
126281      break;
126282    case FTSQUERY_AND:
126283      zBuf = sqlite3_mprintf("%zAND ", zBuf);
126284      break;
126285    case FTSQUERY_OR:
126286      zBuf = sqlite3_mprintf("%zOR ", zBuf);
126287      break;
126288  }
126289
126290  if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
126291  if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
126292  if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
126293
126294  if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
126295  if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
126296
126297  return zBuf;
126298}
126299
126300/*
126301** This is the implementation of a scalar SQL function used to test the
126302** expression parser. It should be called as follows:
126303**
126304**   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
126305**
126306** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
126307** to parse the query expression (see README.tokenizers). The second argument
126308** is the query expression to parse. Each subsequent argument is the name
126309** of a column of the fts3 table that the query expression may refer to.
126310** For example:
126311**
126312**   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
126313*/
126314static void fts3ExprTest(
126315  sqlite3_context *context,
126316  int argc,
126317  sqlite3_value **argv
126318){
126319  sqlite3_tokenizer_module const *pModule = 0;
126320  sqlite3_tokenizer *pTokenizer = 0;
126321  int rc;
126322  char **azCol = 0;
126323  const char *zExpr;
126324  int nExpr;
126325  int nCol;
126326  int ii;
126327  Fts3Expr *pExpr;
126328  char *zBuf = 0;
126329  sqlite3 *db = sqlite3_context_db_handle(context);
126330
126331  if( argc<3 ){
126332    sqlite3_result_error(context,
126333        "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
126334    );
126335    return;
126336  }
126337
126338  rc = queryTestTokenizer(db,
126339                          (const char *)sqlite3_value_text(argv[0]), &pModule);
126340  if( rc==SQLITE_NOMEM ){
126341    sqlite3_result_error_nomem(context);
126342    goto exprtest_out;
126343  }else if( !pModule ){
126344    sqlite3_result_error(context, "No such tokenizer module", -1);
126345    goto exprtest_out;
126346  }
126347
126348  rc = pModule->xCreate(0, 0, &pTokenizer);
126349  assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
126350  if( rc==SQLITE_NOMEM ){
126351    sqlite3_result_error_nomem(context);
126352    goto exprtest_out;
126353  }
126354  pTokenizer->pModule = pModule;
126355
126356  zExpr = (const char *)sqlite3_value_text(argv[1]);
126357  nExpr = sqlite3_value_bytes(argv[1]);
126358  nCol = argc-2;
126359  azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
126360  if( !azCol ){
126361    sqlite3_result_error_nomem(context);
126362    goto exprtest_out;
126363  }
126364  for(ii=0; ii<nCol; ii++){
126365    azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
126366  }
126367
126368  if( sqlite3_user_data(context) ){
126369    char *zDummy = 0;
126370    rc = sqlite3Fts3ExprParse(
126371        pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy
126372    );
126373    assert( rc==SQLITE_OK || pExpr==0 );
126374    sqlite3_free(zDummy);
126375  }else{
126376    rc = fts3ExprParseUnbalanced(
126377        pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
126378    );
126379  }
126380
126381  if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
126382    sqlite3Fts3ExprFree(pExpr);
126383    sqlite3_result_error(context, "Error parsing expression", -1);
126384  }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
126385    sqlite3_result_error_nomem(context);
126386  }else{
126387    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
126388    sqlite3_free(zBuf);
126389  }
126390
126391  sqlite3Fts3ExprFree(pExpr);
126392
126393exprtest_out:
126394  if( pModule && pTokenizer ){
126395    rc = pModule->xDestroy(pTokenizer);
126396  }
126397  sqlite3_free(azCol);
126398}
126399
126400/*
126401** Register the query expression parser test function fts3_exprtest()
126402** with database connection db.
126403*/
126404SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
126405  int rc = sqlite3_create_function(
126406      db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
126407  );
126408  if( rc==SQLITE_OK ){
126409    rc = sqlite3_create_function(db, "fts3_exprtest_rebalance",
126410        -1, SQLITE_UTF8, (void *)1, fts3ExprTest, 0, 0
126411    );
126412  }
126413  return rc;
126414}
126415
126416#endif
126417#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
126418
126419/************** End of fts3_expr.c *******************************************/
126420/************** Begin file fts3_hash.c ***************************************/
126421/*
126422** 2001 September 22
126423**
126424** The author disclaims copyright to this source code.  In place of
126425** a legal notice, here is a blessing:
126426**
126427**    May you do good and not evil.
126428**    May you find forgiveness for yourself and forgive others.
126429**    May you share freely, never taking more than you give.
126430**
126431*************************************************************************
126432** This is the implementation of generic hash-tables used in SQLite.
126433** We've modified it slightly to serve as a standalone hash table
126434** implementation for the full-text indexing module.
126435*/
126436
126437/*
126438** The code in this file is only compiled if:
126439**
126440**     * The FTS3 module is being built as an extension
126441**       (in which case SQLITE_CORE is not defined), or
126442**
126443**     * The FTS3 module is being built into the core of
126444**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
126445*/
126446#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
126447
126448/* #include <assert.h> */
126449/* #include <stdlib.h> */
126450/* #include <string.h> */
126451
126452
126453/*
126454** Malloc and Free functions
126455*/
126456static void *fts3HashMalloc(int n){
126457  void *p = sqlite3_malloc(n);
126458  if( p ){
126459    memset(p, 0, n);
126460  }
126461  return p;
126462}
126463static void fts3HashFree(void *p){
126464  sqlite3_free(p);
126465}
126466
126467/* Turn bulk memory into a hash table object by initializing the
126468** fields of the Hash structure.
126469**
126470** "pNew" is a pointer to the hash table that is to be initialized.
126471** keyClass is one of the constants
126472** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass
126473** determines what kind of key the hash table will use.  "copyKey" is
126474** true if the hash table should make its own private copy of keys and
126475** false if it should just use the supplied pointer.
126476*/
126477SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
126478  assert( pNew!=0 );
126479  assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
126480  pNew->keyClass = keyClass;
126481  pNew->copyKey = copyKey;
126482  pNew->first = 0;
126483  pNew->count = 0;
126484  pNew->htsize = 0;
126485  pNew->ht = 0;
126486}
126487
126488/* Remove all entries from a hash table.  Reclaim all memory.
126489** Call this routine to delete a hash table or to reset a hash table
126490** to the empty state.
126491*/
126492SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
126493  Fts3HashElem *elem;         /* For looping over all elements of the table */
126494
126495  assert( pH!=0 );
126496  elem = pH->first;
126497  pH->first = 0;
126498  fts3HashFree(pH->ht);
126499  pH->ht = 0;
126500  pH->htsize = 0;
126501  while( elem ){
126502    Fts3HashElem *next_elem = elem->next;
126503    if( pH->copyKey && elem->pKey ){
126504      fts3HashFree(elem->pKey);
126505    }
126506    fts3HashFree(elem);
126507    elem = next_elem;
126508  }
126509  pH->count = 0;
126510}
126511
126512/*
126513** Hash and comparison functions when the mode is FTS3_HASH_STRING
126514*/
126515static int fts3StrHash(const void *pKey, int nKey){
126516  const char *z = (const char *)pKey;
126517  int h = 0;
126518  if( nKey<=0 ) nKey = (int) strlen(z);
126519  while( nKey > 0  ){
126520    h = (h<<3) ^ h ^ *z++;
126521    nKey--;
126522  }
126523  return h & 0x7fffffff;
126524}
126525static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
126526  if( n1!=n2 ) return 1;
126527  return strncmp((const char*)pKey1,(const char*)pKey2,n1);
126528}
126529
126530/*
126531** Hash and comparison functions when the mode is FTS3_HASH_BINARY
126532*/
126533static int fts3BinHash(const void *pKey, int nKey){
126534  int h = 0;
126535  const char *z = (const char *)pKey;
126536  while( nKey-- > 0 ){
126537    h = (h<<3) ^ h ^ *(z++);
126538  }
126539  return h & 0x7fffffff;
126540}
126541static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
126542  if( n1!=n2 ) return 1;
126543  return memcmp(pKey1,pKey2,n1);
126544}
126545
126546/*
126547** Return a pointer to the appropriate hash function given the key class.
126548**
126549** The C syntax in this function definition may be unfamilar to some
126550** programmers, so we provide the following additional explanation:
126551**
126552** The name of the function is "ftsHashFunction".  The function takes a
126553** single parameter "keyClass".  The return value of ftsHashFunction()
126554** is a pointer to another function.  Specifically, the return value
126555** of ftsHashFunction() is a pointer to a function that takes two parameters
126556** with types "const void*" and "int" and returns an "int".
126557*/
126558static int (*ftsHashFunction(int keyClass))(const void*,int){
126559  if( keyClass==FTS3_HASH_STRING ){
126560    return &fts3StrHash;
126561  }else{
126562    assert( keyClass==FTS3_HASH_BINARY );
126563    return &fts3BinHash;
126564  }
126565}
126566
126567/*
126568** Return a pointer to the appropriate hash function given the key class.
126569**
126570** For help in interpreted the obscure C code in the function definition,
126571** see the header comment on the previous function.
126572*/
126573static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
126574  if( keyClass==FTS3_HASH_STRING ){
126575    return &fts3StrCompare;
126576  }else{
126577    assert( keyClass==FTS3_HASH_BINARY );
126578    return &fts3BinCompare;
126579  }
126580}
126581
126582/* Link an element into the hash table
126583*/
126584static void fts3HashInsertElement(
126585  Fts3Hash *pH,            /* The complete hash table */
126586  struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
126587  Fts3HashElem *pNew       /* The element to be inserted */
126588){
126589  Fts3HashElem *pHead;     /* First element already in pEntry */
126590  pHead = pEntry->chain;
126591  if( pHead ){
126592    pNew->next = pHead;
126593    pNew->prev = pHead->prev;
126594    if( pHead->prev ){ pHead->prev->next = pNew; }
126595    else             { pH->first = pNew; }
126596    pHead->prev = pNew;
126597  }else{
126598    pNew->next = pH->first;
126599    if( pH->first ){ pH->first->prev = pNew; }
126600    pNew->prev = 0;
126601    pH->first = pNew;
126602  }
126603  pEntry->count++;
126604  pEntry->chain = pNew;
126605}
126606
126607
126608/* Resize the hash table so that it cantains "new_size" buckets.
126609** "new_size" must be a power of 2.  The hash table might fail
126610** to resize if sqliteMalloc() fails.
126611**
126612** Return non-zero if a memory allocation error occurs.
126613*/
126614static int fts3Rehash(Fts3Hash *pH, int new_size){
126615  struct _fts3ht *new_ht;          /* The new hash table */
126616  Fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
126617  int (*xHash)(const void*,int);   /* The hash function */
126618
126619  assert( (new_size & (new_size-1))==0 );
126620  new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
126621  if( new_ht==0 ) return 1;
126622  fts3HashFree(pH->ht);
126623  pH->ht = new_ht;
126624  pH->htsize = new_size;
126625  xHash = ftsHashFunction(pH->keyClass);
126626  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
126627    int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
126628    next_elem = elem->next;
126629    fts3HashInsertElement(pH, &new_ht[h], elem);
126630  }
126631  return 0;
126632}
126633
126634/* This function (for internal use only) locates an element in an
126635** hash table that matches the given key.  The hash for this key has
126636** already been computed and is passed as the 4th parameter.
126637*/
126638static Fts3HashElem *fts3FindElementByHash(
126639  const Fts3Hash *pH, /* The pH to be searched */
126640  const void *pKey,   /* The key we are searching for */
126641  int nKey,
126642  int h               /* The hash for this key. */
126643){
126644  Fts3HashElem *elem;            /* Used to loop thru the element list */
126645  int count;                     /* Number of elements left to test */
126646  int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
126647
126648  if( pH->ht ){
126649    struct _fts3ht *pEntry = &pH->ht[h];
126650    elem = pEntry->chain;
126651    count = pEntry->count;
126652    xCompare = ftsCompareFunction(pH->keyClass);
126653    while( count-- && elem ){
126654      if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
126655        return elem;
126656      }
126657      elem = elem->next;
126658    }
126659  }
126660  return 0;
126661}
126662
126663/* Remove a single entry from the hash table given a pointer to that
126664** element and a hash on the element's key.
126665*/
126666static void fts3RemoveElementByHash(
126667  Fts3Hash *pH,         /* The pH containing "elem" */
126668  Fts3HashElem* elem,   /* The element to be removed from the pH */
126669  int h                 /* Hash value for the element */
126670){
126671  struct _fts3ht *pEntry;
126672  if( elem->prev ){
126673    elem->prev->next = elem->next;
126674  }else{
126675    pH->first = elem->next;
126676  }
126677  if( elem->next ){
126678    elem->next->prev = elem->prev;
126679  }
126680  pEntry = &pH->ht[h];
126681  if( pEntry->chain==elem ){
126682    pEntry->chain = elem->next;
126683  }
126684  pEntry->count--;
126685  if( pEntry->count<=0 ){
126686    pEntry->chain = 0;
126687  }
126688  if( pH->copyKey && elem->pKey ){
126689    fts3HashFree(elem->pKey);
126690  }
126691  fts3HashFree( elem );
126692  pH->count--;
126693  if( pH->count<=0 ){
126694    assert( pH->first==0 );
126695    assert( pH->count==0 );
126696    fts3HashClear(pH);
126697  }
126698}
126699
126700SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
126701  const Fts3Hash *pH,
126702  const void *pKey,
126703  int nKey
126704){
126705  int h;                          /* A hash on key */
126706  int (*xHash)(const void*,int);  /* The hash function */
126707
126708  if( pH==0 || pH->ht==0 ) return 0;
126709  xHash = ftsHashFunction(pH->keyClass);
126710  assert( xHash!=0 );
126711  h = (*xHash)(pKey,nKey);
126712  assert( (pH->htsize & (pH->htsize-1))==0 );
126713  return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
126714}
126715
126716/*
126717** Attempt to locate an element of the hash table pH with a key
126718** that matches pKey,nKey.  Return the data for this element if it is
126719** found, or NULL if there is no match.
126720*/
126721SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
126722  Fts3HashElem *pElem;            /* The element that matches key (if any) */
126723
126724  pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
126725  return pElem ? pElem->data : 0;
126726}
126727
126728/* Insert an element into the hash table pH.  The key is pKey,nKey
126729** and the data is "data".
126730**
126731** If no element exists with a matching key, then a new
126732** element is created.  A copy of the key is made if the copyKey
126733** flag is set.  NULL is returned.
126734**
126735** If another element already exists with the same key, then the
126736** new data replaces the old data and the old data is returned.
126737** The key is not copied in this instance.  If a malloc fails, then
126738** the new data is returned and the hash table is unchanged.
126739**
126740** If the "data" parameter to this function is NULL, then the
126741** element corresponding to "key" is removed from the hash table.
126742*/
126743SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
126744  Fts3Hash *pH,        /* The hash table to insert into */
126745  const void *pKey,    /* The key */
126746  int nKey,            /* Number of bytes in the key */
126747  void *data           /* The data */
126748){
126749  int hraw;                 /* Raw hash value of the key */
126750  int h;                    /* the hash of the key modulo hash table size */
126751  Fts3HashElem *elem;       /* Used to loop thru the element list */
126752  Fts3HashElem *new_elem;   /* New element added to the pH */
126753  int (*xHash)(const void*,int);  /* The hash function */
126754
126755  assert( pH!=0 );
126756  xHash = ftsHashFunction(pH->keyClass);
126757  assert( xHash!=0 );
126758  hraw = (*xHash)(pKey, nKey);
126759  assert( (pH->htsize & (pH->htsize-1))==0 );
126760  h = hraw & (pH->htsize-1);
126761  elem = fts3FindElementByHash(pH,pKey,nKey,h);
126762  if( elem ){
126763    void *old_data = elem->data;
126764    if( data==0 ){
126765      fts3RemoveElementByHash(pH,elem,h);
126766    }else{
126767      elem->data = data;
126768    }
126769    return old_data;
126770  }
126771  if( data==0 ) return 0;
126772  if( (pH->htsize==0 && fts3Rehash(pH,8))
126773   || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
126774  ){
126775    pH->count = 0;
126776    return data;
126777  }
126778  assert( pH->htsize>0 );
126779  new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
126780  if( new_elem==0 ) return data;
126781  if( pH->copyKey && pKey!=0 ){
126782    new_elem->pKey = fts3HashMalloc( nKey );
126783    if( new_elem->pKey==0 ){
126784      fts3HashFree(new_elem);
126785      return data;
126786    }
126787    memcpy((void*)new_elem->pKey, pKey, nKey);
126788  }else{
126789    new_elem->pKey = (void*)pKey;
126790  }
126791  new_elem->nKey = nKey;
126792  pH->count++;
126793  assert( pH->htsize>0 );
126794  assert( (pH->htsize & (pH->htsize-1))==0 );
126795  h = hraw & (pH->htsize-1);
126796  fts3HashInsertElement(pH, &pH->ht[h], new_elem);
126797  new_elem->data = data;
126798  return 0;
126799}
126800
126801#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
126802
126803/************** End of fts3_hash.c *******************************************/
126804/************** Begin file fts3_porter.c *************************************/
126805/*
126806** 2006 September 30
126807**
126808** The author disclaims copyright to this source code.  In place of
126809** a legal notice, here is a blessing:
126810**
126811**    May you do good and not evil.
126812**    May you find forgiveness for yourself and forgive others.
126813**    May you share freely, never taking more than you give.
126814**
126815*************************************************************************
126816** Implementation of the full-text-search tokenizer that implements
126817** a Porter stemmer.
126818*/
126819
126820/*
126821** The code in this file is only compiled if:
126822**
126823**     * The FTS3 module is being built as an extension
126824**       (in which case SQLITE_CORE is not defined), or
126825**
126826**     * The FTS3 module is being built into the core of
126827**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
126828*/
126829#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
126830
126831/* #include <assert.h> */
126832/* #include <stdlib.h> */
126833/* #include <stdio.h> */
126834/* #include <string.h> */
126835
126836
126837/*
126838** Class derived from sqlite3_tokenizer
126839*/
126840typedef struct porter_tokenizer {
126841  sqlite3_tokenizer base;      /* Base class */
126842} porter_tokenizer;
126843
126844/*
126845** Class derived from sqlite3_tokenizer_cursor
126846*/
126847typedef struct porter_tokenizer_cursor {
126848  sqlite3_tokenizer_cursor base;
126849  const char *zInput;          /* input we are tokenizing */
126850  int nInput;                  /* size of the input */
126851  int iOffset;                 /* current position in zInput */
126852  int iToken;                  /* index of next token to be returned */
126853  char *zToken;                /* storage for current token */
126854  int nAllocated;              /* space allocated to zToken buffer */
126855} porter_tokenizer_cursor;
126856
126857
126858/*
126859** Create a new tokenizer instance.
126860*/
126861static int porterCreate(
126862  int argc, const char * const *argv,
126863  sqlite3_tokenizer **ppTokenizer
126864){
126865  porter_tokenizer *t;
126866
126867  UNUSED_PARAMETER(argc);
126868  UNUSED_PARAMETER(argv);
126869
126870  t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
126871  if( t==NULL ) return SQLITE_NOMEM;
126872  memset(t, 0, sizeof(*t));
126873  *ppTokenizer = &t->base;
126874  return SQLITE_OK;
126875}
126876
126877/*
126878** Destroy a tokenizer
126879*/
126880static int porterDestroy(sqlite3_tokenizer *pTokenizer){
126881  sqlite3_free(pTokenizer);
126882  return SQLITE_OK;
126883}
126884
126885/*
126886** Prepare to begin tokenizing a particular string.  The input
126887** string to be tokenized is zInput[0..nInput-1].  A cursor
126888** used to incrementally tokenize this string is returned in
126889** *ppCursor.
126890*/
126891static int porterOpen(
126892  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
126893  const char *zInput, int nInput,        /* String to be tokenized */
126894  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
126895){
126896  porter_tokenizer_cursor *c;
126897
126898  UNUSED_PARAMETER(pTokenizer);
126899
126900  c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
126901  if( c==NULL ) return SQLITE_NOMEM;
126902
126903  c->zInput = zInput;
126904  if( zInput==0 ){
126905    c->nInput = 0;
126906  }else if( nInput<0 ){
126907    c->nInput = (int)strlen(zInput);
126908  }else{
126909    c->nInput = nInput;
126910  }
126911  c->iOffset = 0;                 /* start tokenizing at the beginning */
126912  c->iToken = 0;
126913  c->zToken = NULL;               /* no space allocated, yet. */
126914  c->nAllocated = 0;
126915
126916  *ppCursor = &c->base;
126917  return SQLITE_OK;
126918}
126919
126920/*
126921** Close a tokenization cursor previously opened by a call to
126922** porterOpen() above.
126923*/
126924static int porterClose(sqlite3_tokenizer_cursor *pCursor){
126925  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
126926  sqlite3_free(c->zToken);
126927  sqlite3_free(c);
126928  return SQLITE_OK;
126929}
126930/*
126931** Vowel or consonant
126932*/
126933static const char cType[] = {
126934   0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
126935   1, 1, 1, 2, 1
126936};
126937
126938/*
126939** isConsonant() and isVowel() determine if their first character in
126940** the string they point to is a consonant or a vowel, according
126941** to Porter ruls.
126942**
126943** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
126944** 'Y' is a consonant unless it follows another consonant,
126945** in which case it is a vowel.
126946**
126947** In these routine, the letters are in reverse order.  So the 'y' rule
126948** is that 'y' is a consonant unless it is followed by another
126949** consonent.
126950*/
126951static int isVowel(const char*);
126952static int isConsonant(const char *z){
126953  int j;
126954  char x = *z;
126955  if( x==0 ) return 0;
126956  assert( x>='a' && x<='z' );
126957  j = cType[x-'a'];
126958  if( j<2 ) return j;
126959  return z[1]==0 || isVowel(z + 1);
126960}
126961static int isVowel(const char *z){
126962  int j;
126963  char x = *z;
126964  if( x==0 ) return 0;
126965  assert( x>='a' && x<='z' );
126966  j = cType[x-'a'];
126967  if( j<2 ) return 1-j;
126968  return isConsonant(z + 1);
126969}
126970
126971/*
126972** Let any sequence of one or more vowels be represented by V and let
126973** C be sequence of one or more consonants.  Then every word can be
126974** represented as:
126975**
126976**           [C] (VC){m} [V]
126977**
126978** In prose:  A word is an optional consonant followed by zero or
126979** vowel-consonant pairs followed by an optional vowel.  "m" is the
126980** number of vowel consonant pairs.  This routine computes the value
126981** of m for the first i bytes of a word.
126982**
126983** Return true if the m-value for z is 1 or more.  In other words,
126984** return true if z contains at least one vowel that is followed
126985** by a consonant.
126986**
126987** In this routine z[] is in reverse order.  So we are really looking
126988** for an instance of of a consonant followed by a vowel.
126989*/
126990static int m_gt_0(const char *z){
126991  while( isVowel(z) ){ z++; }
126992  if( *z==0 ) return 0;
126993  while( isConsonant(z) ){ z++; }
126994  return *z!=0;
126995}
126996
126997/* Like mgt0 above except we are looking for a value of m which is
126998** exactly 1
126999*/
127000static int m_eq_1(const char *z){
127001  while( isVowel(z) ){ z++; }
127002  if( *z==0 ) return 0;
127003  while( isConsonant(z) ){ z++; }
127004  if( *z==0 ) return 0;
127005  while( isVowel(z) ){ z++; }
127006  if( *z==0 ) return 1;
127007  while( isConsonant(z) ){ z++; }
127008  return *z==0;
127009}
127010
127011/* Like mgt0 above except we are looking for a value of m>1 instead
127012** or m>0
127013*/
127014static int m_gt_1(const char *z){
127015  while( isVowel(z) ){ z++; }
127016  if( *z==0 ) return 0;
127017  while( isConsonant(z) ){ z++; }
127018  if( *z==0 ) return 0;
127019  while( isVowel(z) ){ z++; }
127020  if( *z==0 ) return 0;
127021  while( isConsonant(z) ){ z++; }
127022  return *z!=0;
127023}
127024
127025/*
127026** Return TRUE if there is a vowel anywhere within z[0..n-1]
127027*/
127028static int hasVowel(const char *z){
127029  while( isConsonant(z) ){ z++; }
127030  return *z!=0;
127031}
127032
127033/*
127034** Return TRUE if the word ends in a double consonant.
127035**
127036** The text is reversed here. So we are really looking at
127037** the first two characters of z[].
127038*/
127039static int doubleConsonant(const char *z){
127040  return isConsonant(z) && z[0]==z[1];
127041}
127042
127043/*
127044** Return TRUE if the word ends with three letters which
127045** are consonant-vowel-consonent and where the final consonant
127046** is not 'w', 'x', or 'y'.
127047**
127048** The word is reversed here.  So we are really checking the
127049** first three letters and the first one cannot be in [wxy].
127050*/
127051static int star_oh(const char *z){
127052  return
127053    isConsonant(z) &&
127054    z[0]!='w' && z[0]!='x' && z[0]!='y' &&
127055    isVowel(z+1) &&
127056    isConsonant(z+2);
127057}
127058
127059/*
127060** If the word ends with zFrom and xCond() is true for the stem
127061** of the word that preceeds the zFrom ending, then change the
127062** ending to zTo.
127063**
127064** The input word *pz and zFrom are both in reverse order.  zTo
127065** is in normal order.
127066**
127067** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
127068** match.  Not that TRUE is returned even if xCond() fails and
127069** no substitution occurs.
127070*/
127071static int stem(
127072  char **pz,             /* The word being stemmed (Reversed) */
127073  const char *zFrom,     /* If the ending matches this... (Reversed) */
127074  const char *zTo,       /* ... change the ending to this (not reversed) */
127075  int (*xCond)(const char*)   /* Condition that must be true */
127076){
127077  char *z = *pz;
127078  while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
127079  if( *zFrom!=0 ) return 0;
127080  if( xCond && !xCond(z) ) return 1;
127081  while( *zTo ){
127082    *(--z) = *(zTo++);
127083  }
127084  *pz = z;
127085  return 1;
127086}
127087
127088/*
127089** This is the fallback stemmer used when the porter stemmer is
127090** inappropriate.  The input word is copied into the output with
127091** US-ASCII case folding.  If the input word is too long (more
127092** than 20 bytes if it contains no digits or more than 6 bytes if
127093** it contains digits) then word is truncated to 20 or 6 bytes
127094** by taking 10 or 3 bytes from the beginning and end.
127095*/
127096static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
127097  int i, mx, j;
127098  int hasDigit = 0;
127099  for(i=0; i<nIn; i++){
127100    char c = zIn[i];
127101    if( c>='A' && c<='Z' ){
127102      zOut[i] = c - 'A' + 'a';
127103    }else{
127104      if( c>='0' && c<='9' ) hasDigit = 1;
127105      zOut[i] = c;
127106    }
127107  }
127108  mx = hasDigit ? 3 : 10;
127109  if( nIn>mx*2 ){
127110    for(j=mx, i=nIn-mx; i<nIn; i++, j++){
127111      zOut[j] = zOut[i];
127112    }
127113    i = j;
127114  }
127115  zOut[i] = 0;
127116  *pnOut = i;
127117}
127118
127119
127120/*
127121** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
127122** zOut is at least big enough to hold nIn bytes.  Write the actual
127123** size of the output word (exclusive of the '\0' terminator) into *pnOut.
127124**
127125** Any upper-case characters in the US-ASCII character set ([A-Z])
127126** are converted to lower case.  Upper-case UTF characters are
127127** unchanged.
127128**
127129** Words that are longer than about 20 bytes are stemmed by retaining
127130** a few bytes from the beginning and the end of the word.  If the
127131** word contains digits, 3 bytes are taken from the beginning and
127132** 3 bytes from the end.  For long words without digits, 10 bytes
127133** are taken from each end.  US-ASCII case folding still applies.
127134**
127135** If the input word contains not digits but does characters not
127136** in [a-zA-Z] then no stemming is attempted and this routine just
127137** copies the input into the input into the output with US-ASCII
127138** case folding.
127139**
127140** Stemming never increases the length of the word.  So there is
127141** no chance of overflowing the zOut buffer.
127142*/
127143static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
127144  int i, j;
127145  char zReverse[28];
127146  char *z, *z2;
127147  if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
127148    /* The word is too big or too small for the porter stemmer.
127149    ** Fallback to the copy stemmer */
127150    copy_stemmer(zIn, nIn, zOut, pnOut);
127151    return;
127152  }
127153  for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
127154    char c = zIn[i];
127155    if( c>='A' && c<='Z' ){
127156      zReverse[j] = c + 'a' - 'A';
127157    }else if( c>='a' && c<='z' ){
127158      zReverse[j] = c;
127159    }else{
127160      /* The use of a character not in [a-zA-Z] means that we fallback
127161      ** to the copy stemmer */
127162      copy_stemmer(zIn, nIn, zOut, pnOut);
127163      return;
127164    }
127165  }
127166  memset(&zReverse[sizeof(zReverse)-5], 0, 5);
127167  z = &zReverse[j+1];
127168
127169
127170  /* Step 1a */
127171  if( z[0]=='s' ){
127172    if(
127173     !stem(&z, "sess", "ss", 0) &&
127174     !stem(&z, "sei", "i", 0)  &&
127175     !stem(&z, "ss", "ss", 0)
127176    ){
127177      z++;
127178    }
127179  }
127180
127181  /* Step 1b */
127182  z2 = z;
127183  if( stem(&z, "dee", "ee", m_gt_0) ){
127184    /* Do nothing.  The work was all in the test */
127185  }else if(
127186     (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
127187      && z!=z2
127188  ){
127189     if( stem(&z, "ta", "ate", 0) ||
127190         stem(&z, "lb", "ble", 0) ||
127191         stem(&z, "zi", "ize", 0) ){
127192       /* Do nothing.  The work was all in the test */
127193     }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
127194       z++;
127195     }else if( m_eq_1(z) && star_oh(z) ){
127196       *(--z) = 'e';
127197     }
127198  }
127199
127200  /* Step 1c */
127201  if( z[0]=='y' && hasVowel(z+1) ){
127202    z[0] = 'i';
127203  }
127204
127205  /* Step 2 */
127206  switch( z[1] ){
127207   case 'a':
127208     stem(&z, "lanoita", "ate", m_gt_0) ||
127209     stem(&z, "lanoit", "tion", m_gt_0);
127210     break;
127211   case 'c':
127212     stem(&z, "icne", "ence", m_gt_0) ||
127213     stem(&z, "icna", "ance", m_gt_0);
127214     break;
127215   case 'e':
127216     stem(&z, "rezi", "ize", m_gt_0);
127217     break;
127218   case 'g':
127219     stem(&z, "igol", "log", m_gt_0);
127220     break;
127221   case 'l':
127222     stem(&z, "ilb", "ble", m_gt_0) ||
127223     stem(&z, "illa", "al", m_gt_0) ||
127224     stem(&z, "iltne", "ent", m_gt_0) ||
127225     stem(&z, "ile", "e", m_gt_0) ||
127226     stem(&z, "ilsuo", "ous", m_gt_0);
127227     break;
127228   case 'o':
127229     stem(&z, "noitazi", "ize", m_gt_0) ||
127230     stem(&z, "noita", "ate", m_gt_0) ||
127231     stem(&z, "rota", "ate", m_gt_0);
127232     break;
127233   case 's':
127234     stem(&z, "msila", "al", m_gt_0) ||
127235     stem(&z, "ssenevi", "ive", m_gt_0) ||
127236     stem(&z, "ssenluf", "ful", m_gt_0) ||
127237     stem(&z, "ssensuo", "ous", m_gt_0);
127238     break;
127239   case 't':
127240     stem(&z, "itila", "al", m_gt_0) ||
127241     stem(&z, "itivi", "ive", m_gt_0) ||
127242     stem(&z, "itilib", "ble", m_gt_0);
127243     break;
127244  }
127245
127246  /* Step 3 */
127247  switch( z[0] ){
127248   case 'e':
127249     stem(&z, "etaci", "ic", m_gt_0) ||
127250     stem(&z, "evita", "", m_gt_0)   ||
127251     stem(&z, "ezila", "al", m_gt_0);
127252     break;
127253   case 'i':
127254     stem(&z, "itici", "ic", m_gt_0);
127255     break;
127256   case 'l':
127257     stem(&z, "laci", "ic", m_gt_0) ||
127258     stem(&z, "luf", "", m_gt_0);
127259     break;
127260   case 's':
127261     stem(&z, "ssen", "", m_gt_0);
127262     break;
127263  }
127264
127265  /* Step 4 */
127266  switch( z[1] ){
127267   case 'a':
127268     if( z[0]=='l' && m_gt_1(z+2) ){
127269       z += 2;
127270     }
127271     break;
127272   case 'c':
127273     if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
127274       z += 4;
127275     }
127276     break;
127277   case 'e':
127278     if( z[0]=='r' && m_gt_1(z+2) ){
127279       z += 2;
127280     }
127281     break;
127282   case 'i':
127283     if( z[0]=='c' && m_gt_1(z+2) ){
127284       z += 2;
127285     }
127286     break;
127287   case 'l':
127288     if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
127289       z += 4;
127290     }
127291     break;
127292   case 'n':
127293     if( z[0]=='t' ){
127294       if( z[2]=='a' ){
127295         if( m_gt_1(z+3) ){
127296           z += 3;
127297         }
127298       }else if( z[2]=='e' ){
127299         stem(&z, "tneme", "", m_gt_1) ||
127300         stem(&z, "tnem", "", m_gt_1) ||
127301         stem(&z, "tne", "", m_gt_1);
127302       }
127303     }
127304     break;
127305   case 'o':
127306     if( z[0]=='u' ){
127307       if( m_gt_1(z+2) ){
127308         z += 2;
127309       }
127310     }else if( z[3]=='s' || z[3]=='t' ){
127311       stem(&z, "noi", "", m_gt_1);
127312     }
127313     break;
127314   case 's':
127315     if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
127316       z += 3;
127317     }
127318     break;
127319   case 't':
127320     stem(&z, "eta", "", m_gt_1) ||
127321     stem(&z, "iti", "", m_gt_1);
127322     break;
127323   case 'u':
127324     if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
127325       z += 3;
127326     }
127327     break;
127328   case 'v':
127329   case 'z':
127330     if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
127331       z += 3;
127332     }
127333     break;
127334  }
127335
127336  /* Step 5a */
127337  if( z[0]=='e' ){
127338    if( m_gt_1(z+1) ){
127339      z++;
127340    }else if( m_eq_1(z+1) && !star_oh(z+1) ){
127341      z++;
127342    }
127343  }
127344
127345  /* Step 5b */
127346  if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
127347    z++;
127348  }
127349
127350  /* z[] is now the stemmed word in reverse order.  Flip it back
127351  ** around into forward order and return.
127352  */
127353  *pnOut = i = (int)strlen(z);
127354  zOut[i] = 0;
127355  while( *z ){
127356    zOut[--i] = *(z++);
127357  }
127358}
127359
127360/*
127361** Characters that can be part of a token.  We assume any character
127362** whose value is greater than 0x80 (any UTF character) can be
127363** part of a token.  In other words, delimiters all must have
127364** values of 0x7f or lower.
127365*/
127366static const char porterIdChar[] = {
127367/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
127368    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
127369    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
127370    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
127371    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
127372    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
127373};
127374#define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
127375
127376/*
127377** Extract the next token from a tokenization cursor.  The cursor must
127378** have been opened by a prior call to porterOpen().
127379*/
127380static int porterNext(
127381  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
127382  const char **pzToken,               /* OUT: *pzToken is the token text */
127383  int *pnBytes,                       /* OUT: Number of bytes in token */
127384  int *piStartOffset,                 /* OUT: Starting offset of token */
127385  int *piEndOffset,                   /* OUT: Ending offset of token */
127386  int *piPosition                     /* OUT: Position integer of token */
127387){
127388  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
127389  const char *z = c->zInput;
127390
127391  while( c->iOffset<c->nInput ){
127392    int iStartOffset, ch;
127393
127394    /* Scan past delimiter characters */
127395    while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
127396      c->iOffset++;
127397    }
127398
127399    /* Count non-delimiter characters. */
127400    iStartOffset = c->iOffset;
127401    while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
127402      c->iOffset++;
127403    }
127404
127405    if( c->iOffset>iStartOffset ){
127406      int n = c->iOffset-iStartOffset;
127407      if( n>c->nAllocated ){
127408        char *pNew;
127409        c->nAllocated = n+20;
127410        pNew = sqlite3_realloc(c->zToken, c->nAllocated);
127411        if( !pNew ) return SQLITE_NOMEM;
127412        c->zToken = pNew;
127413      }
127414      porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
127415      *pzToken = c->zToken;
127416      *piStartOffset = iStartOffset;
127417      *piEndOffset = c->iOffset;
127418      *piPosition = c->iToken++;
127419      return SQLITE_OK;
127420    }
127421  }
127422  return SQLITE_DONE;
127423}
127424
127425/*
127426** The set of routines that implement the porter-stemmer tokenizer
127427*/
127428static const sqlite3_tokenizer_module porterTokenizerModule = {
127429  0,
127430  porterCreate,
127431  porterDestroy,
127432  porterOpen,
127433  porterClose,
127434  porterNext,
127435  0
127436};
127437
127438/*
127439** Allocate a new porter tokenizer.  Return a pointer to the new
127440** tokenizer in *ppModule
127441*/
127442SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
127443  sqlite3_tokenizer_module const**ppModule
127444){
127445  *ppModule = &porterTokenizerModule;
127446}
127447
127448#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
127449
127450/************** End of fts3_porter.c *****************************************/
127451/************** Begin file fts3_tokenizer.c **********************************/
127452/*
127453** 2007 June 22
127454**
127455** The author disclaims copyright to this source code.  In place of
127456** a legal notice, here is a blessing:
127457**
127458**    May you do good and not evil.
127459**    May you find forgiveness for yourself and forgive others.
127460**    May you share freely, never taking more than you give.
127461**
127462******************************************************************************
127463**
127464** This is part of an SQLite module implementing full-text search.
127465** This particular file implements the generic tokenizer interface.
127466*/
127467
127468/*
127469** The code in this file is only compiled if:
127470**
127471**     * The FTS3 module is being built as an extension
127472**       (in which case SQLITE_CORE is not defined), or
127473**
127474**     * The FTS3 module is being built into the core of
127475**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
127476*/
127477#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
127478
127479/* #include <assert.h> */
127480/* #include <string.h> */
127481
127482/*
127483** Implementation of the SQL scalar function for accessing the underlying
127484** hash table. This function may be called as follows:
127485**
127486**   SELECT <function-name>(<key-name>);
127487**   SELECT <function-name>(<key-name>, <pointer>);
127488**
127489** where <function-name> is the name passed as the second argument
127490** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
127491**
127492** If the <pointer> argument is specified, it must be a blob value
127493** containing a pointer to be stored as the hash data corresponding
127494** to the string <key-name>. If <pointer> is not specified, then
127495** the string <key-name> must already exist in the has table. Otherwise,
127496** an error is returned.
127497**
127498** Whether or not the <pointer> argument is specified, the value returned
127499** is a blob containing the pointer stored as the hash data corresponding
127500** to string <key-name> (after the hash-table is updated, if applicable).
127501*/
127502static void scalarFunc(
127503  sqlite3_context *context,
127504  int argc,
127505  sqlite3_value **argv
127506){
127507  Fts3Hash *pHash;
127508  void *pPtr = 0;
127509  const unsigned char *zName;
127510  int nName;
127511
127512  assert( argc==1 || argc==2 );
127513
127514  pHash = (Fts3Hash *)sqlite3_user_data(context);
127515
127516  zName = sqlite3_value_text(argv[0]);
127517  nName = sqlite3_value_bytes(argv[0])+1;
127518
127519  if( argc==2 ){
127520    void *pOld;
127521    int n = sqlite3_value_bytes(argv[1]);
127522    if( n!=sizeof(pPtr) ){
127523      sqlite3_result_error(context, "argument type mismatch", -1);
127524      return;
127525    }
127526    pPtr = *(void **)sqlite3_value_blob(argv[1]);
127527    pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
127528    if( pOld==pPtr ){
127529      sqlite3_result_error(context, "out of memory", -1);
127530      return;
127531    }
127532  }else{
127533    pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
127534    if( !pPtr ){
127535      char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
127536      sqlite3_result_error(context, zErr, -1);
127537      sqlite3_free(zErr);
127538      return;
127539    }
127540  }
127541
127542  sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
127543}
127544
127545SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
127546  static const char isFtsIdChar[] = {
127547      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */
127548      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */
127549      0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
127550      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
127551      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
127552      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
127553      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
127554      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
127555  };
127556  return (c&0x80 || isFtsIdChar[(int)(c)]);
127557}
127558
127559SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
127560  const char *z1;
127561  const char *z2 = 0;
127562
127563  /* Find the start of the next token. */
127564  z1 = zStr;
127565  while( z2==0 ){
127566    char c = *z1;
127567    switch( c ){
127568      case '\0': return 0;        /* No more tokens here */
127569      case '\'':
127570      case '"':
127571      case '`': {
127572        z2 = z1;
127573        while( *++z2 && (*z2!=c || *++z2==c) );
127574        break;
127575      }
127576      case '[':
127577        z2 = &z1[1];
127578        while( *z2 && z2[0]!=']' ) z2++;
127579        if( *z2 ) z2++;
127580        break;
127581
127582      default:
127583        if( sqlite3Fts3IsIdChar(*z1) ){
127584          z2 = &z1[1];
127585          while( sqlite3Fts3IsIdChar(*z2) ) z2++;
127586        }else{
127587          z1++;
127588        }
127589    }
127590  }
127591
127592  *pn = (int)(z2-z1);
127593  return z1;
127594}
127595
127596SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
127597  Fts3Hash *pHash,                /* Tokenizer hash table */
127598  const char *zArg,               /* Tokenizer name */
127599  sqlite3_tokenizer **ppTok,      /* OUT: Tokenizer (if applicable) */
127600  char **pzErr                    /* OUT: Set to malloced error message */
127601){
127602  int rc;
127603  char *z = (char *)zArg;
127604  int n = 0;
127605  char *zCopy;
127606  char *zEnd;                     /* Pointer to nul-term of zCopy */
127607  sqlite3_tokenizer_module *m;
127608
127609  zCopy = sqlite3_mprintf("%s", zArg);
127610  if( !zCopy ) return SQLITE_NOMEM;
127611  zEnd = &zCopy[strlen(zCopy)];
127612
127613  z = (char *)sqlite3Fts3NextToken(zCopy, &n);
127614  z[n] = '\0';
127615  sqlite3Fts3Dequote(z);
127616
127617  m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
127618  if( !m ){
127619    *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
127620    rc = SQLITE_ERROR;
127621  }else{
127622    char const **aArg = 0;
127623    int iArg = 0;
127624    z = &z[n+1];
127625    while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
127626      int nNew = sizeof(char *)*(iArg+1);
127627      char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
127628      if( !aNew ){
127629        sqlite3_free(zCopy);
127630        sqlite3_free((void *)aArg);
127631        return SQLITE_NOMEM;
127632      }
127633      aArg = aNew;
127634      aArg[iArg++] = z;
127635      z[n] = '\0';
127636      sqlite3Fts3Dequote(z);
127637      z = &z[n+1];
127638    }
127639    rc = m->xCreate(iArg, aArg, ppTok);
127640    assert( rc!=SQLITE_OK || *ppTok );
127641    if( rc!=SQLITE_OK ){
127642      *pzErr = sqlite3_mprintf("unknown tokenizer");
127643    }else{
127644      (*ppTok)->pModule = m;
127645    }
127646    sqlite3_free((void *)aArg);
127647  }
127648
127649  sqlite3_free(zCopy);
127650  return rc;
127651}
127652
127653
127654#ifdef SQLITE_TEST
127655
127656/* #include <tcl.h> */
127657/* #include <string.h> */
127658
127659/*
127660** Implementation of a special SQL scalar function for testing tokenizers
127661** designed to be used in concert with the Tcl testing framework. This
127662** function must be called with two or more arguments:
127663**
127664**   SELECT <function-name>(<key-name>, ..., <input-string>);
127665**
127666** where <function-name> is the name passed as the second argument
127667** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
127668** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
127669**
127670** The return value is a string that may be interpreted as a Tcl
127671** list. For each token in the <input-string>, three elements are
127672** added to the returned list. The first is the token position, the
127673** second is the token text (folded, stemmed, etc.) and the third is the
127674** substring of <input-string> associated with the token. For example,
127675** using the built-in "simple" tokenizer:
127676**
127677**   SELECT fts_tokenizer_test('simple', 'I don't see how');
127678**
127679** will return the string:
127680**
127681**   "{0 i I 1 dont don't 2 see see 3 how how}"
127682**
127683*/
127684static void testFunc(
127685  sqlite3_context *context,
127686  int argc,
127687  sqlite3_value **argv
127688){
127689  Fts3Hash *pHash;
127690  sqlite3_tokenizer_module *p;
127691  sqlite3_tokenizer *pTokenizer = 0;
127692  sqlite3_tokenizer_cursor *pCsr = 0;
127693
127694  const char *zErr = 0;
127695
127696  const char *zName;
127697  int nName;
127698  const char *zInput;
127699  int nInput;
127700
127701  const char *azArg[64];
127702
127703  const char *zToken;
127704  int nToken = 0;
127705  int iStart = 0;
127706  int iEnd = 0;
127707  int iPos = 0;
127708  int i;
127709
127710  Tcl_Obj *pRet;
127711
127712  if( argc<2 ){
127713    sqlite3_result_error(context, "insufficient arguments", -1);
127714    return;
127715  }
127716
127717  nName = sqlite3_value_bytes(argv[0]);
127718  zName = (const char *)sqlite3_value_text(argv[0]);
127719  nInput = sqlite3_value_bytes(argv[argc-1]);
127720  zInput = (const char *)sqlite3_value_text(argv[argc-1]);
127721
127722  pHash = (Fts3Hash *)sqlite3_user_data(context);
127723  p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
127724
127725  if( !p ){
127726    char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
127727    sqlite3_result_error(context, zErr, -1);
127728    sqlite3_free(zErr);
127729    return;
127730  }
127731
127732  pRet = Tcl_NewObj();
127733  Tcl_IncrRefCount(pRet);
127734
127735  for(i=1; i<argc-1; i++){
127736    azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
127737  }
127738
127739  if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
127740    zErr = "error in xCreate()";
127741    goto finish;
127742  }
127743  pTokenizer->pModule = p;
127744  if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
127745    zErr = "error in xOpen()";
127746    goto finish;
127747  }
127748
127749  while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
127750    Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
127751    Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
127752    zToken = &zInput[iStart];
127753    nToken = iEnd-iStart;
127754    Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
127755  }
127756
127757  if( SQLITE_OK!=p->xClose(pCsr) ){
127758    zErr = "error in xClose()";
127759    goto finish;
127760  }
127761  if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
127762    zErr = "error in xDestroy()";
127763    goto finish;
127764  }
127765
127766finish:
127767  if( zErr ){
127768    sqlite3_result_error(context, zErr, -1);
127769  }else{
127770    sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
127771  }
127772  Tcl_DecrRefCount(pRet);
127773}
127774
127775static
127776int registerTokenizer(
127777  sqlite3 *db,
127778  char *zName,
127779  const sqlite3_tokenizer_module *p
127780){
127781  int rc;
127782  sqlite3_stmt *pStmt;
127783  const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
127784
127785  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
127786  if( rc!=SQLITE_OK ){
127787    return rc;
127788  }
127789
127790  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
127791  sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
127792  sqlite3_step(pStmt);
127793
127794  return sqlite3_finalize(pStmt);
127795}
127796
127797static
127798int queryTokenizer(
127799  sqlite3 *db,
127800  char *zName,
127801  const sqlite3_tokenizer_module **pp
127802){
127803  int rc;
127804  sqlite3_stmt *pStmt;
127805  const char zSql[] = "SELECT fts3_tokenizer(?)";
127806
127807  *pp = 0;
127808  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
127809  if( rc!=SQLITE_OK ){
127810    return rc;
127811  }
127812
127813  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
127814  if( SQLITE_ROW==sqlite3_step(pStmt) ){
127815    if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
127816      memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
127817    }
127818  }
127819
127820  return sqlite3_finalize(pStmt);
127821}
127822
127823SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
127824
127825/*
127826** Implementation of the scalar function fts3_tokenizer_internal_test().
127827** This function is used for testing only, it is not included in the
127828** build unless SQLITE_TEST is defined.
127829**
127830** The purpose of this is to test that the fts3_tokenizer() function
127831** can be used as designed by the C-code in the queryTokenizer and
127832** registerTokenizer() functions above. These two functions are repeated
127833** in the README.tokenizer file as an example, so it is important to
127834** test them.
127835**
127836** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
127837** function with no arguments. An assert() will fail if a problem is
127838** detected. i.e.:
127839**
127840**     SELECT fts3_tokenizer_internal_test();
127841**
127842*/
127843static void intTestFunc(
127844  sqlite3_context *context,
127845  int argc,
127846  sqlite3_value **argv
127847){
127848  int rc;
127849  const sqlite3_tokenizer_module *p1;
127850  const sqlite3_tokenizer_module *p2;
127851  sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
127852
127853  UNUSED_PARAMETER(argc);
127854  UNUSED_PARAMETER(argv);
127855
127856  /* Test the query function */
127857  sqlite3Fts3SimpleTokenizerModule(&p1);
127858  rc = queryTokenizer(db, "simple", &p2);
127859  assert( rc==SQLITE_OK );
127860  assert( p1==p2 );
127861  rc = queryTokenizer(db, "nosuchtokenizer", &p2);
127862  assert( rc==SQLITE_ERROR );
127863  assert( p2==0 );
127864  assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
127865
127866  /* Test the storage function */
127867  rc = registerTokenizer(db, "nosuchtokenizer", p1);
127868  assert( rc==SQLITE_OK );
127869  rc = queryTokenizer(db, "nosuchtokenizer", &p2);
127870  assert( rc==SQLITE_OK );
127871  assert( p2==p1 );
127872
127873  sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
127874}
127875
127876#endif
127877
127878/*
127879** Set up SQL objects in database db used to access the contents of
127880** the hash table pointed to by argument pHash. The hash table must
127881** been initialized to use string keys, and to take a private copy
127882** of the key when a value is inserted. i.e. by a call similar to:
127883**
127884**    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
127885**
127886** This function adds a scalar function (see header comment above
127887** scalarFunc() in this file for details) and, if ENABLE_TABLE is
127888** defined at compilation time, a temporary virtual table (see header
127889** comment above struct HashTableVtab) to the database schema. Both
127890** provide read/write access to the contents of *pHash.
127891**
127892** The third argument to this function, zName, is used as the name
127893** of both the scalar and, if created, the virtual table.
127894*/
127895SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
127896  sqlite3 *db,
127897  Fts3Hash *pHash,
127898  const char *zName
127899){
127900  int rc = SQLITE_OK;
127901  void *p = (void *)pHash;
127902  const int any = SQLITE_ANY;
127903
127904#ifdef SQLITE_TEST
127905  char *zTest = 0;
127906  char *zTest2 = 0;
127907  void *pdb = (void *)db;
127908  zTest = sqlite3_mprintf("%s_test", zName);
127909  zTest2 = sqlite3_mprintf("%s_internal_test", zName);
127910  if( !zTest || !zTest2 ){
127911    rc = SQLITE_NOMEM;
127912  }
127913#endif
127914
127915  if( SQLITE_OK==rc ){
127916    rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0);
127917  }
127918  if( SQLITE_OK==rc ){
127919    rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0);
127920  }
127921#ifdef SQLITE_TEST
127922  if( SQLITE_OK==rc ){
127923    rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
127924  }
127925  if( SQLITE_OK==rc ){
127926    rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
127927  }
127928#endif
127929
127930#ifdef SQLITE_TEST
127931  sqlite3_free(zTest);
127932  sqlite3_free(zTest2);
127933#endif
127934
127935  return rc;
127936}
127937
127938#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
127939
127940/************** End of fts3_tokenizer.c **************************************/
127941/************** Begin file fts3_tokenizer1.c *********************************/
127942/*
127943** 2006 Oct 10
127944**
127945** The author disclaims copyright to this source code.  In place of
127946** a legal notice, here is a blessing:
127947**
127948**    May you do good and not evil.
127949**    May you find forgiveness for yourself and forgive others.
127950**    May you share freely, never taking more than you give.
127951**
127952******************************************************************************
127953**
127954** Implementation of the "simple" full-text-search tokenizer.
127955*/
127956
127957/*
127958** The code in this file is only compiled if:
127959**
127960**     * The FTS3 module is being built as an extension
127961**       (in which case SQLITE_CORE is not defined), or
127962**
127963**     * The FTS3 module is being built into the core of
127964**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
127965*/
127966#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
127967
127968/* #include <assert.h> */
127969/* #include <stdlib.h> */
127970/* #include <stdio.h> */
127971/* #include <string.h> */
127972
127973
127974typedef struct simple_tokenizer {
127975  sqlite3_tokenizer base;
127976  char delim[128];             /* flag ASCII delimiters */
127977} simple_tokenizer;
127978
127979typedef struct simple_tokenizer_cursor {
127980  sqlite3_tokenizer_cursor base;
127981  const char *pInput;          /* input we are tokenizing */
127982  int nBytes;                  /* size of the input */
127983  int iOffset;                 /* current position in pInput */
127984  int iToken;                  /* index of next token to be returned */
127985  char *pToken;                /* storage for current token */
127986  int nTokenAllocated;         /* space allocated to zToken buffer */
127987} simple_tokenizer_cursor;
127988
127989
127990static int simpleDelim(simple_tokenizer *t, unsigned char c){
127991  return c<0x80 && t->delim[c];
127992}
127993static int fts3_isalnum(int x){
127994  return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
127995}
127996
127997/*
127998** Create a new tokenizer instance.
127999*/
128000static int simpleCreate(
128001  int argc, const char * const *argv,
128002  sqlite3_tokenizer **ppTokenizer
128003){
128004  simple_tokenizer *t;
128005
128006  t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
128007  if( t==NULL ) return SQLITE_NOMEM;
128008  memset(t, 0, sizeof(*t));
128009
128010  /* TODO(shess) Delimiters need to remain the same from run to run,
128011  ** else we need to reindex.  One solution would be a meta-table to
128012  ** track such information in the database, then we'd only want this
128013  ** information on the initial create.
128014  */
128015  if( argc>1 ){
128016    int i, n = (int)strlen(argv[1]);
128017    for(i=0; i<n; i++){
128018      unsigned char ch = argv[1][i];
128019      /* We explicitly don't support UTF-8 delimiters for now. */
128020      if( ch>=0x80 ){
128021        sqlite3_free(t);
128022        return SQLITE_ERROR;
128023      }
128024      t->delim[ch] = 1;
128025    }
128026  } else {
128027    /* Mark non-alphanumeric ASCII characters as delimiters */
128028    int i;
128029    for(i=1; i<0x80; i++){
128030      t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
128031    }
128032  }
128033
128034  *ppTokenizer = &t->base;
128035  return SQLITE_OK;
128036}
128037
128038/*
128039** Destroy a tokenizer
128040*/
128041static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
128042  sqlite3_free(pTokenizer);
128043  return SQLITE_OK;
128044}
128045
128046/*
128047** Prepare to begin tokenizing a particular string.  The input
128048** string to be tokenized is pInput[0..nBytes-1].  A cursor
128049** used to incrementally tokenize this string is returned in
128050** *ppCursor.
128051*/
128052static int simpleOpen(
128053  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
128054  const char *pInput, int nBytes,        /* String to be tokenized */
128055  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
128056){
128057  simple_tokenizer_cursor *c;
128058
128059  UNUSED_PARAMETER(pTokenizer);
128060
128061  c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
128062  if( c==NULL ) return SQLITE_NOMEM;
128063
128064  c->pInput = pInput;
128065  if( pInput==0 ){
128066    c->nBytes = 0;
128067  }else if( nBytes<0 ){
128068    c->nBytes = (int)strlen(pInput);
128069  }else{
128070    c->nBytes = nBytes;
128071  }
128072  c->iOffset = 0;                 /* start tokenizing at the beginning */
128073  c->iToken = 0;
128074  c->pToken = NULL;               /* no space allocated, yet. */
128075  c->nTokenAllocated = 0;
128076
128077  *ppCursor = &c->base;
128078  return SQLITE_OK;
128079}
128080
128081/*
128082** Close a tokenization cursor previously opened by a call to
128083** simpleOpen() above.
128084*/
128085static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
128086  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
128087  sqlite3_free(c->pToken);
128088  sqlite3_free(c);
128089  return SQLITE_OK;
128090}
128091
128092/*
128093** Extract the next token from a tokenization cursor.  The cursor must
128094** have been opened by a prior call to simpleOpen().
128095*/
128096static int simpleNext(
128097  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
128098  const char **ppToken,               /* OUT: *ppToken is the token text */
128099  int *pnBytes,                       /* OUT: Number of bytes in token */
128100  int *piStartOffset,                 /* OUT: Starting offset of token */
128101  int *piEndOffset,                   /* OUT: Ending offset of token */
128102  int *piPosition                     /* OUT: Position integer of token */
128103){
128104  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
128105  simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
128106  unsigned char *p = (unsigned char *)c->pInput;
128107
128108  while( c->iOffset<c->nBytes ){
128109    int iStartOffset;
128110
128111    /* Scan past delimiter characters */
128112    while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
128113      c->iOffset++;
128114    }
128115
128116    /* Count non-delimiter characters. */
128117    iStartOffset = c->iOffset;
128118    while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
128119      c->iOffset++;
128120    }
128121
128122    if( c->iOffset>iStartOffset ){
128123      int i, n = c->iOffset-iStartOffset;
128124      if( n>c->nTokenAllocated ){
128125        char *pNew;
128126        c->nTokenAllocated = n+20;
128127        pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
128128        if( !pNew ) return SQLITE_NOMEM;
128129        c->pToken = pNew;
128130      }
128131      for(i=0; i<n; i++){
128132        /* TODO(shess) This needs expansion to handle UTF-8
128133        ** case-insensitivity.
128134        */
128135        unsigned char ch = p[iStartOffset+i];
128136        c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
128137      }
128138      *ppToken = c->pToken;
128139      *pnBytes = n;
128140      *piStartOffset = iStartOffset;
128141      *piEndOffset = c->iOffset;
128142      *piPosition = c->iToken++;
128143
128144      return SQLITE_OK;
128145    }
128146  }
128147  return SQLITE_DONE;
128148}
128149
128150/*
128151** The set of routines that implement the simple tokenizer
128152*/
128153static const sqlite3_tokenizer_module simpleTokenizerModule = {
128154  0,
128155  simpleCreate,
128156  simpleDestroy,
128157  simpleOpen,
128158  simpleClose,
128159  simpleNext,
128160  0,
128161};
128162
128163/*
128164** Allocate a new simple tokenizer.  Return a pointer to the new
128165** tokenizer in *ppModule
128166*/
128167SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
128168  sqlite3_tokenizer_module const**ppModule
128169){
128170  *ppModule = &simpleTokenizerModule;
128171}
128172
128173#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
128174
128175/************** End of fts3_tokenizer1.c *************************************/
128176/************** Begin file fts3_tokenize_vtab.c ******************************/
128177/*
128178** 2013 Apr 22
128179**
128180** The author disclaims copyright to this source code.  In place of
128181** a legal notice, here is a blessing:
128182**
128183**    May you do good and not evil.
128184**    May you find forgiveness for yourself and forgive others.
128185**    May you share freely, never taking more than you give.
128186**
128187******************************************************************************
128188**
128189** This file contains code for the "fts3tokenize" virtual table module.
128190** An fts3tokenize virtual table is created as follows:
128191**
128192**   CREATE VIRTUAL TABLE <tbl> USING fts3tokenize(
128193**       <tokenizer-name>, <arg-1>, ...
128194**   );
128195**
128196** The table created has the following schema:
128197**
128198**   CREATE TABLE <tbl>(input, token, start, end, position)
128199**
128200** When queried, the query must include a WHERE clause of type:
128201**
128202**   input = <string>
128203**
128204** The virtual table module tokenizes this <string>, using the FTS3
128205** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE
128206** statement and returns one row for each token in the result. With
128207** fields set as follows:
128208**
128209**   input:   Always set to a copy of <string>
128210**   token:   A token from the input.
128211**   start:   Byte offset of the token within the input <string>.
128212**   end:     Byte offset of the byte immediately following the end of the
128213**            token within the input string.
128214**   pos:     Token offset of token within input.
128215**
128216*/
128217#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
128218
128219/* #include <string.h> */
128220/* #include <assert.h> */
128221
128222typedef struct Fts3tokTable Fts3tokTable;
128223typedef struct Fts3tokCursor Fts3tokCursor;
128224
128225/*
128226** Virtual table structure.
128227*/
128228struct Fts3tokTable {
128229  sqlite3_vtab base;              /* Base class used by SQLite core */
128230  const sqlite3_tokenizer_module *pMod;
128231  sqlite3_tokenizer *pTok;
128232};
128233
128234/*
128235** Virtual table cursor structure.
128236*/
128237struct Fts3tokCursor {
128238  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
128239  char *zInput;                   /* Input string */
128240  sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */
128241  int iRowid;                     /* Current 'rowid' value */
128242  const char *zToken;             /* Current 'token' value */
128243  int nToken;                     /* Size of zToken in bytes */
128244  int iStart;                     /* Current 'start' value */
128245  int iEnd;                       /* Current 'end' value */
128246  int iPos;                       /* Current 'pos' value */
128247};
128248
128249/*
128250** Query FTS for the tokenizer implementation named zName.
128251*/
128252static int fts3tokQueryTokenizer(
128253  Fts3Hash *pHash,
128254  const char *zName,
128255  const sqlite3_tokenizer_module **pp,
128256  char **pzErr
128257){
128258  sqlite3_tokenizer_module *p;
128259  int nName = (int)strlen(zName);
128260
128261  p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
128262  if( !p ){
128263    *pzErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
128264    return SQLITE_ERROR;
128265  }
128266
128267  *pp = p;
128268  return SQLITE_OK;
128269}
128270
128271/*
128272** The second argument, argv[], is an array of pointers to nul-terminated
128273** strings. This function makes a copy of the array and strings into a
128274** single block of memory. It then dequotes any of the strings that appear
128275** to be quoted.
128276**
128277** If successful, output parameter *pazDequote is set to point at the
128278** array of dequoted strings and SQLITE_OK is returned. The caller is
128279** responsible for eventually calling sqlite3_free() to free the array
128280** in this case. Or, if an error occurs, an SQLite error code is returned.
128281** The final value of *pazDequote is undefined in this case.
128282*/
128283static int fts3tokDequoteArray(
128284  int argc,                       /* Number of elements in argv[] */
128285  const char * const *argv,       /* Input array */
128286  char ***pazDequote              /* Output array */
128287){
128288  int rc = SQLITE_OK;             /* Return code */
128289  if( argc==0 ){
128290    *pazDequote = 0;
128291  }else{
128292    int i;
128293    int nByte = 0;
128294    char **azDequote;
128295
128296    for(i=0; i<argc; i++){
128297      nByte += (int)(strlen(argv[i]) + 1);
128298    }
128299
128300    *pazDequote = azDequote = sqlite3_malloc(sizeof(char *)*argc + nByte);
128301    if( azDequote==0 ){
128302      rc = SQLITE_NOMEM;
128303    }else{
128304      char *pSpace = (char *)&azDequote[argc];
128305      for(i=0; i<argc; i++){
128306        int n = (int)strlen(argv[i]);
128307        azDequote[i] = pSpace;
128308        memcpy(pSpace, argv[i], n+1);
128309        sqlite3Fts3Dequote(pSpace);
128310        pSpace += (n+1);
128311      }
128312    }
128313  }
128314
128315  return rc;
128316}
128317
128318/*
128319** Schema of the tokenizer table.
128320*/
128321#define FTS3_TOK_SCHEMA "CREATE TABLE x(input, token, start, end, position)"
128322
128323/*
128324** This function does all the work for both the xConnect and xCreate methods.
128325** These tables have no persistent representation of their own, so xConnect
128326** and xCreate are identical operations.
128327**
128328**   argv[0]: module name
128329**   argv[1]: database name
128330**   argv[2]: table name
128331**   argv[3]: first argument (tokenizer name)
128332*/
128333static int fts3tokConnectMethod(
128334  sqlite3 *db,                    /* Database connection */
128335  void *pHash,                    /* Hash table of tokenizers */
128336  int argc,                       /* Number of elements in argv array */
128337  const char * const *argv,       /* xCreate/xConnect argument array */
128338  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
128339  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
128340){
128341  Fts3tokTable *pTab;
128342  const sqlite3_tokenizer_module *pMod = 0;
128343  sqlite3_tokenizer *pTok = 0;
128344  int rc;
128345  char **azDequote = 0;
128346  int nDequote;
128347
128348  rc = sqlite3_declare_vtab(db, FTS3_TOK_SCHEMA);
128349  if( rc!=SQLITE_OK ) return rc;
128350
128351  nDequote = argc-3;
128352  rc = fts3tokDequoteArray(nDequote, &argv[3], &azDequote);
128353
128354  if( rc==SQLITE_OK ){
128355    const char *zModule;
128356    if( nDequote<1 ){
128357      zModule = "simple";
128358    }else{
128359      zModule = azDequote[0];
128360    }
128361    rc = fts3tokQueryTokenizer((Fts3Hash*)pHash, zModule, &pMod, pzErr);
128362  }
128363
128364  assert( (rc==SQLITE_OK)==(pMod!=0) );
128365  if( rc==SQLITE_OK ){
128366    const char * const *azArg = (const char * const *)&azDequote[1];
128367    rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok);
128368  }
128369
128370  if( rc==SQLITE_OK ){
128371    pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable));
128372    if( pTab==0 ){
128373      rc = SQLITE_NOMEM;
128374    }
128375  }
128376
128377  if( rc==SQLITE_OK ){
128378    memset(pTab, 0, sizeof(Fts3tokTable));
128379    pTab->pMod = pMod;
128380    pTab->pTok = pTok;
128381    *ppVtab = &pTab->base;
128382  }else{
128383    if( pTok ){
128384      pMod->xDestroy(pTok);
128385    }
128386  }
128387
128388  sqlite3_free(azDequote);
128389  return rc;
128390}
128391
128392/*
128393** This function does the work for both the xDisconnect and xDestroy methods.
128394** These tables have no persistent representation of their own, so xDisconnect
128395** and xDestroy are identical operations.
128396*/
128397static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){
128398  Fts3tokTable *pTab = (Fts3tokTable *)pVtab;
128399
128400  pTab->pMod->xDestroy(pTab->pTok);
128401  sqlite3_free(pTab);
128402  return SQLITE_OK;
128403}
128404
128405/*
128406** xBestIndex - Analyze a WHERE and ORDER BY clause.
128407*/
128408static int fts3tokBestIndexMethod(
128409  sqlite3_vtab *pVTab,
128410  sqlite3_index_info *pInfo
128411){
128412  int i;
128413  UNUSED_PARAMETER(pVTab);
128414
128415  for(i=0; i<pInfo->nConstraint; i++){
128416    if( pInfo->aConstraint[i].usable
128417     && pInfo->aConstraint[i].iColumn==0
128418     && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ
128419    ){
128420      pInfo->idxNum = 1;
128421      pInfo->aConstraintUsage[i].argvIndex = 1;
128422      pInfo->aConstraintUsage[i].omit = 1;
128423      pInfo->estimatedCost = 1;
128424      return SQLITE_OK;
128425    }
128426  }
128427
128428  pInfo->idxNum = 0;
128429  assert( pInfo->estimatedCost>1000000.0 );
128430
128431  return SQLITE_OK;
128432}
128433
128434/*
128435** xOpen - Open a cursor.
128436*/
128437static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
128438  Fts3tokCursor *pCsr;
128439  UNUSED_PARAMETER(pVTab);
128440
128441  pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor));
128442  if( pCsr==0 ){
128443    return SQLITE_NOMEM;
128444  }
128445  memset(pCsr, 0, sizeof(Fts3tokCursor));
128446
128447  *ppCsr = (sqlite3_vtab_cursor *)pCsr;
128448  return SQLITE_OK;
128449}
128450
128451/*
128452** Reset the tokenizer cursor passed as the only argument. As if it had
128453** just been returned by fts3tokOpenMethod().
128454*/
128455static void fts3tokResetCursor(Fts3tokCursor *pCsr){
128456  if( pCsr->pCsr ){
128457    Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab);
128458    pTab->pMod->xClose(pCsr->pCsr);
128459    pCsr->pCsr = 0;
128460  }
128461  sqlite3_free(pCsr->zInput);
128462  pCsr->zInput = 0;
128463  pCsr->zToken = 0;
128464  pCsr->nToken = 0;
128465  pCsr->iStart = 0;
128466  pCsr->iEnd = 0;
128467  pCsr->iPos = 0;
128468  pCsr->iRowid = 0;
128469}
128470
128471/*
128472** xClose - Close a cursor.
128473*/
128474static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){
128475  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
128476
128477  fts3tokResetCursor(pCsr);
128478  sqlite3_free(pCsr);
128479  return SQLITE_OK;
128480}
128481
128482/*
128483** xNext - Advance the cursor to the next row, if any.
128484*/
128485static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){
128486  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
128487  Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
128488  int rc;                         /* Return code */
128489
128490  pCsr->iRowid++;
128491  rc = pTab->pMod->xNext(pCsr->pCsr,
128492      &pCsr->zToken, &pCsr->nToken,
128493      &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos
128494  );
128495
128496  if( rc!=SQLITE_OK ){
128497    fts3tokResetCursor(pCsr);
128498    if( rc==SQLITE_DONE ) rc = SQLITE_OK;
128499  }
128500
128501  return rc;
128502}
128503
128504/*
128505** xFilter - Initialize a cursor to point at the start of its data.
128506*/
128507static int fts3tokFilterMethod(
128508  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
128509  int idxNum,                     /* Strategy index */
128510  const char *idxStr,             /* Unused */
128511  int nVal,                       /* Number of elements in apVal */
128512  sqlite3_value **apVal           /* Arguments for the indexing scheme */
128513){
128514  int rc = SQLITE_ERROR;
128515  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
128516  Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
128517  UNUSED_PARAMETER(idxStr);
128518  UNUSED_PARAMETER(nVal);
128519
128520  fts3tokResetCursor(pCsr);
128521  if( idxNum==1 ){
128522    const char *zByte = (const char *)sqlite3_value_text(apVal[0]);
128523    int nByte = sqlite3_value_bytes(apVal[0]);
128524    pCsr->zInput = sqlite3_malloc(nByte+1);
128525    if( pCsr->zInput==0 ){
128526      rc = SQLITE_NOMEM;
128527    }else{
128528      memcpy(pCsr->zInput, zByte, nByte);
128529      pCsr->zInput[nByte] = 0;
128530      rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr);
128531      if( rc==SQLITE_OK ){
128532        pCsr->pCsr->pTokenizer = pTab->pTok;
128533      }
128534    }
128535  }
128536
128537  if( rc!=SQLITE_OK ) return rc;
128538  return fts3tokNextMethod(pCursor);
128539}
128540
128541/*
128542** xEof - Return true if the cursor is at EOF, or false otherwise.
128543*/
128544static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){
128545  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
128546  return (pCsr->zToken==0);
128547}
128548
128549/*
128550** xColumn - Return a column value.
128551*/
128552static int fts3tokColumnMethod(
128553  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
128554  sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
128555  int iCol                        /* Index of column to read value from */
128556){
128557  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
128558
128559  /* CREATE TABLE x(input, token, start, end, position) */
128560  switch( iCol ){
128561    case 0:
128562      sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT);
128563      break;
128564    case 1:
128565      sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT);
128566      break;
128567    case 2:
128568      sqlite3_result_int(pCtx, pCsr->iStart);
128569      break;
128570    case 3:
128571      sqlite3_result_int(pCtx, pCsr->iEnd);
128572      break;
128573    default:
128574      assert( iCol==4 );
128575      sqlite3_result_int(pCtx, pCsr->iPos);
128576      break;
128577  }
128578  return SQLITE_OK;
128579}
128580
128581/*
128582** xRowid - Return the current rowid for the cursor.
128583*/
128584static int fts3tokRowidMethod(
128585  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
128586  sqlite_int64 *pRowid            /* OUT: Rowid value */
128587){
128588  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
128589  *pRowid = (sqlite3_int64)pCsr->iRowid;
128590  return SQLITE_OK;
128591}
128592
128593/*
128594** Register the fts3tok module with database connection db. Return SQLITE_OK
128595** if successful or an error code if sqlite3_create_module() fails.
128596*/
128597SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
128598  static const sqlite3_module fts3tok_module = {
128599     0,                           /* iVersion      */
128600     fts3tokConnectMethod,        /* xCreate       */
128601     fts3tokConnectMethod,        /* xConnect      */
128602     fts3tokBestIndexMethod,      /* xBestIndex    */
128603     fts3tokDisconnectMethod,     /* xDisconnect   */
128604     fts3tokDisconnectMethod,     /* xDestroy      */
128605     fts3tokOpenMethod,           /* xOpen         */
128606     fts3tokCloseMethod,          /* xClose        */
128607     fts3tokFilterMethod,         /* xFilter       */
128608     fts3tokNextMethod,           /* xNext         */
128609     fts3tokEofMethod,            /* xEof          */
128610     fts3tokColumnMethod,         /* xColumn       */
128611     fts3tokRowidMethod,          /* xRowid        */
128612     0,                           /* xUpdate       */
128613     0,                           /* xBegin        */
128614     0,                           /* xSync         */
128615     0,                           /* xCommit       */
128616     0,                           /* xRollback     */
128617     0,                           /* xFindFunction */
128618     0,                           /* xRename       */
128619     0,                           /* xSavepoint    */
128620     0,                           /* xRelease      */
128621     0                            /* xRollbackTo   */
128622  };
128623  int rc;                         /* Return code */
128624
128625  rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash);
128626  return rc;
128627}
128628
128629#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
128630
128631/************** End of fts3_tokenize_vtab.c **********************************/
128632/************** Begin file fts3_write.c **************************************/
128633/*
128634** 2009 Oct 23
128635**
128636** The author disclaims copyright to this source code.  In place of
128637** a legal notice, here is a blessing:
128638**
128639**    May you do good and not evil.
128640**    May you find forgiveness for yourself and forgive others.
128641**    May you share freely, never taking more than you give.
128642**
128643******************************************************************************
128644**
128645** This file is part of the SQLite FTS3 extension module. Specifically,
128646** this file contains code to insert, update and delete rows from FTS3
128647** tables. It also contains code to merge FTS3 b-tree segments. Some
128648** of the sub-routines used to merge segments are also used by the query
128649** code in fts3.c.
128650*/
128651
128652#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
128653
128654/* #include <string.h> */
128655/* #include <assert.h> */
128656/* #include <stdlib.h> */
128657
128658
128659#define FTS_MAX_APPENDABLE_HEIGHT 16
128660
128661/*
128662** When full-text index nodes are loaded from disk, the buffer that they
128663** are loaded into has the following number of bytes of padding at the end
128664** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
128665** of 920 bytes is allocated for it.
128666**
128667** This means that if we have a pointer into a buffer containing node data,
128668** it is always safe to read up to two varints from it without risking an
128669** overread, even if the node data is corrupted.
128670*/
128671#define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
128672
128673/*
128674** Under certain circumstances, b-tree nodes (doclists) can be loaded into
128675** memory incrementally instead of all at once. This can be a big performance
128676** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
128677** method before retrieving all query results (as may happen, for example,
128678** if a query has a LIMIT clause).
128679**
128680** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
128681** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
128682** The code is written so that the hard lower-limit for each of these values
128683** is 1. Clearly such small values would be inefficient, but can be useful
128684** for testing purposes.
128685**
128686** If this module is built with SQLITE_TEST defined, these constants may
128687** be overridden at runtime for testing purposes. File fts3_test.c contains
128688** a Tcl interface to read and write the values.
128689*/
128690#ifdef SQLITE_TEST
128691int test_fts3_node_chunksize = (4*1024);
128692int test_fts3_node_chunk_threshold = (4*1024)*4;
128693# define FTS3_NODE_CHUNKSIZE       test_fts3_node_chunksize
128694# define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
128695#else
128696# define FTS3_NODE_CHUNKSIZE (4*1024)
128697# define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
128698#endif
128699
128700/*
128701** The two values that may be meaningfully bound to the :1 parameter in
128702** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
128703*/
128704#define FTS_STAT_DOCTOTAL      0
128705#define FTS_STAT_INCRMERGEHINT 1
128706#define FTS_STAT_AUTOINCRMERGE 2
128707
128708/*
128709** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
128710** and incremental merge operation that takes place. This is used for
128711** debugging FTS only, it should not usually be turned on in production
128712** systems.
128713*/
128714#ifdef FTS3_LOG_MERGES
128715static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
128716  sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
128717}
128718#else
128719#define fts3LogMerge(x, y)
128720#endif
128721
128722
128723typedef struct PendingList PendingList;
128724typedef struct SegmentNode SegmentNode;
128725typedef struct SegmentWriter SegmentWriter;
128726
128727/*
128728** An instance of the following data structure is used to build doclists
128729** incrementally. See function fts3PendingListAppend() for details.
128730*/
128731struct PendingList {
128732  int nData;
128733  char *aData;
128734  int nSpace;
128735  sqlite3_int64 iLastDocid;
128736  sqlite3_int64 iLastCol;
128737  sqlite3_int64 iLastPos;
128738};
128739
128740
128741/*
128742** Each cursor has a (possibly empty) linked list of the following objects.
128743*/
128744struct Fts3DeferredToken {
128745  Fts3PhraseToken *pToken;        /* Pointer to corresponding expr token */
128746  int iCol;                       /* Column token must occur in */
128747  Fts3DeferredToken *pNext;       /* Next in list of deferred tokens */
128748  PendingList *pList;             /* Doclist is assembled here */
128749};
128750
128751/*
128752** An instance of this structure is used to iterate through the terms on
128753** a contiguous set of segment b-tree leaf nodes. Although the details of
128754** this structure are only manipulated by code in this file, opaque handles
128755** of type Fts3SegReader* are also used by code in fts3.c to iterate through
128756** terms when querying the full-text index. See functions:
128757**
128758**   sqlite3Fts3SegReaderNew()
128759**   sqlite3Fts3SegReaderFree()
128760**   sqlite3Fts3SegReaderIterate()
128761**
128762** Methods used to manipulate Fts3SegReader structures:
128763**
128764**   fts3SegReaderNext()
128765**   fts3SegReaderFirstDocid()
128766**   fts3SegReaderNextDocid()
128767*/
128768struct Fts3SegReader {
128769  int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */
128770  u8 bLookup;                     /* True for a lookup only */
128771  u8 rootOnly;                    /* True for a root-only reader */
128772
128773  sqlite3_int64 iStartBlock;      /* Rowid of first leaf block to traverse */
128774  sqlite3_int64 iLeafEndBlock;    /* Rowid of final leaf block to traverse */
128775  sqlite3_int64 iEndBlock;        /* Rowid of final block in segment (or 0) */
128776  sqlite3_int64 iCurrentBlock;    /* Current leaf block (or 0) */
128777
128778  char *aNode;                    /* Pointer to node data (or NULL) */
128779  int nNode;                      /* Size of buffer at aNode (or 0) */
128780  int nPopulate;                  /* If >0, bytes of buffer aNode[] loaded */
128781  sqlite3_blob *pBlob;            /* If not NULL, blob handle to read node */
128782
128783  Fts3HashElem **ppNextElem;
128784
128785  /* Variables set by fts3SegReaderNext(). These may be read directly
128786  ** by the caller. They are valid from the time SegmentReaderNew() returns
128787  ** until SegmentReaderNext() returns something other than SQLITE_OK
128788  ** (i.e. SQLITE_DONE).
128789  */
128790  int nTerm;                      /* Number of bytes in current term */
128791  char *zTerm;                    /* Pointer to current term */
128792  int nTermAlloc;                 /* Allocated size of zTerm buffer */
128793  char *aDoclist;                 /* Pointer to doclist of current entry */
128794  int nDoclist;                   /* Size of doclist in current entry */
128795
128796  /* The following variables are used by fts3SegReaderNextDocid() to iterate
128797  ** through the current doclist (aDoclist/nDoclist).
128798  */
128799  char *pOffsetList;
128800  int nOffsetList;                /* For descending pending seg-readers only */
128801  sqlite3_int64 iDocid;
128802};
128803
128804#define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
128805#define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
128806
128807/*
128808** An instance of this structure is used to create a segment b-tree in the
128809** database. The internal details of this type are only accessed by the
128810** following functions:
128811**
128812**   fts3SegWriterAdd()
128813**   fts3SegWriterFlush()
128814**   fts3SegWriterFree()
128815*/
128816struct SegmentWriter {
128817  SegmentNode *pTree;             /* Pointer to interior tree structure */
128818  sqlite3_int64 iFirst;           /* First slot in %_segments written */
128819  sqlite3_int64 iFree;            /* Next free slot in %_segments */
128820  char *zTerm;                    /* Pointer to previous term buffer */
128821  int nTerm;                      /* Number of bytes in zTerm */
128822  int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
128823  char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
128824  int nSize;                      /* Size of allocation at aData */
128825  int nData;                      /* Bytes of data in aData */
128826  char *aData;                    /* Pointer to block from malloc() */
128827};
128828
128829/*
128830** Type SegmentNode is used by the following three functions to create
128831** the interior part of the segment b+-tree structures (everything except
128832** the leaf nodes). These functions and type are only ever used by code
128833** within the fts3SegWriterXXX() family of functions described above.
128834**
128835**   fts3NodeAddTerm()
128836**   fts3NodeWrite()
128837**   fts3NodeFree()
128838**
128839** When a b+tree is written to the database (either as a result of a merge
128840** or the pending-terms table being flushed), leaves are written into the
128841** database file as soon as they are completely populated. The interior of
128842** the tree is assembled in memory and written out only once all leaves have
128843** been populated and stored. This is Ok, as the b+-tree fanout is usually
128844** very large, meaning that the interior of the tree consumes relatively
128845** little memory.
128846*/
128847struct SegmentNode {
128848  SegmentNode *pParent;           /* Parent node (or NULL for root node) */
128849  SegmentNode *pRight;            /* Pointer to right-sibling */
128850  SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */
128851  int nEntry;                     /* Number of terms written to node so far */
128852  char *zTerm;                    /* Pointer to previous term buffer */
128853  int nTerm;                      /* Number of bytes in zTerm */
128854  int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
128855  char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
128856  int nData;                      /* Bytes of valid data so far */
128857  char *aData;                    /* Node data */
128858};
128859
128860/*
128861** Valid values for the second argument to fts3SqlStmt().
128862*/
128863#define SQL_DELETE_CONTENT             0
128864#define SQL_IS_EMPTY                   1
128865#define SQL_DELETE_ALL_CONTENT         2
128866#define SQL_DELETE_ALL_SEGMENTS        3
128867#define SQL_DELETE_ALL_SEGDIR          4
128868#define SQL_DELETE_ALL_DOCSIZE         5
128869#define SQL_DELETE_ALL_STAT            6
128870#define SQL_SELECT_CONTENT_BY_ROWID    7
128871#define SQL_NEXT_SEGMENT_INDEX         8
128872#define SQL_INSERT_SEGMENTS            9
128873#define SQL_NEXT_SEGMENTS_ID          10
128874#define SQL_INSERT_SEGDIR             11
128875#define SQL_SELECT_LEVEL              12
128876#define SQL_SELECT_LEVEL_RANGE        13
128877#define SQL_SELECT_LEVEL_COUNT        14
128878#define SQL_SELECT_SEGDIR_MAX_LEVEL   15
128879#define SQL_DELETE_SEGDIR_LEVEL       16
128880#define SQL_DELETE_SEGMENTS_RANGE     17
128881#define SQL_CONTENT_INSERT            18
128882#define SQL_DELETE_DOCSIZE            19
128883#define SQL_REPLACE_DOCSIZE           20
128884#define SQL_SELECT_DOCSIZE            21
128885#define SQL_SELECT_STAT               22
128886#define SQL_REPLACE_STAT              23
128887
128888#define SQL_SELECT_ALL_PREFIX_LEVEL   24
128889#define SQL_DELETE_ALL_TERMS_SEGDIR   25
128890#define SQL_DELETE_SEGDIR_RANGE       26
128891#define SQL_SELECT_ALL_LANGID         27
128892#define SQL_FIND_MERGE_LEVEL          28
128893#define SQL_MAX_LEAF_NODE_ESTIMATE    29
128894#define SQL_DELETE_SEGDIR_ENTRY       30
128895#define SQL_SHIFT_SEGDIR_ENTRY        31
128896#define SQL_SELECT_SEGDIR             32
128897#define SQL_CHOMP_SEGDIR              33
128898#define SQL_SEGMENT_IS_APPENDABLE     34
128899#define SQL_SELECT_INDEXES            35
128900#define SQL_SELECT_MXLEVEL            36
128901
128902/*
128903** This function is used to obtain an SQLite prepared statement handle
128904** for the statement identified by the second argument. If successful,
128905** *pp is set to the requested statement handle and SQLITE_OK returned.
128906** Otherwise, an SQLite error code is returned and *pp is set to 0.
128907**
128908** If argument apVal is not NULL, then it must point to an array with
128909** at least as many entries as the requested statement has bound
128910** parameters. The values are bound to the statements parameters before
128911** returning.
128912*/
128913static int fts3SqlStmt(
128914  Fts3Table *p,                   /* Virtual table handle */
128915  int eStmt,                      /* One of the SQL_XXX constants above */
128916  sqlite3_stmt **pp,              /* OUT: Statement handle */
128917  sqlite3_value **apVal           /* Values to bind to statement */
128918){
128919  const char *azSql[] = {
128920/* 0  */  "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
128921/* 1  */  "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
128922/* 2  */  "DELETE FROM %Q.'%q_content'",
128923/* 3  */  "DELETE FROM %Q.'%q_segments'",
128924/* 4  */  "DELETE FROM %Q.'%q_segdir'",
128925/* 5  */  "DELETE FROM %Q.'%q_docsize'",
128926/* 6  */  "DELETE FROM %Q.'%q_stat'",
128927/* 7  */  "SELECT %s WHERE rowid=?",
128928/* 8  */  "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
128929/* 9  */  "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
128930/* 10 */  "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
128931/* 11 */  "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
128932
128933          /* Return segments in order from oldest to newest.*/
128934/* 12 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
128935            "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
128936/* 13 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
128937            "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
128938            "ORDER BY level DESC, idx ASC",
128939
128940/* 14 */  "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
128941/* 15 */  "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
128942
128943/* 16 */  "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
128944/* 17 */  "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
128945/* 18 */  "INSERT INTO %Q.'%q_content' VALUES(%s)",
128946/* 19 */  "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
128947/* 20 */  "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
128948/* 21 */  "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
128949/* 22 */  "SELECT value FROM %Q.'%q_stat' WHERE id=?",
128950/* 23 */  "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
128951/* 24 */  "",
128952/* 25 */  "",
128953
128954/* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
128955/* 27 */ "SELECT DISTINCT level / (1024 * ?) FROM %Q.'%q_segdir'",
128956
128957/* This statement is used to determine which level to read the input from
128958** when performing an incremental merge. It returns the absolute level number
128959** of the oldest level in the db that contains at least ? segments. Or,
128960** if no level in the FTS index contains more than ? segments, the statement
128961** returns zero rows.  */
128962/* 28 */ "SELECT level FROM %Q.'%q_segdir' GROUP BY level HAVING count(*)>=?"
128963         "  ORDER BY (level %% 1024) ASC LIMIT 1",
128964
128965/* Estimate the upper limit on the number of leaf nodes in a new segment
128966** created by merging the oldest :2 segments from absolute level :1. See
128967** function sqlite3Fts3Incrmerge() for details.  */
128968/* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
128969         "  FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
128970
128971/* SQL_DELETE_SEGDIR_ENTRY
128972**   Delete the %_segdir entry on absolute level :1 with index :2.  */
128973/* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
128974
128975/* SQL_SHIFT_SEGDIR_ENTRY
128976**   Modify the idx value for the segment with idx=:3 on absolute level :2
128977**   to :1.  */
128978/* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
128979
128980/* SQL_SELECT_SEGDIR
128981**   Read a single entry from the %_segdir table. The entry from absolute
128982**   level :1 with index value :2.  */
128983/* 32 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
128984            "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
128985
128986/* SQL_CHOMP_SEGDIR
128987**   Update the start_block (:1) and root (:2) fields of the %_segdir
128988**   entry located on absolute level :3 with index :4.  */
128989/* 33 */  "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
128990            "WHERE level = ? AND idx = ?",
128991
128992/* SQL_SEGMENT_IS_APPENDABLE
128993**   Return a single row if the segment with end_block=? is appendable. Or
128994**   no rows otherwise.  */
128995/* 34 */  "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
128996
128997/* SQL_SELECT_INDEXES
128998**   Return the list of valid segment indexes for absolute level ?  */
128999/* 35 */  "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
129000
129001/* SQL_SELECT_MXLEVEL
129002**   Return the largest relative level in the FTS index or indexes.  */
129003/* 36 */  "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'"
129004  };
129005  int rc = SQLITE_OK;
129006  sqlite3_stmt *pStmt;
129007
129008  assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
129009  assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
129010
129011  pStmt = p->aStmt[eStmt];
129012  if( !pStmt ){
129013    char *zSql;
129014    if( eStmt==SQL_CONTENT_INSERT ){
129015      zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
129016    }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
129017      zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
129018    }else{
129019      zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
129020    }
129021    if( !zSql ){
129022      rc = SQLITE_NOMEM;
129023    }else{
129024      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
129025      sqlite3_free(zSql);
129026      assert( rc==SQLITE_OK || pStmt==0 );
129027      p->aStmt[eStmt] = pStmt;
129028    }
129029  }
129030  if( apVal ){
129031    int i;
129032    int nParam = sqlite3_bind_parameter_count(pStmt);
129033    for(i=0; rc==SQLITE_OK && i<nParam; i++){
129034      rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
129035    }
129036  }
129037  *pp = pStmt;
129038  return rc;
129039}
129040
129041
129042static int fts3SelectDocsize(
129043  Fts3Table *pTab,                /* FTS3 table handle */
129044  sqlite3_int64 iDocid,           /* Docid to bind for SQL_SELECT_DOCSIZE */
129045  sqlite3_stmt **ppStmt           /* OUT: Statement handle */
129046){
129047  sqlite3_stmt *pStmt = 0;        /* Statement requested from fts3SqlStmt() */
129048  int rc;                         /* Return code */
129049
129050  rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
129051  if( rc==SQLITE_OK ){
129052    sqlite3_bind_int64(pStmt, 1, iDocid);
129053    rc = sqlite3_step(pStmt);
129054    if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
129055      rc = sqlite3_reset(pStmt);
129056      if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
129057      pStmt = 0;
129058    }else{
129059      rc = SQLITE_OK;
129060    }
129061  }
129062
129063  *ppStmt = pStmt;
129064  return rc;
129065}
129066
129067SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
129068  Fts3Table *pTab,                /* Fts3 table handle */
129069  sqlite3_stmt **ppStmt           /* OUT: Statement handle */
129070){
129071  sqlite3_stmt *pStmt = 0;
129072  int rc;
129073  rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
129074  if( rc==SQLITE_OK ){
129075    sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
129076    if( sqlite3_step(pStmt)!=SQLITE_ROW
129077     || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
129078    ){
129079      rc = sqlite3_reset(pStmt);
129080      if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
129081      pStmt = 0;
129082    }
129083  }
129084  *ppStmt = pStmt;
129085  return rc;
129086}
129087
129088SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
129089  Fts3Table *pTab,                /* Fts3 table handle */
129090  sqlite3_int64 iDocid,           /* Docid to read size data for */
129091  sqlite3_stmt **ppStmt           /* OUT: Statement handle */
129092){
129093  return fts3SelectDocsize(pTab, iDocid, ppStmt);
129094}
129095
129096/*
129097** Similar to fts3SqlStmt(). Except, after binding the parameters in
129098** array apVal[] to the SQL statement identified by eStmt, the statement
129099** is executed.
129100**
129101** Returns SQLITE_OK if the statement is successfully executed, or an
129102** SQLite error code otherwise.
129103*/
129104static void fts3SqlExec(
129105  int *pRC,                /* Result code */
129106  Fts3Table *p,            /* The FTS3 table */
129107  int eStmt,               /* Index of statement to evaluate */
129108  sqlite3_value **apVal    /* Parameters to bind */
129109){
129110  sqlite3_stmt *pStmt;
129111  int rc;
129112  if( *pRC ) return;
129113  rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
129114  if( rc==SQLITE_OK ){
129115    sqlite3_step(pStmt);
129116    rc = sqlite3_reset(pStmt);
129117  }
129118  *pRC = rc;
129119}
129120
129121
129122/*
129123** This function ensures that the caller has obtained a shared-cache
129124** table-lock on the %_content table. This is required before reading
129125** data from the fts3 table. If this lock is not acquired first, then
129126** the caller may end up holding read-locks on the %_segments and %_segdir
129127** tables, but no read-lock on the %_content table. If this happens
129128** a second connection will be able to write to the fts3 table, but
129129** attempting to commit those writes might return SQLITE_LOCKED or
129130** SQLITE_LOCKED_SHAREDCACHE (because the commit attempts to obtain
129131** write-locks on the %_segments and %_segdir ** tables).
129132**
129133** We try to avoid this because if FTS3 returns any error when committing
129134** a transaction, the whole transaction will be rolled back. And this is
129135** not what users expect when they get SQLITE_LOCKED_SHAREDCACHE. It can
129136** still happen if the user reads data directly from the %_segments or
129137** %_segdir tables instead of going through FTS3 though.
129138**
129139** This reasoning does not apply to a content=xxx table.
129140*/
129141SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *p){
129142  int rc;                         /* Return code */
129143  sqlite3_stmt *pStmt;            /* Statement used to obtain lock */
129144
129145  if( p->zContentTbl==0 ){
129146    rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pStmt, 0);
129147    if( rc==SQLITE_OK ){
129148      sqlite3_bind_null(pStmt, 1);
129149      sqlite3_step(pStmt);
129150      rc = sqlite3_reset(pStmt);
129151    }
129152  }else{
129153    rc = SQLITE_OK;
129154  }
129155
129156  return rc;
129157}
129158
129159/*
129160** FTS maintains a separate indexes for each language-id (a 32-bit integer).
129161** Within each language id, a separate index is maintained to store the
129162** document terms, and each configured prefix size (configured the FTS
129163** "prefix=" option). And each index consists of multiple levels ("relative
129164** levels").
129165**
129166** All three of these values (the language id, the specific index and the
129167** level within the index) are encoded in 64-bit integer values stored
129168** in the %_segdir table on disk. This function is used to convert three
129169** separate component values into the single 64-bit integer value that
129170** can be used to query the %_segdir table.
129171**
129172** Specifically, each language-id/index combination is allocated 1024
129173** 64-bit integer level values ("absolute levels"). The main terms index
129174** for language-id 0 is allocate values 0-1023. The first prefix index
129175** (if any) for language-id 0 is allocated values 1024-2047. And so on.
129176** Language 1 indexes are allocated immediately following language 0.
129177**
129178** So, for a system with nPrefix prefix indexes configured, the block of
129179** absolute levels that corresponds to language-id iLangid and index
129180** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
129181*/
129182static sqlite3_int64 getAbsoluteLevel(
129183  Fts3Table *p,                   /* FTS3 table handle */
129184  int iLangid,                    /* Language id */
129185  int iIndex,                     /* Index in p->aIndex[] */
129186  int iLevel                      /* Level of segments */
129187){
129188  sqlite3_int64 iBase;            /* First absolute level for iLangid/iIndex */
129189  assert( iLangid>=0 );
129190  assert( p->nIndex>0 );
129191  assert( iIndex>=0 && iIndex<p->nIndex );
129192
129193  iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
129194  return iBase + iLevel;
129195}
129196
129197/*
129198** Set *ppStmt to a statement handle that may be used to iterate through
129199** all rows in the %_segdir table, from oldest to newest. If successful,
129200** return SQLITE_OK. If an error occurs while preparing the statement,
129201** return an SQLite error code.
129202**
129203** There is only ever one instance of this SQL statement compiled for
129204** each FTS3 table.
129205**
129206** The statement returns the following columns from the %_segdir table:
129207**
129208**   0: idx
129209**   1: start_block
129210**   2: leaves_end_block
129211**   3: end_block
129212**   4: root
129213*/
129214SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
129215  Fts3Table *p,                   /* FTS3 table */
129216  int iLangid,                    /* Language being queried */
129217  int iIndex,                     /* Index for p->aIndex[] */
129218  int iLevel,                     /* Level to select (relative level) */
129219  sqlite3_stmt **ppStmt           /* OUT: Compiled statement */
129220){
129221  int rc;
129222  sqlite3_stmt *pStmt = 0;
129223
129224  assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
129225  assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
129226  assert( iIndex>=0 && iIndex<p->nIndex );
129227
129228  if( iLevel<0 ){
129229    /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
129230    rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
129231    if( rc==SQLITE_OK ){
129232      sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
129233      sqlite3_bind_int64(pStmt, 2,
129234          getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
129235      );
129236    }
129237  }else{
129238    /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
129239    rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
129240    if( rc==SQLITE_OK ){
129241      sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
129242    }
129243  }
129244  *ppStmt = pStmt;
129245  return rc;
129246}
129247
129248
129249/*
129250** Append a single varint to a PendingList buffer. SQLITE_OK is returned
129251** if successful, or an SQLite error code otherwise.
129252**
129253** This function also serves to allocate the PendingList structure itself.
129254** For example, to create a new PendingList structure containing two
129255** varints:
129256**
129257**   PendingList *p = 0;
129258**   fts3PendingListAppendVarint(&p, 1);
129259**   fts3PendingListAppendVarint(&p, 2);
129260*/
129261static int fts3PendingListAppendVarint(
129262  PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */
129263  sqlite3_int64 i                 /* Value to append to data */
129264){
129265  PendingList *p = *pp;
129266
129267  /* Allocate or grow the PendingList as required. */
129268  if( !p ){
129269    p = sqlite3_malloc(sizeof(*p) + 100);
129270    if( !p ){
129271      return SQLITE_NOMEM;
129272    }
129273    p->nSpace = 100;
129274    p->aData = (char *)&p[1];
129275    p->nData = 0;
129276  }
129277  else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
129278    int nNew = p->nSpace * 2;
129279    p = sqlite3_realloc(p, sizeof(*p) + nNew);
129280    if( !p ){
129281      sqlite3_free(*pp);
129282      *pp = 0;
129283      return SQLITE_NOMEM;
129284    }
129285    p->nSpace = nNew;
129286    p->aData = (char *)&p[1];
129287  }
129288
129289  /* Append the new serialized varint to the end of the list. */
129290  p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
129291  p->aData[p->nData] = '\0';
129292  *pp = p;
129293  return SQLITE_OK;
129294}
129295
129296/*
129297** Add a docid/column/position entry to a PendingList structure. Non-zero
129298** is returned if the structure is sqlite3_realloced as part of adding
129299** the entry. Otherwise, zero.
129300**
129301** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
129302** Zero is always returned in this case. Otherwise, if no OOM error occurs,
129303** it is set to SQLITE_OK.
129304*/
129305static int fts3PendingListAppend(
129306  PendingList **pp,               /* IN/OUT: PendingList structure */
129307  sqlite3_int64 iDocid,           /* Docid for entry to add */
129308  sqlite3_int64 iCol,             /* Column for entry to add */
129309  sqlite3_int64 iPos,             /* Position of term for entry to add */
129310  int *pRc                        /* OUT: Return code */
129311){
129312  PendingList *p = *pp;
129313  int rc = SQLITE_OK;
129314
129315  assert( !p || p->iLastDocid<=iDocid );
129316
129317  if( !p || p->iLastDocid!=iDocid ){
129318    sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
129319    if( p ){
129320      assert( p->nData<p->nSpace );
129321      assert( p->aData[p->nData]==0 );
129322      p->nData++;
129323    }
129324    if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
129325      goto pendinglistappend_out;
129326    }
129327    p->iLastCol = -1;
129328    p->iLastPos = 0;
129329    p->iLastDocid = iDocid;
129330  }
129331  if( iCol>0 && p->iLastCol!=iCol ){
129332    if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
129333     || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
129334    ){
129335      goto pendinglistappend_out;
129336    }
129337    p->iLastCol = iCol;
129338    p->iLastPos = 0;
129339  }
129340  if( iCol>=0 ){
129341    assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
129342    rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
129343    if( rc==SQLITE_OK ){
129344      p->iLastPos = iPos;
129345    }
129346  }
129347
129348 pendinglistappend_out:
129349  *pRc = rc;
129350  if( p!=*pp ){
129351    *pp = p;
129352    return 1;
129353  }
129354  return 0;
129355}
129356
129357/*
129358** Free a PendingList object allocated by fts3PendingListAppend().
129359*/
129360static void fts3PendingListDelete(PendingList *pList){
129361  sqlite3_free(pList);
129362}
129363
129364/*
129365** Add an entry to one of the pending-terms hash tables.
129366*/
129367static int fts3PendingTermsAddOne(
129368  Fts3Table *p,
129369  int iCol,
129370  int iPos,
129371  Fts3Hash *pHash,                /* Pending terms hash table to add entry to */
129372  const char *zToken,
129373  int nToken
129374){
129375  PendingList *pList;
129376  int rc = SQLITE_OK;
129377
129378  pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
129379  if( pList ){
129380    p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
129381  }
129382  if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
129383    if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
129384      /* Malloc failed while inserting the new entry. This can only
129385      ** happen if there was no previous entry for this token.
129386      */
129387      assert( 0==fts3HashFind(pHash, zToken, nToken) );
129388      sqlite3_free(pList);
129389      rc = SQLITE_NOMEM;
129390    }
129391  }
129392  if( rc==SQLITE_OK ){
129393    p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
129394  }
129395  return rc;
129396}
129397
129398/*
129399** Tokenize the nul-terminated string zText and add all tokens to the
129400** pending-terms hash-table. The docid used is that currently stored in
129401** p->iPrevDocid, and the column is specified by argument iCol.
129402**
129403** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
129404*/
129405static int fts3PendingTermsAdd(
129406  Fts3Table *p,                   /* Table into which text will be inserted */
129407  int iLangid,                    /* Language id to use */
129408  const char *zText,              /* Text of document to be inserted */
129409  int iCol,                       /* Column into which text is being inserted */
129410  u32 *pnWord                     /* IN/OUT: Incr. by number tokens inserted */
129411){
129412  int rc;
129413  int iStart = 0;
129414  int iEnd = 0;
129415  int iPos = 0;
129416  int nWord = 0;
129417
129418  char const *zToken;
129419  int nToken = 0;
129420
129421  sqlite3_tokenizer *pTokenizer = p->pTokenizer;
129422  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
129423  sqlite3_tokenizer_cursor *pCsr;
129424  int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
129425      const char**,int*,int*,int*,int*);
129426
129427  assert( pTokenizer && pModule );
129428
129429  /* If the user has inserted a NULL value, this function may be called with
129430  ** zText==0. In this case, add zero token entries to the hash table and
129431  ** return early. */
129432  if( zText==0 ){
129433    *pnWord = 0;
129434    return SQLITE_OK;
129435  }
129436
129437  rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
129438  if( rc!=SQLITE_OK ){
129439    return rc;
129440  }
129441
129442  xNext = pModule->xNext;
129443  while( SQLITE_OK==rc
129444      && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
129445  ){
129446    int i;
129447    if( iPos>=nWord ) nWord = iPos+1;
129448
129449    /* Positions cannot be negative; we use -1 as a terminator internally.
129450    ** Tokens must have a non-zero length.
129451    */
129452    if( iPos<0 || !zToken || nToken<=0 ){
129453      rc = SQLITE_ERROR;
129454      break;
129455    }
129456
129457    /* Add the term to the terms index */
129458    rc = fts3PendingTermsAddOne(
129459        p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
129460    );
129461
129462    /* Add the term to each of the prefix indexes that it is not too
129463    ** short for. */
129464    for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
129465      struct Fts3Index *pIndex = &p->aIndex[i];
129466      if( nToken<pIndex->nPrefix ) continue;
129467      rc = fts3PendingTermsAddOne(
129468          p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
129469      );
129470    }
129471  }
129472
129473  pModule->xClose(pCsr);
129474  *pnWord += nWord;
129475  return (rc==SQLITE_DONE ? SQLITE_OK : rc);
129476}
129477
129478/*
129479** Calling this function indicates that subsequent calls to
129480** fts3PendingTermsAdd() are to add term/position-list pairs for the
129481** contents of the document with docid iDocid.
129482*/
129483static int fts3PendingTermsDocid(
129484  Fts3Table *p,                   /* Full-text table handle */
129485  int iLangid,                    /* Language id of row being written */
129486  sqlite_int64 iDocid             /* Docid of row being written */
129487){
129488  assert( iLangid>=0 );
129489
129490  /* TODO(shess) Explore whether partially flushing the buffer on
129491  ** forced-flush would provide better performance.  I suspect that if
129492  ** we ordered the doclists by size and flushed the largest until the
129493  ** buffer was half empty, that would let the less frequent terms
129494  ** generate longer doclists.
129495  */
129496  if( iDocid<=p->iPrevDocid
129497   || p->iPrevLangid!=iLangid
129498   || p->nPendingData>p->nMaxPendingData
129499  ){
129500    int rc = sqlite3Fts3PendingTermsFlush(p);
129501    if( rc!=SQLITE_OK ) return rc;
129502  }
129503  p->iPrevDocid = iDocid;
129504  p->iPrevLangid = iLangid;
129505  return SQLITE_OK;
129506}
129507
129508/*
129509** Discard the contents of the pending-terms hash tables.
129510*/
129511SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
129512  int i;
129513  for(i=0; i<p->nIndex; i++){
129514    Fts3HashElem *pElem;
129515    Fts3Hash *pHash = &p->aIndex[i].hPending;
129516    for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
129517      PendingList *pList = (PendingList *)fts3HashData(pElem);
129518      fts3PendingListDelete(pList);
129519    }
129520    fts3HashClear(pHash);
129521  }
129522  p->nPendingData = 0;
129523}
129524
129525/*
129526** This function is called by the xUpdate() method as part of an INSERT
129527** operation. It adds entries for each term in the new record to the
129528** pendingTerms hash table.
129529**
129530** Argument apVal is the same as the similarly named argument passed to
129531** fts3InsertData(). Parameter iDocid is the docid of the new row.
129532*/
129533static int fts3InsertTerms(
129534  Fts3Table *p,
129535  int iLangid,
129536  sqlite3_value **apVal,
129537  u32 *aSz
129538){
129539  int i;                          /* Iterator variable */
129540  for(i=2; i<p->nColumn+2; i++){
129541    const char *zText = (const char *)sqlite3_value_text(apVal[i]);
129542    int rc = fts3PendingTermsAdd(p, iLangid, zText, i-2, &aSz[i-2]);
129543    if( rc!=SQLITE_OK ){
129544      return rc;
129545    }
129546    aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
129547  }
129548  return SQLITE_OK;
129549}
129550
129551/*
129552** This function is called by the xUpdate() method for an INSERT operation.
129553** The apVal parameter is passed a copy of the apVal argument passed by
129554** SQLite to the xUpdate() method. i.e:
129555**
129556**   apVal[0]                Not used for INSERT.
129557**   apVal[1]                rowid
129558**   apVal[2]                Left-most user-defined column
129559**   ...
129560**   apVal[p->nColumn+1]     Right-most user-defined column
129561**   apVal[p->nColumn+2]     Hidden column with same name as table
129562**   apVal[p->nColumn+3]     Hidden "docid" column (alias for rowid)
129563**   apVal[p->nColumn+4]     Hidden languageid column
129564*/
129565static int fts3InsertData(
129566  Fts3Table *p,                   /* Full-text table */
129567  sqlite3_value **apVal,          /* Array of values to insert */
129568  sqlite3_int64 *piDocid          /* OUT: Docid for row just inserted */
129569){
129570  int rc;                         /* Return code */
129571  sqlite3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */
129572
129573  if( p->zContentTbl ){
129574    sqlite3_value *pRowid = apVal[p->nColumn+3];
129575    if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
129576      pRowid = apVal[1];
129577    }
129578    if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
129579      return SQLITE_CONSTRAINT;
129580    }
129581    *piDocid = sqlite3_value_int64(pRowid);
129582    return SQLITE_OK;
129583  }
129584
129585  /* Locate the statement handle used to insert data into the %_content
129586  ** table. The SQL for this statement is:
129587  **
129588  **   INSERT INTO %_content VALUES(?, ?, ?, ...)
129589  **
129590  ** The statement features N '?' variables, where N is the number of user
129591  ** defined columns in the FTS3 table, plus one for the docid field.
129592  */
129593  rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
129594  if( rc==SQLITE_OK && p->zLanguageid ){
129595    rc = sqlite3_bind_int(
129596        pContentInsert, p->nColumn+2,
129597        sqlite3_value_int(apVal[p->nColumn+4])
129598    );
129599  }
129600  if( rc!=SQLITE_OK ) return rc;
129601
129602  /* There is a quirk here. The users INSERT statement may have specified
129603  ** a value for the "rowid" field, for the "docid" field, or for both.
129604  ** Which is a problem, since "rowid" and "docid" are aliases for the
129605  ** same value. For example:
129606  **
129607  **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
129608  **
129609  ** In FTS3, this is an error. It is an error to specify non-NULL values
129610  ** for both docid and some other rowid alias.
129611  */
129612  if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
129613    if( SQLITE_NULL==sqlite3_value_type(apVal[0])
129614     && SQLITE_NULL!=sqlite3_value_type(apVal[1])
129615    ){
129616      /* A rowid/docid conflict. */
129617      return SQLITE_ERROR;
129618    }
129619    rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
129620    if( rc!=SQLITE_OK ) return rc;
129621  }
129622
129623  /* Execute the statement to insert the record. Set *piDocid to the
129624  ** new docid value.
129625  */
129626  sqlite3_step(pContentInsert);
129627  rc = sqlite3_reset(pContentInsert);
129628
129629  *piDocid = sqlite3_last_insert_rowid(p->db);
129630  return rc;
129631}
129632
129633
129634
129635/*
129636** Remove all data from the FTS3 table. Clear the hash table containing
129637** pending terms.
129638*/
129639static int fts3DeleteAll(Fts3Table *p, int bContent){
129640  int rc = SQLITE_OK;             /* Return code */
129641
129642  /* Discard the contents of the pending-terms hash table. */
129643  sqlite3Fts3PendingTermsClear(p);
129644
129645  /* Delete everything from the shadow tables. Except, leave %_content as
129646  ** is if bContent is false.  */
129647  assert( p->zContentTbl==0 || bContent==0 );
129648  if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
129649  fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
129650  fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
129651  if( p->bHasDocsize ){
129652    fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
129653  }
129654  if( p->bHasStat ){
129655    fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
129656  }
129657  return rc;
129658}
129659
129660/*
129661**
129662*/
129663static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
129664  int iLangid = 0;
129665  if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
129666  return iLangid;
129667}
129668
129669/*
129670** The first element in the apVal[] array is assumed to contain the docid
129671** (an integer) of a row about to be deleted. Remove all terms from the
129672** full-text index.
129673*/
129674static void fts3DeleteTerms(
129675  int *pRC,               /* Result code */
129676  Fts3Table *p,           /* The FTS table to delete from */
129677  sqlite3_value *pRowid,  /* The docid to be deleted */
129678  u32 *aSz,               /* Sizes of deleted document written here */
129679  int *pbFound            /* OUT: Set to true if row really does exist */
129680){
129681  int rc;
129682  sqlite3_stmt *pSelect;
129683
129684  assert( *pbFound==0 );
129685  if( *pRC ) return;
129686  rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
129687  if( rc==SQLITE_OK ){
129688    if( SQLITE_ROW==sqlite3_step(pSelect) ){
129689      int i;
129690      int iLangid = langidFromSelect(p, pSelect);
129691      rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pSelect, 0));
129692      for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
129693        const char *zText = (const char *)sqlite3_column_text(pSelect, i);
129694        rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[i-1]);
129695        aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
129696      }
129697      if( rc!=SQLITE_OK ){
129698        sqlite3_reset(pSelect);
129699        *pRC = rc;
129700        return;
129701      }
129702      *pbFound = 1;
129703    }
129704    rc = sqlite3_reset(pSelect);
129705  }else{
129706    sqlite3_reset(pSelect);
129707  }
129708  *pRC = rc;
129709}
129710
129711/*
129712** Forward declaration to account for the circular dependency between
129713** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
129714*/
129715static int fts3SegmentMerge(Fts3Table *, int, int, int);
129716
129717/*
129718** This function allocates a new level iLevel index in the segdir table.
129719** Usually, indexes are allocated within a level sequentially starting
129720** with 0, so the allocated index is one greater than the value returned
129721** by:
129722**
129723**   SELECT max(idx) FROM %_segdir WHERE level = :iLevel
129724**
129725** However, if there are already FTS3_MERGE_COUNT indexes at the requested
129726** level, they are merged into a single level (iLevel+1) segment and the
129727** allocated index is 0.
129728**
129729** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
129730** returned. Otherwise, an SQLite error code is returned.
129731*/
129732static int fts3AllocateSegdirIdx(
129733  Fts3Table *p,
129734  int iLangid,                    /* Language id */
129735  int iIndex,                     /* Index for p->aIndex */
129736  int iLevel,
129737  int *piIdx
129738){
129739  int rc;                         /* Return Code */
129740  sqlite3_stmt *pNextIdx;         /* Query for next idx at level iLevel */
129741  int iNext = 0;                  /* Result of query pNextIdx */
129742
129743  assert( iLangid>=0 );
129744  assert( p->nIndex>=1 );
129745
129746  /* Set variable iNext to the next available segdir index at level iLevel. */
129747  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
129748  if( rc==SQLITE_OK ){
129749    sqlite3_bind_int64(
129750        pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
129751    );
129752    if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
129753      iNext = sqlite3_column_int(pNextIdx, 0);
129754    }
129755    rc = sqlite3_reset(pNextIdx);
129756  }
129757
129758  if( rc==SQLITE_OK ){
129759    /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
129760    ** full, merge all segments in level iLevel into a single iLevel+1
129761    ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
129762    ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
129763    */
129764    if( iNext>=FTS3_MERGE_COUNT ){
129765      fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
129766      rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
129767      *piIdx = 0;
129768    }else{
129769      *piIdx = iNext;
129770    }
129771  }
129772
129773  return rc;
129774}
129775
129776/*
129777** The %_segments table is declared as follows:
129778**
129779**   CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
129780**
129781** This function reads data from a single row of the %_segments table. The
129782** specific row is identified by the iBlockid parameter. If paBlob is not
129783** NULL, then a buffer is allocated using sqlite3_malloc() and populated
129784** with the contents of the blob stored in the "block" column of the
129785** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
129786** to the size of the blob in bytes before returning.
129787**
129788** If an error occurs, or the table does not contain the specified row,
129789** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
129790** paBlob is non-NULL, then it is the responsibility of the caller to
129791** eventually free the returned buffer.
129792**
129793** This function may leave an open sqlite3_blob* handle in the
129794** Fts3Table.pSegments variable. This handle is reused by subsequent calls
129795** to this function. The handle may be closed by calling the
129796** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
129797** performance improvement, but the blob handle should always be closed
129798** before control is returned to the user (to prevent a lock being held
129799** on the database file for longer than necessary). Thus, any virtual table
129800** method (xFilter etc.) that may directly or indirectly call this function
129801** must call sqlite3Fts3SegmentsClose() before returning.
129802*/
129803SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
129804  Fts3Table *p,                   /* FTS3 table handle */
129805  sqlite3_int64 iBlockid,         /* Access the row with blockid=$iBlockid */
129806  char **paBlob,                  /* OUT: Blob data in malloc'd buffer */
129807  int *pnBlob,                    /* OUT: Size of blob data */
129808  int *pnLoad                     /* OUT: Bytes actually loaded */
129809){
129810  int rc;                         /* Return code */
129811
129812  /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
129813  assert( pnBlob );
129814
129815  if( p->pSegments ){
129816    rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
129817  }else{
129818    if( 0==p->zSegmentsTbl ){
129819      p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
129820      if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
129821    }
129822    rc = sqlite3_blob_open(
129823       p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
129824    );
129825  }
129826
129827  if( rc==SQLITE_OK ){
129828    int nByte = sqlite3_blob_bytes(p->pSegments);
129829    *pnBlob = nByte;
129830    if( paBlob ){
129831      char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
129832      if( !aByte ){
129833        rc = SQLITE_NOMEM;
129834      }else{
129835        if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
129836          nByte = FTS3_NODE_CHUNKSIZE;
129837          *pnLoad = nByte;
129838        }
129839        rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
129840        memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
129841        if( rc!=SQLITE_OK ){
129842          sqlite3_free(aByte);
129843          aByte = 0;
129844        }
129845      }
129846      *paBlob = aByte;
129847    }
129848  }
129849
129850  return rc;
129851}
129852
129853/*
129854** Close the blob handle at p->pSegments, if it is open. See comments above
129855** the sqlite3Fts3ReadBlock() function for details.
129856*/
129857SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
129858  sqlite3_blob_close(p->pSegments);
129859  p->pSegments = 0;
129860}
129861
129862static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
129863  int nRead;                      /* Number of bytes to read */
129864  int rc;                         /* Return code */
129865
129866  nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
129867  rc = sqlite3_blob_read(
129868      pReader->pBlob,
129869      &pReader->aNode[pReader->nPopulate],
129870      nRead,
129871      pReader->nPopulate
129872  );
129873
129874  if( rc==SQLITE_OK ){
129875    pReader->nPopulate += nRead;
129876    memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
129877    if( pReader->nPopulate==pReader->nNode ){
129878      sqlite3_blob_close(pReader->pBlob);
129879      pReader->pBlob = 0;
129880      pReader->nPopulate = 0;
129881    }
129882  }
129883  return rc;
129884}
129885
129886static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
129887  int rc = SQLITE_OK;
129888  assert( !pReader->pBlob
129889       || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
129890  );
129891  while( pReader->pBlob && rc==SQLITE_OK
129892     &&  (pFrom - pReader->aNode + nByte)>pReader->nPopulate
129893  ){
129894    rc = fts3SegReaderIncrRead(pReader);
129895  }
129896  return rc;
129897}
129898
129899/*
129900** Set an Fts3SegReader cursor to point at EOF.
129901*/
129902static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
129903  if( !fts3SegReaderIsRootOnly(pSeg) ){
129904    sqlite3_free(pSeg->aNode);
129905    sqlite3_blob_close(pSeg->pBlob);
129906    pSeg->pBlob = 0;
129907  }
129908  pSeg->aNode = 0;
129909}
129910
129911/*
129912** Move the iterator passed as the first argument to the next term in the
129913** segment. If successful, SQLITE_OK is returned. If there is no next term,
129914** SQLITE_DONE. Otherwise, an SQLite error code.
129915*/
129916static int fts3SegReaderNext(
129917  Fts3Table *p,
129918  Fts3SegReader *pReader,
129919  int bIncr
129920){
129921  int rc;                         /* Return code of various sub-routines */
129922  char *pNext;                    /* Cursor variable */
129923  int nPrefix;                    /* Number of bytes in term prefix */
129924  int nSuffix;                    /* Number of bytes in term suffix */
129925
129926  if( !pReader->aDoclist ){
129927    pNext = pReader->aNode;
129928  }else{
129929    pNext = &pReader->aDoclist[pReader->nDoclist];
129930  }
129931
129932  if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
129933
129934    if( fts3SegReaderIsPending(pReader) ){
129935      Fts3HashElem *pElem = *(pReader->ppNextElem);
129936      if( pElem==0 ){
129937        pReader->aNode = 0;
129938      }else{
129939        PendingList *pList = (PendingList *)fts3HashData(pElem);
129940        pReader->zTerm = (char *)fts3HashKey(pElem);
129941        pReader->nTerm = fts3HashKeysize(pElem);
129942        pReader->nNode = pReader->nDoclist = pList->nData + 1;
129943        pReader->aNode = pReader->aDoclist = pList->aData;
129944        pReader->ppNextElem++;
129945        assert( pReader->aNode );
129946      }
129947      return SQLITE_OK;
129948    }
129949
129950    fts3SegReaderSetEof(pReader);
129951
129952    /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
129953    ** blocks have already been traversed.  */
129954    assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
129955    if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
129956      return SQLITE_OK;
129957    }
129958
129959    rc = sqlite3Fts3ReadBlock(
129960        p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
129961        (bIncr ? &pReader->nPopulate : 0)
129962    );
129963    if( rc!=SQLITE_OK ) return rc;
129964    assert( pReader->pBlob==0 );
129965    if( bIncr && pReader->nPopulate<pReader->nNode ){
129966      pReader->pBlob = p->pSegments;
129967      p->pSegments = 0;
129968    }
129969    pNext = pReader->aNode;
129970  }
129971
129972  assert( !fts3SegReaderIsPending(pReader) );
129973
129974  rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
129975  if( rc!=SQLITE_OK ) return rc;
129976
129977  /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
129978  ** safe (no risk of overread) even if the node data is corrupted. */
129979  pNext += sqlite3Fts3GetVarint32(pNext, &nPrefix);
129980  pNext += sqlite3Fts3GetVarint32(pNext, &nSuffix);
129981  if( nPrefix<0 || nSuffix<=0
129982   || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
129983  ){
129984    return FTS_CORRUPT_VTAB;
129985  }
129986
129987  if( nPrefix+nSuffix>pReader->nTermAlloc ){
129988    int nNew = (nPrefix+nSuffix)*2;
129989    char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
129990    if( !zNew ){
129991      return SQLITE_NOMEM;
129992    }
129993    pReader->zTerm = zNew;
129994    pReader->nTermAlloc = nNew;
129995  }
129996
129997  rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
129998  if( rc!=SQLITE_OK ) return rc;
129999
130000  memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
130001  pReader->nTerm = nPrefix+nSuffix;
130002  pNext += nSuffix;
130003  pNext += sqlite3Fts3GetVarint32(pNext, &pReader->nDoclist);
130004  pReader->aDoclist = pNext;
130005  pReader->pOffsetList = 0;
130006
130007  /* Check that the doclist does not appear to extend past the end of the
130008  ** b-tree node. And that the final byte of the doclist is 0x00. If either
130009  ** of these statements is untrue, then the data structure is corrupt.
130010  */
130011  if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
130012   || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
130013  ){
130014    return FTS_CORRUPT_VTAB;
130015  }
130016  return SQLITE_OK;
130017}
130018
130019/*
130020** Set the SegReader to point to the first docid in the doclist associated
130021** with the current term.
130022*/
130023static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
130024  int rc = SQLITE_OK;
130025  assert( pReader->aDoclist );
130026  assert( !pReader->pOffsetList );
130027  if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
130028    u8 bEof = 0;
130029    pReader->iDocid = 0;
130030    pReader->nOffsetList = 0;
130031    sqlite3Fts3DoclistPrev(0,
130032        pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
130033        &pReader->iDocid, &pReader->nOffsetList, &bEof
130034    );
130035  }else{
130036    rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
130037    if( rc==SQLITE_OK ){
130038      int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
130039      pReader->pOffsetList = &pReader->aDoclist[n];
130040    }
130041  }
130042  return rc;
130043}
130044
130045/*
130046** Advance the SegReader to point to the next docid in the doclist
130047** associated with the current term.
130048**
130049** If arguments ppOffsetList and pnOffsetList are not NULL, then
130050** *ppOffsetList is set to point to the first column-offset list
130051** in the doclist entry (i.e. immediately past the docid varint).
130052** *pnOffsetList is set to the length of the set of column-offset
130053** lists, not including the nul-terminator byte. For example:
130054*/
130055static int fts3SegReaderNextDocid(
130056  Fts3Table *pTab,
130057  Fts3SegReader *pReader,         /* Reader to advance to next docid */
130058  char **ppOffsetList,            /* OUT: Pointer to current position-list */
130059  int *pnOffsetList               /* OUT: Length of *ppOffsetList in bytes */
130060){
130061  int rc = SQLITE_OK;
130062  char *p = pReader->pOffsetList;
130063  char c = 0;
130064
130065  assert( p );
130066
130067  if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
130068    /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
130069    ** Pending-terms doclists are always built up in ascending order, so
130070    ** we have to iterate through them backwards here. */
130071    u8 bEof = 0;
130072    if( ppOffsetList ){
130073      *ppOffsetList = pReader->pOffsetList;
130074      *pnOffsetList = pReader->nOffsetList - 1;
130075    }
130076    sqlite3Fts3DoclistPrev(0,
130077        pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
130078        &pReader->nOffsetList, &bEof
130079    );
130080    if( bEof ){
130081      pReader->pOffsetList = 0;
130082    }else{
130083      pReader->pOffsetList = p;
130084    }
130085  }else{
130086    char *pEnd = &pReader->aDoclist[pReader->nDoclist];
130087
130088    /* Pointer p currently points at the first byte of an offset list. The
130089    ** following block advances it to point one byte past the end of
130090    ** the same offset list. */
130091    while( 1 ){
130092
130093      /* The following line of code (and the "p++" below the while() loop) is
130094      ** normally all that is required to move pointer p to the desired
130095      ** position. The exception is if this node is being loaded from disk
130096      ** incrementally and pointer "p" now points to the first byte passed
130097      ** the populated part of pReader->aNode[].
130098      */
130099      while( *p | c ) c = *p++ & 0x80;
130100      assert( *p==0 );
130101
130102      if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
130103      rc = fts3SegReaderIncrRead(pReader);
130104      if( rc!=SQLITE_OK ) return rc;
130105    }
130106    p++;
130107
130108    /* If required, populate the output variables with a pointer to and the
130109    ** size of the previous offset-list.
130110    */
130111    if( ppOffsetList ){
130112      *ppOffsetList = pReader->pOffsetList;
130113      *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
130114    }
130115
130116    /* List may have been edited in place by fts3EvalNearTrim() */
130117    while( p<pEnd && *p==0 ) p++;
130118
130119    /* If there are no more entries in the doclist, set pOffsetList to
130120    ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
130121    ** Fts3SegReader.pOffsetList to point to the next offset list before
130122    ** returning.
130123    */
130124    if( p>=pEnd ){
130125      pReader->pOffsetList = 0;
130126    }else{
130127      rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
130128      if( rc==SQLITE_OK ){
130129        sqlite3_int64 iDelta;
130130        pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
130131        if( pTab->bDescIdx ){
130132          pReader->iDocid -= iDelta;
130133        }else{
130134          pReader->iDocid += iDelta;
130135        }
130136      }
130137    }
130138  }
130139
130140  return SQLITE_OK;
130141}
130142
130143
130144SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
130145  Fts3Cursor *pCsr,
130146  Fts3MultiSegReader *pMsr,
130147  int *pnOvfl
130148){
130149  Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
130150  int nOvfl = 0;
130151  int ii;
130152  int rc = SQLITE_OK;
130153  int pgsz = p->nPgsz;
130154
130155  assert( p->bFts4 );
130156  assert( pgsz>0 );
130157
130158  for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
130159    Fts3SegReader *pReader = pMsr->apSegment[ii];
130160    if( !fts3SegReaderIsPending(pReader)
130161     && !fts3SegReaderIsRootOnly(pReader)
130162    ){
130163      sqlite3_int64 jj;
130164      for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
130165        int nBlob;
130166        rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
130167        if( rc!=SQLITE_OK ) break;
130168        if( (nBlob+35)>pgsz ){
130169          nOvfl += (nBlob + 34)/pgsz;
130170        }
130171      }
130172    }
130173  }
130174  *pnOvfl = nOvfl;
130175  return rc;
130176}
130177
130178/*
130179** Free all allocations associated with the iterator passed as the
130180** second argument.
130181*/
130182SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
130183  if( pReader && !fts3SegReaderIsPending(pReader) ){
130184    sqlite3_free(pReader->zTerm);
130185    if( !fts3SegReaderIsRootOnly(pReader) ){
130186      sqlite3_free(pReader->aNode);
130187      sqlite3_blob_close(pReader->pBlob);
130188    }
130189  }
130190  sqlite3_free(pReader);
130191}
130192
130193/*
130194** Allocate a new SegReader object.
130195*/
130196SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
130197  int iAge,                       /* Segment "age". */
130198  int bLookup,                    /* True for a lookup only */
130199  sqlite3_int64 iStartLeaf,       /* First leaf to traverse */
130200  sqlite3_int64 iEndLeaf,         /* Final leaf to traverse */
130201  sqlite3_int64 iEndBlock,        /* Final block of segment */
130202  const char *zRoot,              /* Buffer containing root node */
130203  int nRoot,                      /* Size of buffer containing root node */
130204  Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
130205){
130206  Fts3SegReader *pReader;         /* Newly allocated SegReader object */
130207  int nExtra = 0;                 /* Bytes to allocate segment root node */
130208
130209  assert( iStartLeaf<=iEndLeaf );
130210  if( iStartLeaf==0 ){
130211    nExtra = nRoot + FTS3_NODE_PADDING;
130212  }
130213
130214  pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
130215  if( !pReader ){
130216    return SQLITE_NOMEM;
130217  }
130218  memset(pReader, 0, sizeof(Fts3SegReader));
130219  pReader->iIdx = iAge;
130220  pReader->bLookup = bLookup!=0;
130221  pReader->iStartBlock = iStartLeaf;
130222  pReader->iLeafEndBlock = iEndLeaf;
130223  pReader->iEndBlock = iEndBlock;
130224
130225  if( nExtra ){
130226    /* The entire segment is stored in the root node. */
130227    pReader->aNode = (char *)&pReader[1];
130228    pReader->rootOnly = 1;
130229    pReader->nNode = nRoot;
130230    memcpy(pReader->aNode, zRoot, nRoot);
130231    memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
130232  }else{
130233    pReader->iCurrentBlock = iStartLeaf-1;
130234  }
130235  *ppReader = pReader;
130236  return SQLITE_OK;
130237}
130238
130239/*
130240** This is a comparison function used as a qsort() callback when sorting
130241** an array of pending terms by term. This occurs as part of flushing
130242** the contents of the pending-terms hash table to the database.
130243*/
130244static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
130245  char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
130246  char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
130247  int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
130248  int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
130249
130250  int n = (n1<n2 ? n1 : n2);
130251  int c = memcmp(z1, z2, n);
130252  if( c==0 ){
130253    c = n1 - n2;
130254  }
130255  return c;
130256}
130257
130258/*
130259** This function is used to allocate an Fts3SegReader that iterates through
130260** a subset of the terms stored in the Fts3Table.pendingTerms array.
130261**
130262** If the isPrefixIter parameter is zero, then the returned SegReader iterates
130263** through each term in the pending-terms table. Or, if isPrefixIter is
130264** non-zero, it iterates through each term and its prefixes. For example, if
130265** the pending terms hash table contains the terms "sqlite", "mysql" and
130266** "firebird", then the iterator visits the following 'terms' (in the order
130267** shown):
130268**
130269**   f fi fir fire fireb firebi firebir firebird
130270**   m my mys mysq mysql
130271**   s sq sql sqli sqlit sqlite
130272**
130273** Whereas if isPrefixIter is zero, the terms visited are:
130274**
130275**   firebird mysql sqlite
130276*/
130277SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
130278  Fts3Table *p,                   /* Virtual table handle */
130279  int iIndex,                     /* Index for p->aIndex */
130280  const char *zTerm,              /* Term to search for */
130281  int nTerm,                      /* Size of buffer zTerm */
130282  int bPrefix,                    /* True for a prefix iterator */
130283  Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */
130284){
130285  Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */
130286  Fts3HashElem *pE;               /* Iterator variable */
130287  Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */
130288  int nElem = 0;                  /* Size of array at aElem */
130289  int rc = SQLITE_OK;             /* Return Code */
130290  Fts3Hash *pHash;
130291
130292  pHash = &p->aIndex[iIndex].hPending;
130293  if( bPrefix ){
130294    int nAlloc = 0;               /* Size of allocated array at aElem */
130295
130296    for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
130297      char *zKey = (char *)fts3HashKey(pE);
130298      int nKey = fts3HashKeysize(pE);
130299      if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
130300        if( nElem==nAlloc ){
130301          Fts3HashElem **aElem2;
130302          nAlloc += 16;
130303          aElem2 = (Fts3HashElem **)sqlite3_realloc(
130304              aElem, nAlloc*sizeof(Fts3HashElem *)
130305          );
130306          if( !aElem2 ){
130307            rc = SQLITE_NOMEM;
130308            nElem = 0;
130309            break;
130310          }
130311          aElem = aElem2;
130312        }
130313
130314        aElem[nElem++] = pE;
130315      }
130316    }
130317
130318    /* If more than one term matches the prefix, sort the Fts3HashElem
130319    ** objects in term order using qsort(). This uses the same comparison
130320    ** callback as is used when flushing terms to disk.
130321    */
130322    if( nElem>1 ){
130323      qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
130324    }
130325
130326  }else{
130327    /* The query is a simple term lookup that matches at most one term in
130328    ** the index. All that is required is a straight hash-lookup.
130329    **
130330    ** Because the stack address of pE may be accessed via the aElem pointer
130331    ** below, the "Fts3HashElem *pE" must be declared so that it is valid
130332    ** within this entire function, not just this "else{...}" block.
130333    */
130334    pE = fts3HashFindElem(pHash, zTerm, nTerm);
130335    if( pE ){
130336      aElem = &pE;
130337      nElem = 1;
130338    }
130339  }
130340
130341  if( nElem>0 ){
130342    int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
130343    pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
130344    if( !pReader ){
130345      rc = SQLITE_NOMEM;
130346    }else{
130347      memset(pReader, 0, nByte);
130348      pReader->iIdx = 0x7FFFFFFF;
130349      pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
130350      memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
130351    }
130352  }
130353
130354  if( bPrefix ){
130355    sqlite3_free(aElem);
130356  }
130357  *ppReader = pReader;
130358  return rc;
130359}
130360
130361/*
130362** Compare the entries pointed to by two Fts3SegReader structures.
130363** Comparison is as follows:
130364**
130365**   1) EOF is greater than not EOF.
130366**
130367**   2) The current terms (if any) are compared using memcmp(). If one
130368**      term is a prefix of another, the longer term is considered the
130369**      larger.
130370**
130371**   3) By segment age. An older segment is considered larger.
130372*/
130373static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
130374  int rc;
130375  if( pLhs->aNode && pRhs->aNode ){
130376    int rc2 = pLhs->nTerm - pRhs->nTerm;
130377    if( rc2<0 ){
130378      rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
130379    }else{
130380      rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
130381    }
130382    if( rc==0 ){
130383      rc = rc2;
130384    }
130385  }else{
130386    rc = (pLhs->aNode==0) - (pRhs->aNode==0);
130387  }
130388  if( rc==0 ){
130389    rc = pRhs->iIdx - pLhs->iIdx;
130390  }
130391  assert( rc!=0 );
130392  return rc;
130393}
130394
130395/*
130396** A different comparison function for SegReader structures. In this
130397** version, it is assumed that each SegReader points to an entry in
130398** a doclist for identical terms. Comparison is made as follows:
130399**
130400**   1) EOF (end of doclist in this case) is greater than not EOF.
130401**
130402**   2) By current docid.
130403**
130404**   3) By segment age. An older segment is considered larger.
130405*/
130406static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
130407  int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
130408  if( rc==0 ){
130409    if( pLhs->iDocid==pRhs->iDocid ){
130410      rc = pRhs->iIdx - pLhs->iIdx;
130411    }else{
130412      rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
130413    }
130414  }
130415  assert( pLhs->aNode && pRhs->aNode );
130416  return rc;
130417}
130418static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
130419  int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
130420  if( rc==0 ){
130421    if( pLhs->iDocid==pRhs->iDocid ){
130422      rc = pRhs->iIdx - pLhs->iIdx;
130423    }else{
130424      rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
130425    }
130426  }
130427  assert( pLhs->aNode && pRhs->aNode );
130428  return rc;
130429}
130430
130431/*
130432** Compare the term that the Fts3SegReader object passed as the first argument
130433** points to with the term specified by arguments zTerm and nTerm.
130434**
130435** If the pSeg iterator is already at EOF, return 0. Otherwise, return
130436** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
130437** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
130438*/
130439static int fts3SegReaderTermCmp(
130440  Fts3SegReader *pSeg,            /* Segment reader object */
130441  const char *zTerm,              /* Term to compare to */
130442  int nTerm                       /* Size of term zTerm in bytes */
130443){
130444  int res = 0;
130445  if( pSeg->aNode ){
130446    if( pSeg->nTerm>nTerm ){
130447      res = memcmp(pSeg->zTerm, zTerm, nTerm);
130448    }else{
130449      res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
130450    }
130451    if( res==0 ){
130452      res = pSeg->nTerm-nTerm;
130453    }
130454  }
130455  return res;
130456}
130457
130458/*
130459** Argument apSegment is an array of nSegment elements. It is known that
130460** the final (nSegment-nSuspect) members are already in sorted order
130461** (according to the comparison function provided). This function shuffles
130462** the array around until all entries are in sorted order.
130463*/
130464static void fts3SegReaderSort(
130465  Fts3SegReader **apSegment,                     /* Array to sort entries of */
130466  int nSegment,                                  /* Size of apSegment array */
130467  int nSuspect,                                  /* Unsorted entry count */
130468  int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */
130469){
130470  int i;                          /* Iterator variable */
130471
130472  assert( nSuspect<=nSegment );
130473
130474  if( nSuspect==nSegment ) nSuspect--;
130475  for(i=nSuspect-1; i>=0; i--){
130476    int j;
130477    for(j=i; j<(nSegment-1); j++){
130478      Fts3SegReader *pTmp;
130479      if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
130480      pTmp = apSegment[j+1];
130481      apSegment[j+1] = apSegment[j];
130482      apSegment[j] = pTmp;
130483    }
130484  }
130485
130486#ifndef NDEBUG
130487  /* Check that the list really is sorted now. */
130488  for(i=0; i<(nSuspect-1); i++){
130489    assert( xCmp(apSegment[i], apSegment[i+1])<0 );
130490  }
130491#endif
130492}
130493
130494/*
130495** Insert a record into the %_segments table.
130496*/
130497static int fts3WriteSegment(
130498  Fts3Table *p,                   /* Virtual table handle */
130499  sqlite3_int64 iBlock,           /* Block id for new block */
130500  char *z,                        /* Pointer to buffer containing block data */
130501  int n                           /* Size of buffer z in bytes */
130502){
130503  sqlite3_stmt *pStmt;
130504  int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
130505  if( rc==SQLITE_OK ){
130506    sqlite3_bind_int64(pStmt, 1, iBlock);
130507    sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
130508    sqlite3_step(pStmt);
130509    rc = sqlite3_reset(pStmt);
130510  }
130511  return rc;
130512}
130513
130514/*
130515** Find the largest relative level number in the table. If successful, set
130516** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
130517** set *pnMax to zero and return an SQLite error code.
130518*/
130519SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
130520  int rc;
130521  int mxLevel = 0;
130522  sqlite3_stmt *pStmt = 0;
130523
130524  rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
130525  if( rc==SQLITE_OK ){
130526    if( SQLITE_ROW==sqlite3_step(pStmt) ){
130527      mxLevel = sqlite3_column_int(pStmt, 0);
130528    }
130529    rc = sqlite3_reset(pStmt);
130530  }
130531  *pnMax = mxLevel;
130532  return rc;
130533}
130534
130535/*
130536** Insert a record into the %_segdir table.
130537*/
130538static int fts3WriteSegdir(
130539  Fts3Table *p,                   /* Virtual table handle */
130540  sqlite3_int64 iLevel,           /* Value for "level" field (absolute level) */
130541  int iIdx,                       /* Value for "idx" field */
130542  sqlite3_int64 iStartBlock,      /* Value for "start_block" field */
130543  sqlite3_int64 iLeafEndBlock,    /* Value for "leaves_end_block" field */
130544  sqlite3_int64 iEndBlock,        /* Value for "end_block" field */
130545  char *zRoot,                    /* Blob value for "root" field */
130546  int nRoot                       /* Number of bytes in buffer zRoot */
130547){
130548  sqlite3_stmt *pStmt;
130549  int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
130550  if( rc==SQLITE_OK ){
130551    sqlite3_bind_int64(pStmt, 1, iLevel);
130552    sqlite3_bind_int(pStmt, 2, iIdx);
130553    sqlite3_bind_int64(pStmt, 3, iStartBlock);
130554    sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
130555    sqlite3_bind_int64(pStmt, 5, iEndBlock);
130556    sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
130557    sqlite3_step(pStmt);
130558    rc = sqlite3_reset(pStmt);
130559  }
130560  return rc;
130561}
130562
130563/*
130564** Return the size of the common prefix (if any) shared by zPrev and
130565** zNext, in bytes. For example,
130566**
130567**   fts3PrefixCompress("abc", 3, "abcdef", 6)   // returns 3
130568**   fts3PrefixCompress("abX", 3, "abcdef", 6)   // returns 2
130569**   fts3PrefixCompress("abX", 3, "Xbcdef", 6)   // returns 0
130570*/
130571static int fts3PrefixCompress(
130572  const char *zPrev,              /* Buffer containing previous term */
130573  int nPrev,                      /* Size of buffer zPrev in bytes */
130574  const char *zNext,              /* Buffer containing next term */
130575  int nNext                       /* Size of buffer zNext in bytes */
130576){
130577  int n;
130578  UNUSED_PARAMETER(nNext);
130579  for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
130580  return n;
130581}
130582
130583/*
130584** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
130585** (according to memcmp) than the previous term.
130586*/
130587static int fts3NodeAddTerm(
130588  Fts3Table *p,                   /* Virtual table handle */
130589  SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */
130590  int isCopyTerm,                 /* True if zTerm/nTerm is transient */
130591  const char *zTerm,              /* Pointer to buffer containing term */
130592  int nTerm                       /* Size of term in bytes */
130593){
130594  SegmentNode *pTree = *ppTree;
130595  int rc;
130596  SegmentNode *pNew;
130597
130598  /* First try to append the term to the current node. Return early if
130599  ** this is possible.
130600  */
130601  if( pTree ){
130602    int nData = pTree->nData;     /* Current size of node in bytes */
130603    int nReq = nData;             /* Required space after adding zTerm */
130604    int nPrefix;                  /* Number of bytes of prefix compression */
130605    int nSuffix;                  /* Suffix length */
130606
130607    nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
130608    nSuffix = nTerm-nPrefix;
130609
130610    nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
130611    if( nReq<=p->nNodeSize || !pTree->zTerm ){
130612
130613      if( nReq>p->nNodeSize ){
130614        /* An unusual case: this is the first term to be added to the node
130615        ** and the static node buffer (p->nNodeSize bytes) is not large
130616        ** enough. Use a separately malloced buffer instead This wastes
130617        ** p->nNodeSize bytes, but since this scenario only comes about when
130618        ** the database contain two terms that share a prefix of almost 2KB,
130619        ** this is not expected to be a serious problem.
130620        */
130621        assert( pTree->aData==(char *)&pTree[1] );
130622        pTree->aData = (char *)sqlite3_malloc(nReq);
130623        if( !pTree->aData ){
130624          return SQLITE_NOMEM;
130625        }
130626      }
130627
130628      if( pTree->zTerm ){
130629        /* There is no prefix-length field for first term in a node */
130630        nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
130631      }
130632
130633      nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
130634      memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
130635      pTree->nData = nData + nSuffix;
130636      pTree->nEntry++;
130637
130638      if( isCopyTerm ){
130639        if( pTree->nMalloc<nTerm ){
130640          char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
130641          if( !zNew ){
130642            return SQLITE_NOMEM;
130643          }
130644          pTree->nMalloc = nTerm*2;
130645          pTree->zMalloc = zNew;
130646        }
130647        pTree->zTerm = pTree->zMalloc;
130648        memcpy(pTree->zTerm, zTerm, nTerm);
130649        pTree->nTerm = nTerm;
130650      }else{
130651        pTree->zTerm = (char *)zTerm;
130652        pTree->nTerm = nTerm;
130653      }
130654      return SQLITE_OK;
130655    }
130656  }
130657
130658  /* If control flows to here, it was not possible to append zTerm to the
130659  ** current node. Create a new node (a right-sibling of the current node).
130660  ** If this is the first node in the tree, the term is added to it.
130661  **
130662  ** Otherwise, the term is not added to the new node, it is left empty for
130663  ** now. Instead, the term is inserted into the parent of pTree. If pTree
130664  ** has no parent, one is created here.
130665  */
130666  pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
130667  if( !pNew ){
130668    return SQLITE_NOMEM;
130669  }
130670  memset(pNew, 0, sizeof(SegmentNode));
130671  pNew->nData = 1 + FTS3_VARINT_MAX;
130672  pNew->aData = (char *)&pNew[1];
130673
130674  if( pTree ){
130675    SegmentNode *pParent = pTree->pParent;
130676    rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
130677    if( pTree->pParent==0 ){
130678      pTree->pParent = pParent;
130679    }
130680    pTree->pRight = pNew;
130681    pNew->pLeftmost = pTree->pLeftmost;
130682    pNew->pParent = pParent;
130683    pNew->zMalloc = pTree->zMalloc;
130684    pNew->nMalloc = pTree->nMalloc;
130685    pTree->zMalloc = 0;
130686  }else{
130687    pNew->pLeftmost = pNew;
130688    rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
130689  }
130690
130691  *ppTree = pNew;
130692  return rc;
130693}
130694
130695/*
130696** Helper function for fts3NodeWrite().
130697*/
130698static int fts3TreeFinishNode(
130699  SegmentNode *pTree,
130700  int iHeight,
130701  sqlite3_int64 iLeftChild
130702){
130703  int nStart;
130704  assert( iHeight>=1 && iHeight<128 );
130705  nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
130706  pTree->aData[nStart] = (char)iHeight;
130707  sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
130708  return nStart;
130709}
130710
130711/*
130712** Write the buffer for the segment node pTree and all of its peers to the
130713** database. Then call this function recursively to write the parent of
130714** pTree and its peers to the database.
130715**
130716** Except, if pTree is a root node, do not write it to the database. Instead,
130717** set output variables *paRoot and *pnRoot to contain the root node.
130718**
130719** If successful, SQLITE_OK is returned and output variable *piLast is
130720** set to the largest blockid written to the database (or zero if no
130721** blocks were written to the db). Otherwise, an SQLite error code is
130722** returned.
130723*/
130724static int fts3NodeWrite(
130725  Fts3Table *p,                   /* Virtual table handle */
130726  SegmentNode *pTree,             /* SegmentNode handle */
130727  int iHeight,                    /* Height of this node in tree */
130728  sqlite3_int64 iLeaf,            /* Block id of first leaf node */
130729  sqlite3_int64 iFree,            /* Block id of next free slot in %_segments */
130730  sqlite3_int64 *piLast,          /* OUT: Block id of last entry written */
130731  char **paRoot,                  /* OUT: Data for root node */
130732  int *pnRoot                     /* OUT: Size of root node in bytes */
130733){
130734  int rc = SQLITE_OK;
130735
130736  if( !pTree->pParent ){
130737    /* Root node of the tree. */
130738    int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
130739    *piLast = iFree-1;
130740    *pnRoot = pTree->nData - nStart;
130741    *paRoot = &pTree->aData[nStart];
130742  }else{
130743    SegmentNode *pIter;
130744    sqlite3_int64 iNextFree = iFree;
130745    sqlite3_int64 iNextLeaf = iLeaf;
130746    for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
130747      int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
130748      int nWrite = pIter->nData - nStart;
130749
130750      rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
130751      iNextFree++;
130752      iNextLeaf += (pIter->nEntry+1);
130753    }
130754    if( rc==SQLITE_OK ){
130755      assert( iNextLeaf==iFree );
130756      rc = fts3NodeWrite(
130757          p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
130758      );
130759    }
130760  }
130761
130762  return rc;
130763}
130764
130765/*
130766** Free all memory allocations associated with the tree pTree.
130767*/
130768static void fts3NodeFree(SegmentNode *pTree){
130769  if( pTree ){
130770    SegmentNode *p = pTree->pLeftmost;
130771    fts3NodeFree(p->pParent);
130772    while( p ){
130773      SegmentNode *pRight = p->pRight;
130774      if( p->aData!=(char *)&p[1] ){
130775        sqlite3_free(p->aData);
130776      }
130777      assert( pRight==0 || p->zMalloc==0 );
130778      sqlite3_free(p->zMalloc);
130779      sqlite3_free(p);
130780      p = pRight;
130781    }
130782  }
130783}
130784
130785/*
130786** Add a term to the segment being constructed by the SegmentWriter object
130787** *ppWriter. When adding the first term to a segment, *ppWriter should
130788** be passed NULL. This function will allocate a new SegmentWriter object
130789** and return it via the input/output variable *ppWriter in this case.
130790**
130791** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
130792*/
130793static int fts3SegWriterAdd(
130794  Fts3Table *p,                   /* Virtual table handle */
130795  SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */
130796  int isCopyTerm,                 /* True if buffer zTerm must be copied */
130797  const char *zTerm,              /* Pointer to buffer containing term */
130798  int nTerm,                      /* Size of term in bytes */
130799  const char *aDoclist,           /* Pointer to buffer containing doclist */
130800  int nDoclist                    /* Size of doclist in bytes */
130801){
130802  int nPrefix;                    /* Size of term prefix in bytes */
130803  int nSuffix;                    /* Size of term suffix in bytes */
130804  int nReq;                       /* Number of bytes required on leaf page */
130805  int nData;
130806  SegmentWriter *pWriter = *ppWriter;
130807
130808  if( !pWriter ){
130809    int rc;
130810    sqlite3_stmt *pStmt;
130811
130812    /* Allocate the SegmentWriter structure */
130813    pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
130814    if( !pWriter ) return SQLITE_NOMEM;
130815    memset(pWriter, 0, sizeof(SegmentWriter));
130816    *ppWriter = pWriter;
130817
130818    /* Allocate a buffer in which to accumulate data */
130819    pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
130820    if( !pWriter->aData ) return SQLITE_NOMEM;
130821    pWriter->nSize = p->nNodeSize;
130822
130823    /* Find the next free blockid in the %_segments table */
130824    rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
130825    if( rc!=SQLITE_OK ) return rc;
130826    if( SQLITE_ROW==sqlite3_step(pStmt) ){
130827      pWriter->iFree = sqlite3_column_int64(pStmt, 0);
130828      pWriter->iFirst = pWriter->iFree;
130829    }
130830    rc = sqlite3_reset(pStmt);
130831    if( rc!=SQLITE_OK ) return rc;
130832  }
130833  nData = pWriter->nData;
130834
130835  nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
130836  nSuffix = nTerm-nPrefix;
130837
130838  /* Figure out how many bytes are required by this new entry */
130839  nReq = sqlite3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */
130840    sqlite3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */
130841    nSuffix +                               /* Term suffix */
130842    sqlite3Fts3VarintLen(nDoclist) +        /* Size of doclist */
130843    nDoclist;                               /* Doclist data */
130844
130845  if( nData>0 && nData+nReq>p->nNodeSize ){
130846    int rc;
130847
130848    /* The current leaf node is full. Write it out to the database. */
130849    rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
130850    if( rc!=SQLITE_OK ) return rc;
130851    p->nLeafAdd++;
130852
130853    /* Add the current term to the interior node tree. The term added to
130854    ** the interior tree must:
130855    **
130856    **   a) be greater than the largest term on the leaf node just written
130857    **      to the database (still available in pWriter->zTerm), and
130858    **
130859    **   b) be less than or equal to the term about to be added to the new
130860    **      leaf node (zTerm/nTerm).
130861    **
130862    ** In other words, it must be the prefix of zTerm 1 byte longer than
130863    ** the common prefix (if any) of zTerm and pWriter->zTerm.
130864    */
130865    assert( nPrefix<nTerm );
130866    rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
130867    if( rc!=SQLITE_OK ) return rc;
130868
130869    nData = 0;
130870    pWriter->nTerm = 0;
130871
130872    nPrefix = 0;
130873    nSuffix = nTerm;
130874    nReq = 1 +                              /* varint containing prefix size */
130875      sqlite3Fts3VarintLen(nTerm) +         /* varint containing suffix size */
130876      nTerm +                               /* Term suffix */
130877      sqlite3Fts3VarintLen(nDoclist) +      /* Size of doclist */
130878      nDoclist;                             /* Doclist data */
130879  }
130880
130881  /* If the buffer currently allocated is too small for this entry, realloc
130882  ** the buffer to make it large enough.
130883  */
130884  if( nReq>pWriter->nSize ){
130885    char *aNew = sqlite3_realloc(pWriter->aData, nReq);
130886    if( !aNew ) return SQLITE_NOMEM;
130887    pWriter->aData = aNew;
130888    pWriter->nSize = nReq;
130889  }
130890  assert( nData+nReq<=pWriter->nSize );
130891
130892  /* Append the prefix-compressed term and doclist to the buffer. */
130893  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
130894  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
130895  memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
130896  nData += nSuffix;
130897  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
130898  memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
130899  pWriter->nData = nData + nDoclist;
130900
130901  /* Save the current term so that it can be used to prefix-compress the next.
130902  ** If the isCopyTerm parameter is true, then the buffer pointed to by
130903  ** zTerm is transient, so take a copy of the term data. Otherwise, just
130904  ** store a copy of the pointer.
130905  */
130906  if( isCopyTerm ){
130907    if( nTerm>pWriter->nMalloc ){
130908      char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
130909      if( !zNew ){
130910        return SQLITE_NOMEM;
130911      }
130912      pWriter->nMalloc = nTerm*2;
130913      pWriter->zMalloc = zNew;
130914      pWriter->zTerm = zNew;
130915    }
130916    assert( pWriter->zTerm==pWriter->zMalloc );
130917    memcpy(pWriter->zTerm, zTerm, nTerm);
130918  }else{
130919    pWriter->zTerm = (char *)zTerm;
130920  }
130921  pWriter->nTerm = nTerm;
130922
130923  return SQLITE_OK;
130924}
130925
130926/*
130927** Flush all data associated with the SegmentWriter object pWriter to the
130928** database. This function must be called after all terms have been added
130929** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
130930** returned. Otherwise, an SQLite error code.
130931*/
130932static int fts3SegWriterFlush(
130933  Fts3Table *p,                   /* Virtual table handle */
130934  SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */
130935  sqlite3_int64 iLevel,           /* Value for 'level' column of %_segdir */
130936  int iIdx                        /* Value for 'idx' column of %_segdir */
130937){
130938  int rc;                         /* Return code */
130939  if( pWriter->pTree ){
130940    sqlite3_int64 iLast = 0;      /* Largest block id written to database */
130941    sqlite3_int64 iLastLeaf;      /* Largest leaf block id written to db */
130942    char *zRoot = NULL;           /* Pointer to buffer containing root node */
130943    int nRoot = 0;                /* Size of buffer zRoot */
130944
130945    iLastLeaf = pWriter->iFree;
130946    rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
130947    if( rc==SQLITE_OK ){
130948      rc = fts3NodeWrite(p, pWriter->pTree, 1,
130949          pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
130950    }
130951    if( rc==SQLITE_OK ){
130952      rc = fts3WriteSegdir(
130953          p, iLevel, iIdx, pWriter->iFirst, iLastLeaf, iLast, zRoot, nRoot);
130954    }
130955  }else{
130956    /* The entire tree fits on the root node. Write it to the segdir table. */
130957    rc = fts3WriteSegdir(
130958        p, iLevel, iIdx, 0, 0, 0, pWriter->aData, pWriter->nData);
130959  }
130960  p->nLeafAdd++;
130961  return rc;
130962}
130963
130964/*
130965** Release all memory held by the SegmentWriter object passed as the
130966** first argument.
130967*/
130968static void fts3SegWriterFree(SegmentWriter *pWriter){
130969  if( pWriter ){
130970    sqlite3_free(pWriter->aData);
130971    sqlite3_free(pWriter->zMalloc);
130972    fts3NodeFree(pWriter->pTree);
130973    sqlite3_free(pWriter);
130974  }
130975}
130976
130977/*
130978** The first value in the apVal[] array is assumed to contain an integer.
130979** This function tests if there exist any documents with docid values that
130980** are different from that integer. i.e. if deleting the document with docid
130981** pRowid would mean the FTS3 table were empty.
130982**
130983** If successful, *pisEmpty is set to true if the table is empty except for
130984** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
130985** error occurs, an SQLite error code is returned.
130986*/
130987static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
130988  sqlite3_stmt *pStmt;
130989  int rc;
130990  if( p->zContentTbl ){
130991    /* If using the content=xxx option, assume the table is never empty */
130992    *pisEmpty = 0;
130993    rc = SQLITE_OK;
130994  }else{
130995    rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
130996    if( rc==SQLITE_OK ){
130997      if( SQLITE_ROW==sqlite3_step(pStmt) ){
130998        *pisEmpty = sqlite3_column_int(pStmt, 0);
130999      }
131000      rc = sqlite3_reset(pStmt);
131001    }
131002  }
131003  return rc;
131004}
131005
131006/*
131007** Set *pnMax to the largest segment level in the database for the index
131008** iIndex.
131009**
131010** Segment levels are stored in the 'level' column of the %_segdir table.
131011**
131012** Return SQLITE_OK if successful, or an SQLite error code if not.
131013*/
131014static int fts3SegmentMaxLevel(
131015  Fts3Table *p,
131016  int iLangid,
131017  int iIndex,
131018  sqlite3_int64 *pnMax
131019){
131020  sqlite3_stmt *pStmt;
131021  int rc;
131022  assert( iIndex>=0 && iIndex<p->nIndex );
131023
131024  /* Set pStmt to the compiled version of:
131025  **
131026  **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
131027  **
131028  ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
131029  */
131030  rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
131031  if( rc!=SQLITE_OK ) return rc;
131032  sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
131033  sqlite3_bind_int64(pStmt, 2,
131034      getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
131035  );
131036  if( SQLITE_ROW==sqlite3_step(pStmt) ){
131037    *pnMax = sqlite3_column_int64(pStmt, 0);
131038  }
131039  return sqlite3_reset(pStmt);
131040}
131041
131042/*
131043** Delete all entries in the %_segments table associated with the segment
131044** opened with seg-reader pSeg. This function does not affect the contents
131045** of the %_segdir table.
131046*/
131047static int fts3DeleteSegment(
131048  Fts3Table *p,                   /* FTS table handle */
131049  Fts3SegReader *pSeg             /* Segment to delete */
131050){
131051  int rc = SQLITE_OK;             /* Return code */
131052  if( pSeg->iStartBlock ){
131053    sqlite3_stmt *pDelete;        /* SQL statement to delete rows */
131054    rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
131055    if( rc==SQLITE_OK ){
131056      sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
131057      sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
131058      sqlite3_step(pDelete);
131059      rc = sqlite3_reset(pDelete);
131060    }
131061  }
131062  return rc;
131063}
131064
131065/*
131066** This function is used after merging multiple segments into a single large
131067** segment to delete the old, now redundant, segment b-trees. Specifically,
131068** it:
131069**
131070**   1) Deletes all %_segments entries for the segments associated with
131071**      each of the SegReader objects in the array passed as the third
131072**      argument, and
131073**
131074**   2) deletes all %_segdir entries with level iLevel, or all %_segdir
131075**      entries regardless of level if (iLevel<0).
131076**
131077** SQLITE_OK is returned if successful, otherwise an SQLite error code.
131078*/
131079static int fts3DeleteSegdir(
131080  Fts3Table *p,                   /* Virtual table handle */
131081  int iLangid,                    /* Language id */
131082  int iIndex,                     /* Index for p->aIndex */
131083  int iLevel,                     /* Level of %_segdir entries to delete */
131084  Fts3SegReader **apSegment,      /* Array of SegReader objects */
131085  int nReader                     /* Size of array apSegment */
131086){
131087  int rc = SQLITE_OK;             /* Return Code */
131088  int i;                          /* Iterator variable */
131089  sqlite3_stmt *pDelete = 0;      /* SQL statement to delete rows */
131090
131091  for(i=0; rc==SQLITE_OK && i<nReader; i++){
131092    rc = fts3DeleteSegment(p, apSegment[i]);
131093  }
131094  if( rc!=SQLITE_OK ){
131095    return rc;
131096  }
131097
131098  assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
131099  if( iLevel==FTS3_SEGCURSOR_ALL ){
131100    rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
131101    if( rc==SQLITE_OK ){
131102      sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
131103      sqlite3_bind_int64(pDelete, 2,
131104          getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
131105      );
131106    }
131107  }else{
131108    rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
131109    if( rc==SQLITE_OK ){
131110      sqlite3_bind_int64(
131111          pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
131112      );
131113    }
131114  }
131115
131116  if( rc==SQLITE_OK ){
131117    sqlite3_step(pDelete);
131118    rc = sqlite3_reset(pDelete);
131119  }
131120
131121  return rc;
131122}
131123
131124/*
131125** When this function is called, buffer *ppList (size *pnList bytes) contains
131126** a position list that may (or may not) feature multiple columns. This
131127** function adjusts the pointer *ppList and the length *pnList so that they
131128** identify the subset of the position list that corresponds to column iCol.
131129**
131130** If there are no entries in the input position list for column iCol, then
131131** *pnList is set to zero before returning.
131132**
131133** If parameter bZero is non-zero, then any part of the input list following
131134** the end of the output list is zeroed before returning.
131135*/
131136static void fts3ColumnFilter(
131137  int iCol,                       /* Column to filter on */
131138  int bZero,                      /* Zero out anything following *ppList */
131139  char **ppList,                  /* IN/OUT: Pointer to position list */
131140  int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */
131141){
131142  char *pList = *ppList;
131143  int nList = *pnList;
131144  char *pEnd = &pList[nList];
131145  int iCurrent = 0;
131146  char *p = pList;
131147
131148  assert( iCol>=0 );
131149  while( 1 ){
131150    char c = 0;
131151    while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
131152
131153    if( iCol==iCurrent ){
131154      nList = (int)(p - pList);
131155      break;
131156    }
131157
131158    nList -= (int)(p - pList);
131159    pList = p;
131160    if( nList==0 ){
131161      break;
131162    }
131163    p = &pList[1];
131164    p += sqlite3Fts3GetVarint32(p, &iCurrent);
131165  }
131166
131167  if( bZero && &pList[nList]!=pEnd ){
131168    memset(&pList[nList], 0, pEnd - &pList[nList]);
131169  }
131170  *ppList = pList;
131171  *pnList = nList;
131172}
131173
131174/*
131175** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
131176** existing data). Grow the buffer if required.
131177**
131178** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
131179** trying to resize the buffer, return SQLITE_NOMEM.
131180*/
131181static int fts3MsrBufferData(
131182  Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
131183  char *pList,
131184  int nList
131185){
131186  if( nList>pMsr->nBuffer ){
131187    char *pNew;
131188    pMsr->nBuffer = nList*2;
131189    pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
131190    if( !pNew ) return SQLITE_NOMEM;
131191    pMsr->aBuffer = pNew;
131192  }
131193
131194  memcpy(pMsr->aBuffer, pList, nList);
131195  return SQLITE_OK;
131196}
131197
131198SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
131199  Fts3Table *p,                   /* Virtual table handle */
131200  Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
131201  sqlite3_int64 *piDocid,         /* OUT: Docid value */
131202  char **paPoslist,               /* OUT: Pointer to position list */
131203  int *pnPoslist                  /* OUT: Size of position list in bytes */
131204){
131205  int nMerge = pMsr->nAdvance;
131206  Fts3SegReader **apSegment = pMsr->apSegment;
131207  int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
131208    p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
131209  );
131210
131211  if( nMerge==0 ){
131212    *paPoslist = 0;
131213    return SQLITE_OK;
131214  }
131215
131216  while( 1 ){
131217    Fts3SegReader *pSeg;
131218    pSeg = pMsr->apSegment[0];
131219
131220    if( pSeg->pOffsetList==0 ){
131221      *paPoslist = 0;
131222      break;
131223    }else{
131224      int rc;
131225      char *pList;
131226      int nList;
131227      int j;
131228      sqlite3_int64 iDocid = apSegment[0]->iDocid;
131229
131230      rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
131231      j = 1;
131232      while( rc==SQLITE_OK
131233        && j<nMerge
131234        && apSegment[j]->pOffsetList
131235        && apSegment[j]->iDocid==iDocid
131236      ){
131237        rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
131238        j++;
131239      }
131240      if( rc!=SQLITE_OK ) return rc;
131241      fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
131242
131243      if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
131244        rc = fts3MsrBufferData(pMsr, pList, nList+1);
131245        if( rc!=SQLITE_OK ) return rc;
131246        assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
131247        pList = pMsr->aBuffer;
131248      }
131249
131250      if( pMsr->iColFilter>=0 ){
131251        fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
131252      }
131253
131254      if( nList>0 ){
131255        *paPoslist = pList;
131256        *piDocid = iDocid;
131257        *pnPoslist = nList;
131258        break;
131259      }
131260    }
131261  }
131262
131263  return SQLITE_OK;
131264}
131265
131266static int fts3SegReaderStart(
131267  Fts3Table *p,                   /* Virtual table handle */
131268  Fts3MultiSegReader *pCsr,       /* Cursor object */
131269  const char *zTerm,              /* Term searched for (or NULL) */
131270  int nTerm                       /* Length of zTerm in bytes */
131271){
131272  int i;
131273  int nSeg = pCsr->nSegment;
131274
131275  /* If the Fts3SegFilter defines a specific term (or term prefix) to search
131276  ** for, then advance each segment iterator until it points to a term of
131277  ** equal or greater value than the specified term. This prevents many
131278  ** unnecessary merge/sort operations for the case where single segment
131279  ** b-tree leaf nodes contain more than one term.
131280  */
131281  for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
131282    int res = 0;
131283    Fts3SegReader *pSeg = pCsr->apSegment[i];
131284    do {
131285      int rc = fts3SegReaderNext(p, pSeg, 0);
131286      if( rc!=SQLITE_OK ) return rc;
131287    }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
131288
131289    if( pSeg->bLookup && res!=0 ){
131290      fts3SegReaderSetEof(pSeg);
131291    }
131292  }
131293  fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
131294
131295  return SQLITE_OK;
131296}
131297
131298SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
131299  Fts3Table *p,                   /* Virtual table handle */
131300  Fts3MultiSegReader *pCsr,       /* Cursor object */
131301  Fts3SegFilter *pFilter          /* Restrictions on range of iteration */
131302){
131303  pCsr->pFilter = pFilter;
131304  return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
131305}
131306
131307SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
131308  Fts3Table *p,                   /* Virtual table handle */
131309  Fts3MultiSegReader *pCsr,       /* Cursor object */
131310  int iCol,                       /* Column to match on. */
131311  const char *zTerm,              /* Term to iterate through a doclist for */
131312  int nTerm                       /* Number of bytes in zTerm */
131313){
131314  int i;
131315  int rc;
131316  int nSegment = pCsr->nSegment;
131317  int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
131318    p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
131319  );
131320
131321  assert( pCsr->pFilter==0 );
131322  assert( zTerm && nTerm>0 );
131323
131324  /* Advance each segment iterator until it points to the term zTerm/nTerm. */
131325  rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
131326  if( rc!=SQLITE_OK ) return rc;
131327
131328  /* Determine how many of the segments actually point to zTerm/nTerm. */
131329  for(i=0; i<nSegment; i++){
131330    Fts3SegReader *pSeg = pCsr->apSegment[i];
131331    if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
131332      break;
131333    }
131334  }
131335  pCsr->nAdvance = i;
131336
131337  /* Advance each of the segments to point to the first docid. */
131338  for(i=0; i<pCsr->nAdvance; i++){
131339    rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
131340    if( rc!=SQLITE_OK ) return rc;
131341  }
131342  fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
131343
131344  assert( iCol<0 || iCol<p->nColumn );
131345  pCsr->iColFilter = iCol;
131346
131347  return SQLITE_OK;
131348}
131349
131350/*
131351** This function is called on a MultiSegReader that has been started using
131352** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
131353** have been made. Calling this function puts the MultiSegReader in such
131354** a state that if the next two calls are:
131355**
131356**   sqlite3Fts3SegReaderStart()
131357**   sqlite3Fts3SegReaderStep()
131358**
131359** then the entire doclist for the term is available in
131360** MultiSegReader.aDoclist/nDoclist.
131361*/
131362SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
131363  int i;                          /* Used to iterate through segment-readers */
131364
131365  assert( pCsr->zTerm==0 );
131366  assert( pCsr->nTerm==0 );
131367  assert( pCsr->aDoclist==0 );
131368  assert( pCsr->nDoclist==0 );
131369
131370  pCsr->nAdvance = 0;
131371  pCsr->bRestart = 1;
131372  for(i=0; i<pCsr->nSegment; i++){
131373    pCsr->apSegment[i]->pOffsetList = 0;
131374    pCsr->apSegment[i]->nOffsetList = 0;
131375    pCsr->apSegment[i]->iDocid = 0;
131376  }
131377
131378  return SQLITE_OK;
131379}
131380
131381
131382SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
131383  Fts3Table *p,                   /* Virtual table handle */
131384  Fts3MultiSegReader *pCsr        /* Cursor object */
131385){
131386  int rc = SQLITE_OK;
131387
131388  int isIgnoreEmpty =  (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
131389  int isRequirePos =   (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
131390  int isColFilter =    (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
131391  int isPrefix =       (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
131392  int isScan =         (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
131393  int isFirst =        (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
131394
131395  Fts3SegReader **apSegment = pCsr->apSegment;
131396  int nSegment = pCsr->nSegment;
131397  Fts3SegFilter *pFilter = pCsr->pFilter;
131398  int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
131399    p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
131400  );
131401
131402  if( pCsr->nSegment==0 ) return SQLITE_OK;
131403
131404  do {
131405    int nMerge;
131406    int i;
131407
131408    /* Advance the first pCsr->nAdvance entries in the apSegment[] array
131409    ** forward. Then sort the list in order of current term again.
131410    */
131411    for(i=0; i<pCsr->nAdvance; i++){
131412      Fts3SegReader *pSeg = apSegment[i];
131413      if( pSeg->bLookup ){
131414        fts3SegReaderSetEof(pSeg);
131415      }else{
131416        rc = fts3SegReaderNext(p, pSeg, 0);
131417      }
131418      if( rc!=SQLITE_OK ) return rc;
131419    }
131420    fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
131421    pCsr->nAdvance = 0;
131422
131423    /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
131424    assert( rc==SQLITE_OK );
131425    if( apSegment[0]->aNode==0 ) break;
131426
131427    pCsr->nTerm = apSegment[0]->nTerm;
131428    pCsr->zTerm = apSegment[0]->zTerm;
131429
131430    /* If this is a prefix-search, and if the term that apSegment[0] points
131431    ** to does not share a suffix with pFilter->zTerm/nTerm, then all
131432    ** required callbacks have been made. In this case exit early.
131433    **
131434    ** Similarly, if this is a search for an exact match, and the first term
131435    ** of segment apSegment[0] is not a match, exit early.
131436    */
131437    if( pFilter->zTerm && !isScan ){
131438      if( pCsr->nTerm<pFilter->nTerm
131439       || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
131440       || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
131441      ){
131442        break;
131443      }
131444    }
131445
131446    nMerge = 1;
131447    while( nMerge<nSegment
131448        && apSegment[nMerge]->aNode
131449        && apSegment[nMerge]->nTerm==pCsr->nTerm
131450        && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
131451    ){
131452      nMerge++;
131453    }
131454
131455    assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
131456    if( nMerge==1
131457     && !isIgnoreEmpty
131458     && !isFirst
131459     && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
131460    ){
131461      pCsr->nDoclist = apSegment[0]->nDoclist;
131462      if( fts3SegReaderIsPending(apSegment[0]) ){
131463        rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
131464        pCsr->aDoclist = pCsr->aBuffer;
131465      }else{
131466        pCsr->aDoclist = apSegment[0]->aDoclist;
131467      }
131468      if( rc==SQLITE_OK ) rc = SQLITE_ROW;
131469    }else{
131470      int nDoclist = 0;           /* Size of doclist */
131471      sqlite3_int64 iPrev = 0;    /* Previous docid stored in doclist */
131472
131473      /* The current term of the first nMerge entries in the array
131474      ** of Fts3SegReader objects is the same. The doclists must be merged
131475      ** and a single term returned with the merged doclist.
131476      */
131477      for(i=0; i<nMerge; i++){
131478        fts3SegReaderFirstDocid(p, apSegment[i]);
131479      }
131480      fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
131481      while( apSegment[0]->pOffsetList ){
131482        int j;                    /* Number of segments that share a docid */
131483        char *pList;
131484        int nList;
131485        int nByte;
131486        sqlite3_int64 iDocid = apSegment[0]->iDocid;
131487        fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
131488        j = 1;
131489        while( j<nMerge
131490            && apSegment[j]->pOffsetList
131491            && apSegment[j]->iDocid==iDocid
131492        ){
131493          fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
131494          j++;
131495        }
131496
131497        if( isColFilter ){
131498          fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
131499        }
131500
131501        if( !isIgnoreEmpty || nList>0 ){
131502
131503          /* Calculate the 'docid' delta value to write into the merged
131504          ** doclist. */
131505          sqlite3_int64 iDelta;
131506          if( p->bDescIdx && nDoclist>0 ){
131507            iDelta = iPrev - iDocid;
131508          }else{
131509            iDelta = iDocid - iPrev;
131510          }
131511          assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
131512          assert( nDoclist>0 || iDelta==iDocid );
131513
131514          nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
131515          if( nDoclist+nByte>pCsr->nBuffer ){
131516            char *aNew;
131517            pCsr->nBuffer = (nDoclist+nByte)*2;
131518            aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
131519            if( !aNew ){
131520              return SQLITE_NOMEM;
131521            }
131522            pCsr->aBuffer = aNew;
131523          }
131524
131525          if( isFirst ){
131526            char *a = &pCsr->aBuffer[nDoclist];
131527            int nWrite;
131528
131529            nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
131530            if( nWrite ){
131531              iPrev = iDocid;
131532              nDoclist += nWrite;
131533            }
131534          }else{
131535            nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
131536            iPrev = iDocid;
131537            if( isRequirePos ){
131538              memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
131539              nDoclist += nList;
131540              pCsr->aBuffer[nDoclist++] = '\0';
131541            }
131542          }
131543        }
131544
131545        fts3SegReaderSort(apSegment, nMerge, j, xCmp);
131546      }
131547      if( nDoclist>0 ){
131548        pCsr->aDoclist = pCsr->aBuffer;
131549        pCsr->nDoclist = nDoclist;
131550        rc = SQLITE_ROW;
131551      }
131552    }
131553    pCsr->nAdvance = nMerge;
131554  }while( rc==SQLITE_OK );
131555
131556  return rc;
131557}
131558
131559
131560SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
131561  Fts3MultiSegReader *pCsr       /* Cursor object */
131562){
131563  if( pCsr ){
131564    int i;
131565    for(i=0; i<pCsr->nSegment; i++){
131566      sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
131567    }
131568    sqlite3_free(pCsr->apSegment);
131569    sqlite3_free(pCsr->aBuffer);
131570
131571    pCsr->nSegment = 0;
131572    pCsr->apSegment = 0;
131573    pCsr->aBuffer = 0;
131574  }
131575}
131576
131577/*
131578** Merge all level iLevel segments in the database into a single
131579** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
131580** single segment with a level equal to the numerically largest level
131581** currently present in the database.
131582**
131583** If this function is called with iLevel<0, but there is only one
131584** segment in the database, SQLITE_DONE is returned immediately.
131585** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
131586** an SQLite error code is returned.
131587*/
131588static int fts3SegmentMerge(
131589  Fts3Table *p,
131590  int iLangid,                    /* Language id to merge */
131591  int iIndex,                     /* Index in p->aIndex[] to merge */
131592  int iLevel                      /* Level to merge */
131593){
131594  int rc;                         /* Return code */
131595  int iIdx = 0;                   /* Index of new segment */
131596  sqlite3_int64 iNewLevel = 0;    /* Level/index to create new segment at */
131597  SegmentWriter *pWriter = 0;     /* Used to write the new, merged, segment */
131598  Fts3SegFilter filter;           /* Segment term filter condition */
131599  Fts3MultiSegReader csr;         /* Cursor to iterate through level(s) */
131600  int bIgnoreEmpty = 0;           /* True to ignore empty segments */
131601
131602  assert( iLevel==FTS3_SEGCURSOR_ALL
131603       || iLevel==FTS3_SEGCURSOR_PENDING
131604       || iLevel>=0
131605  );
131606  assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
131607  assert( iIndex>=0 && iIndex<p->nIndex );
131608
131609  rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
131610  if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
131611
131612  if( iLevel==FTS3_SEGCURSOR_ALL ){
131613    /* This call is to merge all segments in the database to a single
131614    ** segment. The level of the new segment is equal to the numerically
131615    ** greatest segment level currently present in the database for this
131616    ** index. The idx of the new segment is always 0.  */
131617    if( csr.nSegment==1 ){
131618      rc = SQLITE_DONE;
131619      goto finished;
131620    }
131621    rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iNewLevel);
131622    bIgnoreEmpty = 1;
131623
131624  }else if( iLevel==FTS3_SEGCURSOR_PENDING ){
131625    iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, 0);
131626    rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, 0, &iIdx);
131627  }else{
131628    /* This call is to merge all segments at level iLevel. find the next
131629    ** available segment index at level iLevel+1. The call to
131630    ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
131631    ** a single iLevel+2 segment if necessary.  */
131632    rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
131633    iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
131634  }
131635  if( rc!=SQLITE_OK ) goto finished;
131636  assert( csr.nSegment>0 );
131637  assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
131638  assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
131639
131640  memset(&filter, 0, sizeof(Fts3SegFilter));
131641  filter.flags = FTS3_SEGMENT_REQUIRE_POS;
131642  filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
131643
131644  rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
131645  while( SQLITE_OK==rc ){
131646    rc = sqlite3Fts3SegReaderStep(p, &csr);
131647    if( rc!=SQLITE_ROW ) break;
131648    rc = fts3SegWriterAdd(p, &pWriter, 1,
131649        csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
131650  }
131651  if( rc!=SQLITE_OK ) goto finished;
131652  assert( pWriter );
131653
131654  if( iLevel!=FTS3_SEGCURSOR_PENDING ){
131655    rc = fts3DeleteSegdir(
131656        p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
131657    );
131658    if( rc!=SQLITE_OK ) goto finished;
131659  }
131660  rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
131661
131662 finished:
131663  fts3SegWriterFree(pWriter);
131664  sqlite3Fts3SegReaderFinish(&csr);
131665  return rc;
131666}
131667
131668
131669/*
131670** Flush the contents of pendingTerms to level 0 segments.
131671*/
131672SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
131673  int rc = SQLITE_OK;
131674  int i;
131675
131676  for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
131677    rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
131678    if( rc==SQLITE_DONE ) rc = SQLITE_OK;
131679  }
131680  sqlite3Fts3PendingTermsClear(p);
131681
131682  /* Determine the auto-incr-merge setting if unknown.  If enabled,
131683  ** estimate the number of leaf blocks of content to be written
131684  */
131685  if( rc==SQLITE_OK && p->bHasStat
131686   && p->bAutoincrmerge==0xff && p->nLeafAdd>0
131687  ){
131688    sqlite3_stmt *pStmt = 0;
131689    rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
131690    if( rc==SQLITE_OK ){
131691      sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
131692      rc = sqlite3_step(pStmt);
131693      p->bAutoincrmerge = (rc==SQLITE_ROW && sqlite3_column_int(pStmt, 0));
131694      rc = sqlite3_reset(pStmt);
131695    }
131696  }
131697  return rc;
131698}
131699
131700/*
131701** Encode N integers as varints into a blob.
131702*/
131703static void fts3EncodeIntArray(
131704  int N,             /* The number of integers to encode */
131705  u32 *a,            /* The integer values */
131706  char *zBuf,        /* Write the BLOB here */
131707  int *pNBuf         /* Write number of bytes if zBuf[] used here */
131708){
131709  int i, j;
131710  for(i=j=0; i<N; i++){
131711    j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
131712  }
131713  *pNBuf = j;
131714}
131715
131716/*
131717** Decode a blob of varints into N integers
131718*/
131719static void fts3DecodeIntArray(
131720  int N,             /* The number of integers to decode */
131721  u32 *a,            /* Write the integer values */
131722  const char *zBuf,  /* The BLOB containing the varints */
131723  int nBuf           /* size of the BLOB */
131724){
131725  int i, j;
131726  UNUSED_PARAMETER(nBuf);
131727  for(i=j=0; i<N; i++){
131728    sqlite3_int64 x;
131729    j += sqlite3Fts3GetVarint(&zBuf[j], &x);
131730    assert(j<=nBuf);
131731    a[i] = (u32)(x & 0xffffffff);
131732  }
131733}
131734
131735/*
131736** Insert the sizes (in tokens) for each column of the document
131737** with docid equal to p->iPrevDocid.  The sizes are encoded as
131738** a blob of varints.
131739*/
131740static void fts3InsertDocsize(
131741  int *pRC,                       /* Result code */
131742  Fts3Table *p,                   /* Table into which to insert */
131743  u32 *aSz                        /* Sizes of each column, in tokens */
131744){
131745  char *pBlob;             /* The BLOB encoding of the document size */
131746  int nBlob;               /* Number of bytes in the BLOB */
131747  sqlite3_stmt *pStmt;     /* Statement used to insert the encoding */
131748  int rc;                  /* Result code from subfunctions */
131749
131750  if( *pRC ) return;
131751  pBlob = sqlite3_malloc( 10*p->nColumn );
131752  if( pBlob==0 ){
131753    *pRC = SQLITE_NOMEM;
131754    return;
131755  }
131756  fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
131757  rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
131758  if( rc ){
131759    sqlite3_free(pBlob);
131760    *pRC = rc;
131761    return;
131762  }
131763  sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
131764  sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
131765  sqlite3_step(pStmt);
131766  *pRC = sqlite3_reset(pStmt);
131767}
131768
131769/*
131770** Record 0 of the %_stat table contains a blob consisting of N varints,
131771** where N is the number of user defined columns in the fts3 table plus
131772** two. If nCol is the number of user defined columns, then values of the
131773** varints are set as follows:
131774**
131775**   Varint 0:       Total number of rows in the table.
131776**
131777**   Varint 1..nCol: For each column, the total number of tokens stored in
131778**                   the column for all rows of the table.
131779**
131780**   Varint 1+nCol:  The total size, in bytes, of all text values in all
131781**                   columns of all rows of the table.
131782**
131783*/
131784static void fts3UpdateDocTotals(
131785  int *pRC,                       /* The result code */
131786  Fts3Table *p,                   /* Table being updated */
131787  u32 *aSzIns,                    /* Size increases */
131788  u32 *aSzDel,                    /* Size decreases */
131789  int nChng                       /* Change in the number of documents */
131790){
131791  char *pBlob;             /* Storage for BLOB written into %_stat */
131792  int nBlob;               /* Size of BLOB written into %_stat */
131793  u32 *a;                  /* Array of integers that becomes the BLOB */
131794  sqlite3_stmt *pStmt;     /* Statement for reading and writing */
131795  int i;                   /* Loop counter */
131796  int rc;                  /* Result code from subfunctions */
131797
131798  const int nStat = p->nColumn+2;
131799
131800  if( *pRC ) return;
131801  a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
131802  if( a==0 ){
131803    *pRC = SQLITE_NOMEM;
131804    return;
131805  }
131806  pBlob = (char*)&a[nStat];
131807  rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
131808  if( rc ){
131809    sqlite3_free(a);
131810    *pRC = rc;
131811    return;
131812  }
131813  sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
131814  if( sqlite3_step(pStmt)==SQLITE_ROW ){
131815    fts3DecodeIntArray(nStat, a,
131816         sqlite3_column_blob(pStmt, 0),
131817         sqlite3_column_bytes(pStmt, 0));
131818  }else{
131819    memset(a, 0, sizeof(u32)*(nStat) );
131820  }
131821  rc = sqlite3_reset(pStmt);
131822  if( rc!=SQLITE_OK ){
131823    sqlite3_free(a);
131824    *pRC = rc;
131825    return;
131826  }
131827  if( nChng<0 && a[0]<(u32)(-nChng) ){
131828    a[0] = 0;
131829  }else{
131830    a[0] += nChng;
131831  }
131832  for(i=0; i<p->nColumn+1; i++){
131833    u32 x = a[i+1];
131834    if( x+aSzIns[i] < aSzDel[i] ){
131835      x = 0;
131836    }else{
131837      x = x + aSzIns[i] - aSzDel[i];
131838    }
131839    a[i+1] = x;
131840  }
131841  fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
131842  rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
131843  if( rc ){
131844    sqlite3_free(a);
131845    *pRC = rc;
131846    return;
131847  }
131848  sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
131849  sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
131850  sqlite3_step(pStmt);
131851  *pRC = sqlite3_reset(pStmt);
131852  sqlite3_free(a);
131853}
131854
131855/*
131856** Merge the entire database so that there is one segment for each
131857** iIndex/iLangid combination.
131858*/
131859static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
131860  int bSeenDone = 0;
131861  int rc;
131862  sqlite3_stmt *pAllLangid = 0;
131863
131864  rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
131865  if( rc==SQLITE_OK ){
131866    int rc2;
131867    sqlite3_bind_int(pAllLangid, 1, p->nIndex);
131868    while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
131869      int i;
131870      int iLangid = sqlite3_column_int(pAllLangid, 0);
131871      for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
131872        rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
131873        if( rc==SQLITE_DONE ){
131874          bSeenDone = 1;
131875          rc = SQLITE_OK;
131876        }
131877      }
131878    }
131879    rc2 = sqlite3_reset(pAllLangid);
131880    if( rc==SQLITE_OK ) rc = rc2;
131881  }
131882
131883  sqlite3Fts3SegmentsClose(p);
131884  sqlite3Fts3PendingTermsClear(p);
131885
131886  return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
131887}
131888
131889/*
131890** This function is called when the user executes the following statement:
131891**
131892**     INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
131893**
131894** The entire FTS index is discarded and rebuilt. If the table is one
131895** created using the content=xxx option, then the new index is based on
131896** the current contents of the xxx table. Otherwise, it is rebuilt based
131897** on the contents of the %_content table.
131898*/
131899static int fts3DoRebuild(Fts3Table *p){
131900  int rc;                         /* Return Code */
131901
131902  rc = fts3DeleteAll(p, 0);
131903  if( rc==SQLITE_OK ){
131904    u32 *aSz = 0;
131905    u32 *aSzIns = 0;
131906    u32 *aSzDel = 0;
131907    sqlite3_stmt *pStmt = 0;
131908    int nEntry = 0;
131909
131910    /* Compose and prepare an SQL statement to loop through the content table */
131911    char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
131912    if( !zSql ){
131913      rc = SQLITE_NOMEM;
131914    }else{
131915      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
131916      sqlite3_free(zSql);
131917    }
131918
131919    if( rc==SQLITE_OK ){
131920      int nByte = sizeof(u32) * (p->nColumn+1)*3;
131921      aSz = (u32 *)sqlite3_malloc(nByte);
131922      if( aSz==0 ){
131923        rc = SQLITE_NOMEM;
131924      }else{
131925        memset(aSz, 0, nByte);
131926        aSzIns = &aSz[p->nColumn+1];
131927        aSzDel = &aSzIns[p->nColumn+1];
131928      }
131929    }
131930
131931    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
131932      int iCol;
131933      int iLangid = langidFromSelect(p, pStmt);
131934      rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pStmt, 0));
131935      memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
131936      for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
131937        const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
131938        rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
131939        aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
131940      }
131941      if( p->bHasDocsize ){
131942        fts3InsertDocsize(&rc, p, aSz);
131943      }
131944      if( rc!=SQLITE_OK ){
131945        sqlite3_finalize(pStmt);
131946        pStmt = 0;
131947      }else{
131948        nEntry++;
131949        for(iCol=0; iCol<=p->nColumn; iCol++){
131950          aSzIns[iCol] += aSz[iCol];
131951        }
131952      }
131953    }
131954    if( p->bFts4 ){
131955      fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
131956    }
131957    sqlite3_free(aSz);
131958
131959    if( pStmt ){
131960      int rc2 = sqlite3_finalize(pStmt);
131961      if( rc==SQLITE_OK ){
131962        rc = rc2;
131963      }
131964    }
131965  }
131966
131967  return rc;
131968}
131969
131970
131971/*
131972** This function opens a cursor used to read the input data for an
131973** incremental merge operation. Specifically, it opens a cursor to scan
131974** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute
131975** level iAbsLevel.
131976*/
131977static int fts3IncrmergeCsr(
131978  Fts3Table *p,                   /* FTS3 table handle */
131979  sqlite3_int64 iAbsLevel,        /* Absolute level to open */
131980  int nSeg,                       /* Number of segments to merge */
131981  Fts3MultiSegReader *pCsr        /* Cursor object to populate */
131982){
131983  int rc;                         /* Return Code */
131984  sqlite3_stmt *pStmt = 0;        /* Statement used to read %_segdir entry */
131985  int nByte;                      /* Bytes allocated at pCsr->apSegment[] */
131986
131987  /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
131988  memset(pCsr, 0, sizeof(*pCsr));
131989  nByte = sizeof(Fts3SegReader *) * nSeg;
131990  pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
131991
131992  if( pCsr->apSegment==0 ){
131993    rc = SQLITE_NOMEM;
131994  }else{
131995    memset(pCsr->apSegment, 0, nByte);
131996    rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
131997  }
131998  if( rc==SQLITE_OK ){
131999    int i;
132000    int rc2;
132001    sqlite3_bind_int64(pStmt, 1, iAbsLevel);
132002    assert( pCsr->nSegment==0 );
132003    for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
132004      rc = sqlite3Fts3SegReaderNew(i, 0,
132005          sqlite3_column_int64(pStmt, 1),        /* segdir.start_block */
132006          sqlite3_column_int64(pStmt, 2),        /* segdir.leaves_end_block */
132007          sqlite3_column_int64(pStmt, 3),        /* segdir.end_block */
132008          sqlite3_column_blob(pStmt, 4),         /* segdir.root */
132009          sqlite3_column_bytes(pStmt, 4),        /* segdir.root */
132010          &pCsr->apSegment[i]
132011      );
132012      pCsr->nSegment++;
132013    }
132014    rc2 = sqlite3_reset(pStmt);
132015    if( rc==SQLITE_OK ) rc = rc2;
132016  }
132017
132018  return rc;
132019}
132020
132021typedef struct IncrmergeWriter IncrmergeWriter;
132022typedef struct NodeWriter NodeWriter;
132023typedef struct Blob Blob;
132024typedef struct NodeReader NodeReader;
132025
132026/*
132027** An instance of the following structure is used as a dynamic buffer
132028** to build up nodes or other blobs of data in.
132029**
132030** The function blobGrowBuffer() is used to extend the allocation.
132031*/
132032struct Blob {
132033  char *a;                        /* Pointer to allocation */
132034  int n;                          /* Number of valid bytes of data in a[] */
132035  int nAlloc;                     /* Allocated size of a[] (nAlloc>=n) */
132036};
132037
132038/*
132039** This structure is used to build up buffers containing segment b-tree
132040** nodes (blocks).
132041*/
132042struct NodeWriter {
132043  sqlite3_int64 iBlock;           /* Current block id */
132044  Blob key;                       /* Last key written to the current block */
132045  Blob block;                     /* Current block image */
132046};
132047
132048/*
132049** An object of this type contains the state required to create or append
132050** to an appendable b-tree segment.
132051*/
132052struct IncrmergeWriter {
132053  int nLeafEst;                   /* Space allocated for leaf blocks */
132054  int nWork;                      /* Number of leaf pages flushed */
132055  sqlite3_int64 iAbsLevel;        /* Absolute level of input segments */
132056  int iIdx;                       /* Index of *output* segment in iAbsLevel+1 */
132057  sqlite3_int64 iStart;           /* Block number of first allocated block */
132058  sqlite3_int64 iEnd;             /* Block number of last allocated block */
132059  NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
132060};
132061
132062/*
132063** An object of the following type is used to read data from a single
132064** FTS segment node. See the following functions:
132065**
132066**     nodeReaderInit()
132067**     nodeReaderNext()
132068**     nodeReaderRelease()
132069*/
132070struct NodeReader {
132071  const char *aNode;
132072  int nNode;
132073  int iOff;                       /* Current offset within aNode[] */
132074
132075  /* Output variables. Containing the current node entry. */
132076  sqlite3_int64 iChild;           /* Pointer to child node */
132077  Blob term;                      /* Current term */
132078  const char *aDoclist;           /* Pointer to doclist */
132079  int nDoclist;                   /* Size of doclist in bytes */
132080};
132081
132082/*
132083** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
132084** Otherwise, if the allocation at pBlob->a is not already at least nMin
132085** bytes in size, extend (realloc) it to be so.
132086**
132087** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
132088** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
132089** to reflect the new size of the pBlob->a[] buffer.
132090*/
132091static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
132092  if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
132093    int nAlloc = nMin;
132094    char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
132095    if( a ){
132096      pBlob->nAlloc = nAlloc;
132097      pBlob->a = a;
132098    }else{
132099      *pRc = SQLITE_NOMEM;
132100    }
132101  }
132102}
132103
132104/*
132105** Attempt to advance the node-reader object passed as the first argument to
132106** the next entry on the node.
132107**
132108** Return an error code if an error occurs (SQLITE_NOMEM is possible).
132109** Otherwise return SQLITE_OK. If there is no next entry on the node
132110** (e.g. because the current entry is the last) set NodeReader->aNode to
132111** NULL to indicate EOF. Otherwise, populate the NodeReader structure output
132112** variables for the new entry.
132113*/
132114static int nodeReaderNext(NodeReader *p){
132115  int bFirst = (p->term.n==0);    /* True for first term on the node */
132116  int nPrefix = 0;                /* Bytes to copy from previous term */
132117  int nSuffix = 0;                /* Bytes to append to the prefix */
132118  int rc = SQLITE_OK;             /* Return code */
132119
132120  assert( p->aNode );
132121  if( p->iChild && bFirst==0 ) p->iChild++;
132122  if( p->iOff>=p->nNode ){
132123    /* EOF */
132124    p->aNode = 0;
132125  }else{
132126    if( bFirst==0 ){
132127      p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
132128    }
132129    p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
132130
132131    blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
132132    if( rc==SQLITE_OK ){
132133      memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
132134      p->term.n = nPrefix+nSuffix;
132135      p->iOff += nSuffix;
132136      if( p->iChild==0 ){
132137        p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
132138        p->aDoclist = &p->aNode[p->iOff];
132139        p->iOff += p->nDoclist;
132140      }
132141    }
132142  }
132143
132144  assert( p->iOff<=p->nNode );
132145
132146  return rc;
132147}
132148
132149/*
132150** Release all dynamic resources held by node-reader object *p.
132151*/
132152static void nodeReaderRelease(NodeReader *p){
132153  sqlite3_free(p->term.a);
132154}
132155
132156/*
132157** Initialize a node-reader object to read the node in buffer aNode/nNode.
132158**
132159** If successful, SQLITE_OK is returned and the NodeReader object set to
132160** point to the first entry on the node (if any). Otherwise, an SQLite
132161** error code is returned.
132162*/
132163static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
132164  memset(p, 0, sizeof(NodeReader));
132165  p->aNode = aNode;
132166  p->nNode = nNode;
132167
132168  /* Figure out if this is a leaf or an internal node. */
132169  if( p->aNode[0] ){
132170    /* An internal node. */
132171    p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
132172  }else{
132173    p->iOff = 1;
132174  }
132175
132176  return nodeReaderNext(p);
132177}
132178
132179/*
132180** This function is called while writing an FTS segment each time a leaf o
132181** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
132182** to be greater than the largest key on the node just written, but smaller
132183** than or equal to the first key that will be written to the next leaf
132184** node.
132185**
132186** The block id of the leaf node just written to disk may be found in
132187** (pWriter->aNodeWriter[0].iBlock) when this function is called.
132188*/
132189static int fts3IncrmergePush(
132190  Fts3Table *p,                   /* Fts3 table handle */
132191  IncrmergeWriter *pWriter,       /* Writer object */
132192  const char *zTerm,              /* Term to write to internal node */
132193  int nTerm                       /* Bytes at zTerm */
132194){
132195  sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
132196  int iLayer;
132197
132198  assert( nTerm>0 );
132199  for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
132200    sqlite3_int64 iNextPtr = 0;
132201    NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
132202    int rc = SQLITE_OK;
132203    int nPrefix;
132204    int nSuffix;
132205    int nSpace;
132206
132207    /* Figure out how much space the key will consume if it is written to
132208    ** the current node of layer iLayer. Due to the prefix compression,
132209    ** the space required changes depending on which node the key is to
132210    ** be added to.  */
132211    nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
132212    nSuffix = nTerm - nPrefix;
132213    nSpace  = sqlite3Fts3VarintLen(nPrefix);
132214    nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
132215
132216    if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){
132217      /* If the current node of layer iLayer contains zero keys, or if adding
132218      ** the key to it will not cause it to grow to larger than nNodeSize
132219      ** bytes in size, write the key here.  */
132220
132221      Blob *pBlk = &pNode->block;
132222      if( pBlk->n==0 ){
132223        blobGrowBuffer(pBlk, p->nNodeSize, &rc);
132224        if( rc==SQLITE_OK ){
132225          pBlk->a[0] = (char)iLayer;
132226          pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
132227        }
132228      }
132229      blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
132230      blobGrowBuffer(&pNode->key, nTerm, &rc);
132231
132232      if( rc==SQLITE_OK ){
132233        if( pNode->key.n ){
132234          pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
132235        }
132236        pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
132237        memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
132238        pBlk->n += nSuffix;
132239
132240        memcpy(pNode->key.a, zTerm, nTerm);
132241        pNode->key.n = nTerm;
132242      }
132243    }else{
132244      /* Otherwise, flush the current node of layer iLayer to disk.
132245      ** Then allocate a new, empty sibling node. The key will be written
132246      ** into the parent of this node. */
132247      rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
132248
132249      assert( pNode->block.nAlloc>=p->nNodeSize );
132250      pNode->block.a[0] = (char)iLayer;
132251      pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
132252
132253      iNextPtr = pNode->iBlock;
132254      pNode->iBlock++;
132255      pNode->key.n = 0;
132256    }
132257
132258    if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
132259    iPtr = iNextPtr;
132260  }
132261
132262  assert( 0 );
132263  return 0;
132264}
132265
132266/*
132267** Append a term and (optionally) doclist to the FTS segment node currently
132268** stored in blob *pNode. The node need not contain any terms, but the
132269** header must be written before this function is called.
132270**
132271** A node header is a single 0x00 byte for a leaf node, or a height varint
132272** followed by the left-hand-child varint for an internal node.
132273**
132274** The term to be appended is passed via arguments zTerm/nTerm. For a
132275** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
132276** node, both aDoclist and nDoclist must be passed 0.
132277**
132278** If the size of the value in blob pPrev is zero, then this is the first
132279** term written to the node. Otherwise, pPrev contains a copy of the
132280** previous term. Before this function returns, it is updated to contain a
132281** copy of zTerm/nTerm.
132282**
132283** It is assumed that the buffer associated with pNode is already large
132284** enough to accommodate the new entry. The buffer associated with pPrev
132285** is extended by this function if requrired.
132286**
132287** If an error (i.e. OOM condition) occurs, an SQLite error code is
132288** returned. Otherwise, SQLITE_OK.
132289*/
132290static int fts3AppendToNode(
132291  Blob *pNode,                    /* Current node image to append to */
132292  Blob *pPrev,                    /* Buffer containing previous term written */
132293  const char *zTerm,              /* New term to write */
132294  int nTerm,                      /* Size of zTerm in bytes */
132295  const char *aDoclist,           /* Doclist (or NULL) to write */
132296  int nDoclist                    /* Size of aDoclist in bytes */
132297){
132298  int rc = SQLITE_OK;             /* Return code */
132299  int bFirst = (pPrev->n==0);     /* True if this is the first term written */
132300  int nPrefix;                    /* Size of term prefix in bytes */
132301  int nSuffix;                    /* Size of term suffix in bytes */
132302
132303  /* Node must have already been started. There must be a doclist for a
132304  ** leaf node, and there must not be a doclist for an internal node.  */
132305  assert( pNode->n>0 );
132306  assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
132307
132308  blobGrowBuffer(pPrev, nTerm, &rc);
132309  if( rc!=SQLITE_OK ) return rc;
132310
132311  nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
132312  nSuffix = nTerm - nPrefix;
132313  memcpy(pPrev->a, zTerm, nTerm);
132314  pPrev->n = nTerm;
132315
132316  if( bFirst==0 ){
132317    pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
132318  }
132319  pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
132320  memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
132321  pNode->n += nSuffix;
132322
132323  if( aDoclist ){
132324    pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
132325    memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
132326    pNode->n += nDoclist;
132327  }
132328
132329  assert( pNode->n<=pNode->nAlloc );
132330
132331  return SQLITE_OK;
132332}
132333
132334/*
132335** Append the current term and doclist pointed to by cursor pCsr to the
132336** appendable b-tree segment opened for writing by pWriter.
132337**
132338** Return SQLITE_OK if successful, or an SQLite error code otherwise.
132339*/
132340static int fts3IncrmergeAppend(
132341  Fts3Table *p,                   /* Fts3 table handle */
132342  IncrmergeWriter *pWriter,       /* Writer object */
132343  Fts3MultiSegReader *pCsr        /* Cursor containing term and doclist */
132344){
132345  const char *zTerm = pCsr->zTerm;
132346  int nTerm = pCsr->nTerm;
132347  const char *aDoclist = pCsr->aDoclist;
132348  int nDoclist = pCsr->nDoclist;
132349  int rc = SQLITE_OK;           /* Return code */
132350  int nSpace;                   /* Total space in bytes required on leaf */
132351  int nPrefix;                  /* Size of prefix shared with previous term */
132352  int nSuffix;                  /* Size of suffix (nTerm - nPrefix) */
132353  NodeWriter *pLeaf;            /* Object used to write leaf nodes */
132354
132355  pLeaf = &pWriter->aNodeWriter[0];
132356  nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
132357  nSuffix = nTerm - nPrefix;
132358
132359  nSpace  = sqlite3Fts3VarintLen(nPrefix);
132360  nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
132361  nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
132362
132363  /* If the current block is not empty, and if adding this term/doclist
132364  ** to the current block would make it larger than Fts3Table.nNodeSize
132365  ** bytes, write this block out to the database. */
132366  if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
132367    rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
132368    pWriter->nWork++;
132369
132370    /* Add the current term to the parent node. The term added to the
132371    ** parent must:
132372    **
132373    **   a) be greater than the largest term on the leaf node just written
132374    **      to the database (still available in pLeaf->key), and
132375    **
132376    **   b) be less than or equal to the term about to be added to the new
132377    **      leaf node (zTerm/nTerm).
132378    **
132379    ** In other words, it must be the prefix of zTerm 1 byte longer than
132380    ** the common prefix (if any) of zTerm and pWriter->zTerm.
132381    */
132382    if( rc==SQLITE_OK ){
132383      rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
132384    }
132385
132386    /* Advance to the next output block */
132387    pLeaf->iBlock++;
132388    pLeaf->key.n = 0;
132389    pLeaf->block.n = 0;
132390
132391    nSuffix = nTerm;
132392    nSpace  = 1;
132393    nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
132394    nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
132395  }
132396
132397  blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
132398
132399  if( rc==SQLITE_OK ){
132400    if( pLeaf->block.n==0 ){
132401      pLeaf->block.n = 1;
132402      pLeaf->block.a[0] = '\0';
132403    }
132404    rc = fts3AppendToNode(
132405        &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
132406    );
132407  }
132408
132409  return rc;
132410}
132411
132412/*
132413** This function is called to release all dynamic resources held by the
132414** merge-writer object pWriter, and if no error has occurred, to flush
132415** all outstanding node buffers held by pWriter to disk.
132416**
132417** If *pRc is not SQLITE_OK when this function is called, then no attempt
132418** is made to write any data to disk. Instead, this function serves only
132419** to release outstanding resources.
132420**
132421** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
132422** flushing buffers to disk, *pRc is set to an SQLite error code before
132423** returning.
132424*/
132425static void fts3IncrmergeRelease(
132426  Fts3Table *p,                   /* FTS3 table handle */
132427  IncrmergeWriter *pWriter,       /* Merge-writer object */
132428  int *pRc                        /* IN/OUT: Error code */
132429){
132430  int i;                          /* Used to iterate through non-root layers */
132431  int iRoot;                      /* Index of root in pWriter->aNodeWriter */
132432  NodeWriter *pRoot;              /* NodeWriter for root node */
132433  int rc = *pRc;                  /* Error code */
132434
132435  /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment
132436  ** root node. If the segment fits entirely on a single leaf node, iRoot
132437  ** will be set to 0. If the root node is the parent of the leaves, iRoot
132438  ** will be 1. And so on.  */
132439  for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
132440    NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
132441    if( pNode->block.n>0 ) break;
132442    assert( *pRc || pNode->block.nAlloc==0 );
132443    assert( *pRc || pNode->key.nAlloc==0 );
132444    sqlite3_free(pNode->block.a);
132445    sqlite3_free(pNode->key.a);
132446  }
132447
132448  /* Empty output segment. This is a no-op. */
132449  if( iRoot<0 ) return;
132450
132451  /* The entire output segment fits on a single node. Normally, this means
132452  ** the node would be stored as a blob in the "root" column of the %_segdir
132453  ** table. However, this is not permitted in this case. The problem is that
132454  ** space has already been reserved in the %_segments table, and so the
132455  ** start_block and end_block fields of the %_segdir table must be populated.
132456  ** And, by design or by accident, released versions of FTS cannot handle
132457  ** segments that fit entirely on the root node with start_block!=0.
132458  **
132459  ** Instead, create a synthetic root node that contains nothing but a
132460  ** pointer to the single content node. So that the segment consists of a
132461  ** single leaf and a single interior (root) node.
132462  **
132463  ** Todo: Better might be to defer allocating space in the %_segments
132464  ** table until we are sure it is needed.
132465  */
132466  if( iRoot==0 ){
132467    Blob *pBlock = &pWriter->aNodeWriter[1].block;
132468    blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
132469    if( rc==SQLITE_OK ){
132470      pBlock->a[0] = 0x01;
132471      pBlock->n = 1 + sqlite3Fts3PutVarint(
132472          &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
132473      );
132474    }
132475    iRoot = 1;
132476  }
132477  pRoot = &pWriter->aNodeWriter[iRoot];
132478
132479  /* Flush all currently outstanding nodes to disk. */
132480  for(i=0; i<iRoot; i++){
132481    NodeWriter *pNode = &pWriter->aNodeWriter[i];
132482    if( pNode->block.n>0 && rc==SQLITE_OK ){
132483      rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
132484    }
132485    sqlite3_free(pNode->block.a);
132486    sqlite3_free(pNode->key.a);
132487  }
132488
132489  /* Write the %_segdir record. */
132490  if( rc==SQLITE_OK ){
132491    rc = fts3WriteSegdir(p,
132492        pWriter->iAbsLevel+1,               /* level */
132493        pWriter->iIdx,                      /* idx */
132494        pWriter->iStart,                    /* start_block */
132495        pWriter->aNodeWriter[0].iBlock,     /* leaves_end_block */
132496        pWriter->iEnd,                      /* end_block */
132497        pRoot->block.a, pRoot->block.n      /* root */
132498    );
132499  }
132500  sqlite3_free(pRoot->block.a);
132501  sqlite3_free(pRoot->key.a);
132502
132503  *pRc = rc;
132504}
132505
132506/*
132507** Compare the term in buffer zLhs (size in bytes nLhs) with that in
132508** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
132509** the other, it is considered to be smaller than the other.
132510**
132511** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
132512** if it is greater.
132513*/
132514static int fts3TermCmp(
132515  const char *zLhs, int nLhs,     /* LHS of comparison */
132516  const char *zRhs, int nRhs      /* RHS of comparison */
132517){
132518  int nCmp = MIN(nLhs, nRhs);
132519  int res;
132520
132521  res = memcmp(zLhs, zRhs, nCmp);
132522  if( res==0 ) res = nLhs - nRhs;
132523
132524  return res;
132525}
132526
132527
132528/*
132529** Query to see if the entry in the %_segments table with blockid iEnd is
132530** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
132531** returning. Otherwise, set *pbRes to 0.
132532**
132533** Or, if an error occurs while querying the database, return an SQLite
132534** error code. The final value of *pbRes is undefined in this case.
132535**
132536** This is used to test if a segment is an "appendable" segment. If it
132537** is, then a NULL entry has been inserted into the %_segments table
132538** with blockid %_segdir.end_block.
132539*/
132540static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
132541  int bRes = 0;                   /* Result to set *pbRes to */
132542  sqlite3_stmt *pCheck = 0;       /* Statement to query database with */
132543  int rc;                         /* Return code */
132544
132545  rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
132546  if( rc==SQLITE_OK ){
132547    sqlite3_bind_int64(pCheck, 1, iEnd);
132548    if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
132549    rc = sqlite3_reset(pCheck);
132550  }
132551
132552  *pbRes = bRes;
132553  return rc;
132554}
132555
132556/*
132557** This function is called when initializing an incremental-merge operation.
132558** It checks if the existing segment with index value iIdx at absolute level
132559** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
132560** merge-writer object *pWriter is initialized to write to it.
132561**
132562** An existing segment can be appended to by an incremental merge if:
132563**
132564**   * It was initially created as an appendable segment (with all required
132565**     space pre-allocated), and
132566**
132567**   * The first key read from the input (arguments zKey and nKey) is
132568**     greater than the largest key currently stored in the potential
132569**     output segment.
132570*/
132571static int fts3IncrmergeLoad(
132572  Fts3Table *p,                   /* Fts3 table handle */
132573  sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
132574  int iIdx,                       /* Index of candidate output segment */
132575  const char *zKey,               /* First key to write */
132576  int nKey,                       /* Number of bytes in nKey */
132577  IncrmergeWriter *pWriter        /* Populate this object */
132578){
132579  int rc;                         /* Return code */
132580  sqlite3_stmt *pSelect = 0;      /* SELECT to read %_segdir entry */
132581
132582  rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
132583  if( rc==SQLITE_OK ){
132584    sqlite3_int64 iStart = 0;     /* Value of %_segdir.start_block */
132585    sqlite3_int64 iLeafEnd = 0;   /* Value of %_segdir.leaves_end_block */
132586    sqlite3_int64 iEnd = 0;       /* Value of %_segdir.end_block */
132587    const char *aRoot = 0;        /* Pointer to %_segdir.root buffer */
132588    int nRoot = 0;                /* Size of aRoot[] in bytes */
132589    int rc2;                      /* Return code from sqlite3_reset() */
132590    int bAppendable = 0;          /* Set to true if segment is appendable */
132591
132592    /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
132593    sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
132594    sqlite3_bind_int(pSelect, 2, iIdx);
132595    if( sqlite3_step(pSelect)==SQLITE_ROW ){
132596      iStart = sqlite3_column_int64(pSelect, 1);
132597      iLeafEnd = sqlite3_column_int64(pSelect, 2);
132598      iEnd = sqlite3_column_int64(pSelect, 3);
132599      nRoot = sqlite3_column_bytes(pSelect, 4);
132600      aRoot = sqlite3_column_blob(pSelect, 4);
132601    }else{
132602      return sqlite3_reset(pSelect);
132603    }
132604
132605    /* Check for the zero-length marker in the %_segments table */
132606    rc = fts3IsAppendable(p, iEnd, &bAppendable);
132607
132608    /* Check that zKey/nKey is larger than the largest key the candidate */
132609    if( rc==SQLITE_OK && bAppendable ){
132610      char *aLeaf = 0;
132611      int nLeaf = 0;
132612
132613      rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
132614      if( rc==SQLITE_OK ){
132615        NodeReader reader;
132616        for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
132617            rc==SQLITE_OK && reader.aNode;
132618            rc = nodeReaderNext(&reader)
132619        ){
132620          assert( reader.aNode );
132621        }
132622        if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
132623          bAppendable = 0;
132624        }
132625        nodeReaderRelease(&reader);
132626      }
132627      sqlite3_free(aLeaf);
132628    }
132629
132630    if( rc==SQLITE_OK && bAppendable ){
132631      /* It is possible to append to this segment. Set up the IncrmergeWriter
132632      ** object to do so.  */
132633      int i;
132634      int nHeight = (int)aRoot[0];
132635      NodeWriter *pNode;
132636
132637      pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
132638      pWriter->iStart = iStart;
132639      pWriter->iEnd = iEnd;
132640      pWriter->iAbsLevel = iAbsLevel;
132641      pWriter->iIdx = iIdx;
132642
132643      for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
132644        pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
132645      }
132646
132647      pNode = &pWriter->aNodeWriter[nHeight];
132648      pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
132649      blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
132650      if( rc==SQLITE_OK ){
132651        memcpy(pNode->block.a, aRoot, nRoot);
132652        pNode->block.n = nRoot;
132653      }
132654
132655      for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
132656        NodeReader reader;
132657        pNode = &pWriter->aNodeWriter[i];
132658
132659        rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
132660        while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
132661        blobGrowBuffer(&pNode->key, reader.term.n, &rc);
132662        if( rc==SQLITE_OK ){
132663          memcpy(pNode->key.a, reader.term.a, reader.term.n);
132664          pNode->key.n = reader.term.n;
132665          if( i>0 ){
132666            char *aBlock = 0;
132667            int nBlock = 0;
132668            pNode = &pWriter->aNodeWriter[i-1];
132669            pNode->iBlock = reader.iChild;
132670            rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
132671            blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
132672            if( rc==SQLITE_OK ){
132673              memcpy(pNode->block.a, aBlock, nBlock);
132674              pNode->block.n = nBlock;
132675            }
132676            sqlite3_free(aBlock);
132677          }
132678        }
132679        nodeReaderRelease(&reader);
132680      }
132681    }
132682
132683    rc2 = sqlite3_reset(pSelect);
132684    if( rc==SQLITE_OK ) rc = rc2;
132685  }
132686
132687  return rc;
132688}
132689
132690/*
132691** Determine the largest segment index value that exists within absolute
132692** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
132693** one before returning SQLITE_OK. Or, if there are no segments at all
132694** within level iAbsLevel, set *piIdx to zero.
132695**
132696** If an error occurs, return an SQLite error code. The final value of
132697** *piIdx is undefined in this case.
132698*/
132699static int fts3IncrmergeOutputIdx(
132700  Fts3Table *p,                   /* FTS Table handle */
132701  sqlite3_int64 iAbsLevel,        /* Absolute index of input segments */
132702  int *piIdx                      /* OUT: Next free index at iAbsLevel+1 */
132703){
132704  int rc;
132705  sqlite3_stmt *pOutputIdx = 0;   /* SQL used to find output index */
132706
132707  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
132708  if( rc==SQLITE_OK ){
132709    sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
132710    sqlite3_step(pOutputIdx);
132711    *piIdx = sqlite3_column_int(pOutputIdx, 0);
132712    rc = sqlite3_reset(pOutputIdx);
132713  }
132714
132715  return rc;
132716}
132717
132718/*
132719** Allocate an appendable output segment on absolute level iAbsLevel+1
132720** with idx value iIdx.
132721**
132722** In the %_segdir table, a segment is defined by the values in three
132723** columns:
132724**
132725**     start_block
132726**     leaves_end_block
132727**     end_block
132728**
132729** When an appendable segment is allocated, it is estimated that the
132730** maximum number of leaf blocks that may be required is the sum of the
132731** number of leaf blocks consumed by the input segments, plus the number
132732** of input segments, multiplied by two. This value is stored in stack
132733** variable nLeafEst.
132734**
132735** A total of 16*nLeafEst blocks are allocated when an appendable segment
132736** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
132737** array of leaf nodes starts at the first block allocated. The array
132738** of interior nodes that are parents of the leaf nodes start at block
132739** (start_block + (1 + end_block - start_block) / 16). And so on.
132740**
132741** In the actual code below, the value "16" is replaced with the
132742** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
132743*/
132744static int fts3IncrmergeWriter(
132745  Fts3Table *p,                   /* Fts3 table handle */
132746  sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
132747  int iIdx,                       /* Index of new output segment */
132748  Fts3MultiSegReader *pCsr,       /* Cursor that data will be read from */
132749  IncrmergeWriter *pWriter        /* Populate this object */
132750){
132751  int rc;                         /* Return Code */
132752  int i;                          /* Iterator variable */
132753  int nLeafEst = 0;               /* Blocks allocated for leaf nodes */
132754  sqlite3_stmt *pLeafEst = 0;     /* SQL used to determine nLeafEst */
132755  sqlite3_stmt *pFirstBlock = 0;  /* SQL used to determine first block */
132756
132757  /* Calculate nLeafEst. */
132758  rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
132759  if( rc==SQLITE_OK ){
132760    sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
132761    sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
132762    if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
132763      nLeafEst = sqlite3_column_int(pLeafEst, 0);
132764    }
132765    rc = sqlite3_reset(pLeafEst);
132766  }
132767  if( rc!=SQLITE_OK ) return rc;
132768
132769  /* Calculate the first block to use in the output segment */
132770  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
132771  if( rc==SQLITE_OK ){
132772    if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
132773      pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
132774      pWriter->iEnd = pWriter->iStart - 1;
132775      pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
132776    }
132777    rc = sqlite3_reset(pFirstBlock);
132778  }
132779  if( rc!=SQLITE_OK ) return rc;
132780
132781  /* Insert the marker in the %_segments table to make sure nobody tries
132782  ** to steal the space just allocated. This is also used to identify
132783  ** appendable segments.  */
132784  rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
132785  if( rc!=SQLITE_OK ) return rc;
132786
132787  pWriter->iAbsLevel = iAbsLevel;
132788  pWriter->nLeafEst = nLeafEst;
132789  pWriter->iIdx = iIdx;
132790
132791  /* Set up the array of NodeWriter objects */
132792  for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
132793    pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
132794  }
132795  return SQLITE_OK;
132796}
132797
132798/*
132799** Remove an entry from the %_segdir table. This involves running the
132800** following two statements:
132801**
132802**   DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
132803**   UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
132804**
132805** The DELETE statement removes the specific %_segdir level. The UPDATE
132806** statement ensures that the remaining segments have contiguously allocated
132807** idx values.
132808*/
132809static int fts3RemoveSegdirEntry(
132810  Fts3Table *p,                   /* FTS3 table handle */
132811  sqlite3_int64 iAbsLevel,        /* Absolute level to delete from */
132812  int iIdx                        /* Index of %_segdir entry to delete */
132813){
132814  int rc;                         /* Return code */
132815  sqlite3_stmt *pDelete = 0;      /* DELETE statement */
132816
132817  rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
132818  if( rc==SQLITE_OK ){
132819    sqlite3_bind_int64(pDelete, 1, iAbsLevel);
132820    sqlite3_bind_int(pDelete, 2, iIdx);
132821    sqlite3_step(pDelete);
132822    rc = sqlite3_reset(pDelete);
132823  }
132824
132825  return rc;
132826}
132827
132828/*
132829** One or more segments have just been removed from absolute level iAbsLevel.
132830** Update the 'idx' values of the remaining segments in the level so that
132831** the idx values are a contiguous sequence starting from 0.
132832*/
132833static int fts3RepackSegdirLevel(
132834  Fts3Table *p,                   /* FTS3 table handle */
132835  sqlite3_int64 iAbsLevel         /* Absolute level to repack */
132836){
132837  int rc;                         /* Return code */
132838  int *aIdx = 0;                  /* Array of remaining idx values */
132839  int nIdx = 0;                   /* Valid entries in aIdx[] */
132840  int nAlloc = 0;                 /* Allocated size of aIdx[] */
132841  int i;                          /* Iterator variable */
132842  sqlite3_stmt *pSelect = 0;      /* Select statement to read idx values */
132843  sqlite3_stmt *pUpdate = 0;      /* Update statement to modify idx values */
132844
132845  rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
132846  if( rc==SQLITE_OK ){
132847    int rc2;
132848    sqlite3_bind_int64(pSelect, 1, iAbsLevel);
132849    while( SQLITE_ROW==sqlite3_step(pSelect) ){
132850      if( nIdx>=nAlloc ){
132851        int *aNew;
132852        nAlloc += 16;
132853        aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
132854        if( !aNew ){
132855          rc = SQLITE_NOMEM;
132856          break;
132857        }
132858        aIdx = aNew;
132859      }
132860      aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
132861    }
132862    rc2 = sqlite3_reset(pSelect);
132863    if( rc==SQLITE_OK ) rc = rc2;
132864  }
132865
132866  if( rc==SQLITE_OK ){
132867    rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
132868  }
132869  if( rc==SQLITE_OK ){
132870    sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
132871  }
132872
132873  assert( p->bIgnoreSavepoint==0 );
132874  p->bIgnoreSavepoint = 1;
132875  for(i=0; rc==SQLITE_OK && i<nIdx; i++){
132876    if( aIdx[i]!=i ){
132877      sqlite3_bind_int(pUpdate, 3, aIdx[i]);
132878      sqlite3_bind_int(pUpdate, 1, i);
132879      sqlite3_step(pUpdate);
132880      rc = sqlite3_reset(pUpdate);
132881    }
132882  }
132883  p->bIgnoreSavepoint = 0;
132884
132885  sqlite3_free(aIdx);
132886  return rc;
132887}
132888
132889static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
132890  pNode->a[0] = (char)iHeight;
132891  if( iChild ){
132892    assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
132893    pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
132894  }else{
132895    assert( pNode->nAlloc>=1 );
132896    pNode->n = 1;
132897  }
132898}
132899
132900/*
132901** The first two arguments are a pointer to and the size of a segment b-tree
132902** node. The node may be a leaf or an internal node.
132903**
132904** This function creates a new node image in blob object *pNew by copying
132905** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
132906** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
132907*/
132908static int fts3TruncateNode(
132909  const char *aNode,              /* Current node image */
132910  int nNode,                      /* Size of aNode in bytes */
132911  Blob *pNew,                     /* OUT: Write new node image here */
132912  const char *zTerm,              /* Omit all terms smaller than this */
132913  int nTerm,                      /* Size of zTerm in bytes */
132914  sqlite3_int64 *piBlock          /* OUT: Block number in next layer down */
132915){
132916  NodeReader reader;              /* Reader object */
132917  Blob prev = {0, 0, 0};          /* Previous term written to new node */
132918  int rc = SQLITE_OK;             /* Return code */
132919  int bLeaf = aNode[0]=='\0';     /* True for a leaf node */
132920
132921  /* Allocate required output space */
132922  blobGrowBuffer(pNew, nNode, &rc);
132923  if( rc!=SQLITE_OK ) return rc;
132924  pNew->n = 0;
132925
132926  /* Populate new node buffer */
132927  for(rc = nodeReaderInit(&reader, aNode, nNode);
132928      rc==SQLITE_OK && reader.aNode;
132929      rc = nodeReaderNext(&reader)
132930  ){
132931    if( pNew->n==0 ){
132932      int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
132933      if( res<0 || (bLeaf==0 && res==0) ) continue;
132934      fts3StartNode(pNew, (int)aNode[0], reader.iChild);
132935      *piBlock = reader.iChild;
132936    }
132937    rc = fts3AppendToNode(
132938        pNew, &prev, reader.term.a, reader.term.n,
132939        reader.aDoclist, reader.nDoclist
132940    );
132941    if( rc!=SQLITE_OK ) break;
132942  }
132943  if( pNew->n==0 ){
132944    fts3StartNode(pNew, (int)aNode[0], reader.iChild);
132945    *piBlock = reader.iChild;
132946  }
132947  assert( pNew->n<=pNew->nAlloc );
132948
132949  nodeReaderRelease(&reader);
132950  sqlite3_free(prev.a);
132951  return rc;
132952}
132953
132954/*
132955** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute
132956** level iAbsLevel. This may involve deleting entries from the %_segments
132957** table, and modifying existing entries in both the %_segments and %_segdir
132958** tables.
132959**
132960** SQLITE_OK is returned if the segment is updated successfully. Or an
132961** SQLite error code otherwise.
132962*/
132963static int fts3TruncateSegment(
132964  Fts3Table *p,                   /* FTS3 table handle */
132965  sqlite3_int64 iAbsLevel,        /* Absolute level of segment to modify */
132966  int iIdx,                       /* Index within level of segment to modify */
132967  const char *zTerm,              /* Remove terms smaller than this */
132968  int nTerm                      /* Number of bytes in buffer zTerm */
132969){
132970  int rc = SQLITE_OK;             /* Return code */
132971  Blob root = {0,0,0};            /* New root page image */
132972  Blob block = {0,0,0};           /* Buffer used for any other block */
132973  sqlite3_int64 iBlock = 0;       /* Block id */
132974  sqlite3_int64 iNewStart = 0;    /* New value for iStartBlock */
132975  sqlite3_int64 iOldStart = 0;    /* Old value for iStartBlock */
132976  sqlite3_stmt *pFetch = 0;       /* Statement used to fetch segdir */
132977
132978  rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
132979  if( rc==SQLITE_OK ){
132980    int rc2;                      /* sqlite3_reset() return code */
132981    sqlite3_bind_int64(pFetch, 1, iAbsLevel);
132982    sqlite3_bind_int(pFetch, 2, iIdx);
132983    if( SQLITE_ROW==sqlite3_step(pFetch) ){
132984      const char *aRoot = sqlite3_column_blob(pFetch, 4);
132985      int nRoot = sqlite3_column_bytes(pFetch, 4);
132986      iOldStart = sqlite3_column_int64(pFetch, 1);
132987      rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
132988    }
132989    rc2 = sqlite3_reset(pFetch);
132990    if( rc==SQLITE_OK ) rc = rc2;
132991  }
132992
132993  while( rc==SQLITE_OK && iBlock ){
132994    char *aBlock = 0;
132995    int nBlock = 0;
132996    iNewStart = iBlock;
132997
132998    rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
132999    if( rc==SQLITE_OK ){
133000      rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
133001    }
133002    if( rc==SQLITE_OK ){
133003      rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
133004    }
133005    sqlite3_free(aBlock);
133006  }
133007
133008  /* Variable iNewStart now contains the first valid leaf node. */
133009  if( rc==SQLITE_OK && iNewStart ){
133010    sqlite3_stmt *pDel = 0;
133011    rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
133012    if( rc==SQLITE_OK ){
133013      sqlite3_bind_int64(pDel, 1, iOldStart);
133014      sqlite3_bind_int64(pDel, 2, iNewStart-1);
133015      sqlite3_step(pDel);
133016      rc = sqlite3_reset(pDel);
133017    }
133018  }
133019
133020  if( rc==SQLITE_OK ){
133021    sqlite3_stmt *pChomp = 0;
133022    rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
133023    if( rc==SQLITE_OK ){
133024      sqlite3_bind_int64(pChomp, 1, iNewStart);
133025      sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
133026      sqlite3_bind_int64(pChomp, 3, iAbsLevel);
133027      sqlite3_bind_int(pChomp, 4, iIdx);
133028      sqlite3_step(pChomp);
133029      rc = sqlite3_reset(pChomp);
133030    }
133031  }
133032
133033  sqlite3_free(root.a);
133034  sqlite3_free(block.a);
133035  return rc;
133036}
133037
133038/*
133039** This function is called after an incrmental-merge operation has run to
133040** merge (or partially merge) two or more segments from absolute level
133041** iAbsLevel.
133042**
133043** Each input segment is either removed from the db completely (if all of
133044** its data was copied to the output segment by the incrmerge operation)
133045** or modified in place so that it no longer contains those entries that
133046** have been duplicated in the output segment.
133047*/
133048static int fts3IncrmergeChomp(
133049  Fts3Table *p,                   /* FTS table handle */
133050  sqlite3_int64 iAbsLevel,        /* Absolute level containing segments */
133051  Fts3MultiSegReader *pCsr,       /* Chomp all segments opened by this cursor */
133052  int *pnRem                      /* Number of segments not deleted */
133053){
133054  int i;
133055  int nRem = 0;
133056  int rc = SQLITE_OK;
133057
133058  for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
133059    Fts3SegReader *pSeg = 0;
133060    int j;
133061
133062    /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
133063    ** somewhere in the pCsr->apSegment[] array.  */
133064    for(j=0; ALWAYS(j<pCsr->nSegment); j++){
133065      pSeg = pCsr->apSegment[j];
133066      if( pSeg->iIdx==i ) break;
133067    }
133068    assert( j<pCsr->nSegment && pSeg->iIdx==i );
133069
133070    if( pSeg->aNode==0 ){
133071      /* Seg-reader is at EOF. Remove the entire input segment. */
133072      rc = fts3DeleteSegment(p, pSeg);
133073      if( rc==SQLITE_OK ){
133074        rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
133075      }
133076      *pnRem = 0;
133077    }else{
133078      /* The incremental merge did not copy all the data from this
133079      ** segment to the upper level. The segment is modified in place
133080      ** so that it contains no keys smaller than zTerm/nTerm. */
133081      const char *zTerm = pSeg->zTerm;
133082      int nTerm = pSeg->nTerm;
133083      rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
133084      nRem++;
133085    }
133086  }
133087
133088  if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
133089    rc = fts3RepackSegdirLevel(p, iAbsLevel);
133090  }
133091
133092  *pnRem = nRem;
133093  return rc;
133094}
133095
133096/*
133097** Store an incr-merge hint in the database.
133098*/
133099static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
133100  sqlite3_stmt *pReplace = 0;
133101  int rc;                         /* Return code */
133102
133103  rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
133104  if( rc==SQLITE_OK ){
133105    sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
133106    sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
133107    sqlite3_step(pReplace);
133108    rc = sqlite3_reset(pReplace);
133109  }
133110
133111  return rc;
133112}
133113
133114/*
133115** Load an incr-merge hint from the database. The incr-merge hint, if one
133116** exists, is stored in the rowid==1 row of the %_stat table.
133117**
133118** If successful, populate blob *pHint with the value read from the %_stat
133119** table and return SQLITE_OK. Otherwise, if an error occurs, return an
133120** SQLite error code.
133121*/
133122static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
133123  sqlite3_stmt *pSelect = 0;
133124  int rc;
133125
133126  pHint->n = 0;
133127  rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
133128  if( rc==SQLITE_OK ){
133129    int rc2;
133130    sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
133131    if( SQLITE_ROW==sqlite3_step(pSelect) ){
133132      const char *aHint = sqlite3_column_blob(pSelect, 0);
133133      int nHint = sqlite3_column_bytes(pSelect, 0);
133134      if( aHint ){
133135        blobGrowBuffer(pHint, nHint, &rc);
133136        if( rc==SQLITE_OK ){
133137          memcpy(pHint->a, aHint, nHint);
133138          pHint->n = nHint;
133139        }
133140      }
133141    }
133142    rc2 = sqlite3_reset(pSelect);
133143    if( rc==SQLITE_OK ) rc = rc2;
133144  }
133145
133146  return rc;
133147}
133148
133149/*
133150** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
133151** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
133152** consists of two varints, the absolute level number of the input segments
133153** and the number of input segments.
133154**
133155** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
133156** set *pRc to an SQLite error code before returning.
133157*/
133158static void fts3IncrmergeHintPush(
133159  Blob *pHint,                    /* Hint blob to append to */
133160  i64 iAbsLevel,                  /* First varint to store in hint */
133161  int nInput,                     /* Second varint to store in hint */
133162  int *pRc                        /* IN/OUT: Error code */
133163){
133164  blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
133165  if( *pRc==SQLITE_OK ){
133166    pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
133167    pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
133168  }
133169}
133170
133171/*
133172** Read the last entry (most recently pushed) from the hint blob *pHint
133173** and then remove the entry. Write the two values read to *piAbsLevel and
133174** *pnInput before returning.
133175**
133176** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
133177** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
133178*/
133179static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
133180  const int nHint = pHint->n;
133181  int i;
133182
133183  i = pHint->n-2;
133184  while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
133185  while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
133186
133187  pHint->n = i;
133188  i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
133189  i += sqlite3Fts3GetVarint32(&pHint->a[i], pnInput);
133190  if( i!=nHint ) return SQLITE_CORRUPT_VTAB;
133191
133192  return SQLITE_OK;
133193}
133194
133195
133196/*
133197** Attempt an incremental merge that writes nMerge leaf blocks.
133198**
133199** Incremental merges happen nMin segments at a time. The two
133200** segments to be merged are the nMin oldest segments (the ones with
133201** the smallest indexes) in the highest level that contains at least
133202** nMin segments. Multiple merges might occur in an attempt to write the
133203** quota of nMerge leaf blocks.
133204*/
133205SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
133206  int rc;                         /* Return code */
133207  int nRem = nMerge;              /* Number of leaf pages yet to  be written */
133208  Fts3MultiSegReader *pCsr;       /* Cursor used to read input data */
133209  Fts3SegFilter *pFilter;         /* Filter used with cursor pCsr */
133210  IncrmergeWriter *pWriter;       /* Writer object */
133211  int nSeg = 0;                   /* Number of input segments */
133212  sqlite3_int64 iAbsLevel = 0;    /* Absolute level number to work on */
133213  Blob hint = {0, 0, 0};          /* Hint read from %_stat table */
133214  int bDirtyHint = 0;             /* True if blob 'hint' has been modified */
133215
133216  /* Allocate space for the cursor, filter and writer objects */
133217  const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
133218  pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
133219  if( !pWriter ) return SQLITE_NOMEM;
133220  pFilter = (Fts3SegFilter *)&pWriter[1];
133221  pCsr = (Fts3MultiSegReader *)&pFilter[1];
133222
133223  rc = fts3IncrmergeHintLoad(p, &hint);
133224  while( rc==SQLITE_OK && nRem>0 ){
133225    const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
133226    sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
133227    int bUseHint = 0;             /* True if attempting to append */
133228
133229    /* Search the %_segdir table for the absolute level with the smallest
133230    ** relative level number that contains at least nMin segments, if any.
133231    ** If one is found, set iAbsLevel to the absolute level number and
133232    ** nSeg to nMin. If no level with at least nMin segments can be found,
133233    ** set nSeg to -1.
133234    */
133235    rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
133236    sqlite3_bind_int(pFindLevel, 1, nMin);
133237    if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
133238      iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
133239      nSeg = nMin;
133240    }else{
133241      nSeg = -1;
133242    }
133243    rc = sqlite3_reset(pFindLevel);
133244
133245    /* If the hint read from the %_stat table is not empty, check if the
133246    ** last entry in it specifies a relative level smaller than or equal
133247    ** to the level identified by the block above (if any). If so, this
133248    ** iteration of the loop will work on merging at the hinted level.
133249    */
133250    if( rc==SQLITE_OK && hint.n ){
133251      int nHint = hint.n;
133252      sqlite3_int64 iHintAbsLevel = 0;      /* Hint level */
133253      int nHintSeg = 0;                     /* Hint number of segments */
133254
133255      rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
133256      if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
133257        iAbsLevel = iHintAbsLevel;
133258        nSeg = nHintSeg;
133259        bUseHint = 1;
133260        bDirtyHint = 1;
133261      }else{
133262        /* This undoes the effect of the HintPop() above - so that no entry
133263        ** is removed from the hint blob.  */
133264        hint.n = nHint;
133265      }
133266    }
133267
133268    /* If nSeg is less that zero, then there is no level with at least
133269    ** nMin segments and no hint in the %_stat table. No work to do.
133270    ** Exit early in this case.  */
133271    if( nSeg<0 ) break;
133272
133273    /* Open a cursor to iterate through the contents of the oldest nSeg
133274    ** indexes of absolute level iAbsLevel. If this cursor is opened using
133275    ** the 'hint' parameters, it is possible that there are less than nSeg
133276    ** segments available in level iAbsLevel. In this case, no work is
133277    ** done on iAbsLevel - fall through to the next iteration of the loop
133278    ** to start work on some other level.  */
133279    memset(pWriter, 0, nAlloc);
133280    pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
133281    if( rc==SQLITE_OK ){
133282      rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
133283    }
133284    if( SQLITE_OK==rc && pCsr->nSegment==nSeg
133285     && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
133286     && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
133287    ){
133288      int iIdx = 0;               /* Largest idx in level (iAbsLevel+1) */
133289      rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
133290      if( rc==SQLITE_OK ){
133291        if( bUseHint && iIdx>0 ){
133292          const char *zKey = pCsr->zTerm;
133293          int nKey = pCsr->nTerm;
133294          rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
133295        }else{
133296          rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
133297        }
133298      }
133299
133300      if( rc==SQLITE_OK && pWriter->nLeafEst ){
133301        fts3LogMerge(nSeg, iAbsLevel);
133302        do {
133303          rc = fts3IncrmergeAppend(p, pWriter, pCsr);
133304          if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
133305          if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
133306        }while( rc==SQLITE_ROW );
133307
133308        /* Update or delete the input segments */
133309        if( rc==SQLITE_OK ){
133310          nRem -= (1 + pWriter->nWork);
133311          rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
133312          if( nSeg!=0 ){
133313            bDirtyHint = 1;
133314            fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
133315          }
133316        }
133317      }
133318
133319      fts3IncrmergeRelease(p, pWriter, &rc);
133320    }
133321
133322    sqlite3Fts3SegReaderFinish(pCsr);
133323  }
133324
133325  /* Write the hint values into the %_stat table for the next incr-merger */
133326  if( bDirtyHint && rc==SQLITE_OK ){
133327    rc = fts3IncrmergeHintStore(p, &hint);
133328  }
133329
133330  sqlite3_free(pWriter);
133331  sqlite3_free(hint.a);
133332  return rc;
133333}
133334
133335/*
133336** Convert the text beginning at *pz into an integer and return
133337** its value.  Advance *pz to point to the first character past
133338** the integer.
133339*/
133340static int fts3Getint(const char **pz){
133341  const char *z = *pz;
133342  int i = 0;
133343  while( (*z)>='0' && (*z)<='9' ) i = 10*i + *(z++) - '0';
133344  *pz = z;
133345  return i;
133346}
133347
133348/*
133349** Process statements of the form:
133350**
133351**    INSERT INTO table(table) VALUES('merge=A,B');
133352**
133353** A and B are integers that decode to be the number of leaf pages
133354** written for the merge, and the minimum number of segments on a level
133355** before it will be selected for a merge, respectively.
133356*/
133357static int fts3DoIncrmerge(
133358  Fts3Table *p,                   /* FTS3 table handle */
133359  const char *zParam              /* Nul-terminated string containing "A,B" */
133360){
133361  int rc;
133362  int nMin = (FTS3_MERGE_COUNT / 2);
133363  int nMerge = 0;
133364  const char *z = zParam;
133365
133366  /* Read the first integer value */
133367  nMerge = fts3Getint(&z);
133368
133369  /* If the first integer value is followed by a ',',  read the second
133370  ** integer value. */
133371  if( z[0]==',' && z[1]!='\0' ){
133372    z++;
133373    nMin = fts3Getint(&z);
133374  }
133375
133376  if( z[0]!='\0' || nMin<2 ){
133377    rc = SQLITE_ERROR;
133378  }else{
133379    rc = SQLITE_OK;
133380    if( !p->bHasStat ){
133381      assert( p->bFts4==0 );
133382      sqlite3Fts3CreateStatTable(&rc, p);
133383    }
133384    if( rc==SQLITE_OK ){
133385      rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
133386    }
133387    sqlite3Fts3SegmentsClose(p);
133388  }
133389  return rc;
133390}
133391
133392/*
133393** Process statements of the form:
133394**
133395**    INSERT INTO table(table) VALUES('automerge=X');
133396**
133397** where X is an integer.  X==0 means to turn automerge off.  X!=0 means
133398** turn it on.  The setting is persistent.
133399*/
133400static int fts3DoAutoincrmerge(
133401  Fts3Table *p,                   /* FTS3 table handle */
133402  const char *zParam              /* Nul-terminated string containing boolean */
133403){
133404  int rc = SQLITE_OK;
133405  sqlite3_stmt *pStmt = 0;
133406  p->bAutoincrmerge = fts3Getint(&zParam)!=0;
133407  if( !p->bHasStat ){
133408    assert( p->bFts4==0 );
133409    sqlite3Fts3CreateStatTable(&rc, p);
133410    if( rc ) return rc;
133411  }
133412  rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
133413  if( rc ) return rc;;
133414  sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
133415  sqlite3_bind_int(pStmt, 2, p->bAutoincrmerge);
133416  sqlite3_step(pStmt);
133417  rc = sqlite3_reset(pStmt);
133418  return rc;
133419}
133420
133421/*
133422** Return a 64-bit checksum for the FTS index entry specified by the
133423** arguments to this function.
133424*/
133425static u64 fts3ChecksumEntry(
133426  const char *zTerm,              /* Pointer to buffer containing term */
133427  int nTerm,                      /* Size of zTerm in bytes */
133428  int iLangid,                    /* Language id for current row */
133429  int iIndex,                     /* Index (0..Fts3Table.nIndex-1) */
133430  i64 iDocid,                     /* Docid for current row. */
133431  int iCol,                       /* Column number */
133432  int iPos                        /* Position */
133433){
133434  int i;
133435  u64 ret = (u64)iDocid;
133436
133437  ret += (ret<<3) + iLangid;
133438  ret += (ret<<3) + iIndex;
133439  ret += (ret<<3) + iCol;
133440  ret += (ret<<3) + iPos;
133441  for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
133442
133443  return ret;
133444}
133445
133446/*
133447** Return a checksum of all entries in the FTS index that correspond to
133448** language id iLangid. The checksum is calculated by XORing the checksums
133449** of each individual entry (see fts3ChecksumEntry()) together.
133450**
133451** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
133452** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
133453** return value is undefined in this case.
133454*/
133455static u64 fts3ChecksumIndex(
133456  Fts3Table *p,                   /* FTS3 table handle */
133457  int iLangid,                    /* Language id to return cksum for */
133458  int iIndex,                     /* Index to cksum (0..p->nIndex-1) */
133459  int *pRc                        /* OUT: Return code */
133460){
133461  Fts3SegFilter filter;
133462  Fts3MultiSegReader csr;
133463  int rc;
133464  u64 cksum = 0;
133465
133466  assert( *pRc==SQLITE_OK );
133467
133468  memset(&filter, 0, sizeof(filter));
133469  memset(&csr, 0, sizeof(csr));
133470  filter.flags =  FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
133471  filter.flags |= FTS3_SEGMENT_SCAN;
133472
133473  rc = sqlite3Fts3SegReaderCursor(
133474      p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
133475  );
133476  if( rc==SQLITE_OK ){
133477    rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
133478  }
133479
133480  if( rc==SQLITE_OK ){
133481    while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
133482      char *pCsr = csr.aDoclist;
133483      char *pEnd = &pCsr[csr.nDoclist];
133484
133485      i64 iDocid = 0;
133486      i64 iCol = 0;
133487      i64 iPos = 0;
133488
133489      pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
133490      while( pCsr<pEnd ){
133491        i64 iVal = 0;
133492        pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
133493        if( pCsr<pEnd ){
133494          if( iVal==0 || iVal==1 ){
133495            iCol = 0;
133496            iPos = 0;
133497            if( iVal ){
133498              pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
133499            }else{
133500              pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
133501              iDocid += iVal;
133502            }
133503          }else{
133504            iPos += (iVal - 2);
133505            cksum = cksum ^ fts3ChecksumEntry(
133506                csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
133507                (int)iCol, (int)iPos
133508            );
133509          }
133510        }
133511      }
133512    }
133513  }
133514  sqlite3Fts3SegReaderFinish(&csr);
133515
133516  *pRc = rc;
133517  return cksum;
133518}
133519
133520/*
133521** Check if the contents of the FTS index match the current contents of the
133522** content table. If no error occurs and the contents do match, set *pbOk
133523** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
133524** to false before returning.
133525**
133526** If an error occurs (e.g. an OOM or IO error), return an SQLite error
133527** code. The final value of *pbOk is undefined in this case.
133528*/
133529static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
133530  int rc = SQLITE_OK;             /* Return code */
133531  u64 cksum1 = 0;                 /* Checksum based on FTS index contents */
133532  u64 cksum2 = 0;                 /* Checksum based on %_content contents */
133533  sqlite3_stmt *pAllLangid = 0;   /* Statement to return all language-ids */
133534
133535  /* This block calculates the checksum according to the FTS index. */
133536  rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
133537  if( rc==SQLITE_OK ){
133538    int rc2;
133539    sqlite3_bind_int(pAllLangid, 1, p->nIndex);
133540    while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
133541      int iLangid = sqlite3_column_int(pAllLangid, 0);
133542      int i;
133543      for(i=0; i<p->nIndex; i++){
133544        cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
133545      }
133546    }
133547    rc2 = sqlite3_reset(pAllLangid);
133548    if( rc==SQLITE_OK ) rc = rc2;
133549  }
133550
133551  /* This block calculates the checksum according to the %_content table */
133552  rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
133553  if( rc==SQLITE_OK ){
133554    sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
133555    sqlite3_stmt *pStmt = 0;
133556    char *zSql;
133557
133558    zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
133559    if( !zSql ){
133560      rc = SQLITE_NOMEM;
133561    }else{
133562      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
133563      sqlite3_free(zSql);
133564    }
133565
133566    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
133567      i64 iDocid = sqlite3_column_int64(pStmt, 0);
133568      int iLang = langidFromSelect(p, pStmt);
133569      int iCol;
133570
133571      for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
133572        const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
133573        int nText = sqlite3_column_bytes(pStmt, iCol+1);
133574        sqlite3_tokenizer_cursor *pT = 0;
133575
133576        rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText, &pT);
133577        while( rc==SQLITE_OK ){
133578          char const *zToken;       /* Buffer containing token */
133579          int nToken = 0;           /* Number of bytes in token */
133580          int iDum1 = 0, iDum2 = 0; /* Dummy variables */
133581          int iPos = 0;             /* Position of token in zText */
133582
133583          rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
133584          if( rc==SQLITE_OK ){
133585            int i;
133586            cksum2 = cksum2 ^ fts3ChecksumEntry(
133587                zToken, nToken, iLang, 0, iDocid, iCol, iPos
133588            );
133589            for(i=1; i<p->nIndex; i++){
133590              if( p->aIndex[i].nPrefix<=nToken ){
133591                cksum2 = cksum2 ^ fts3ChecksumEntry(
133592                  zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
133593                );
133594              }
133595            }
133596          }
133597        }
133598        if( pT ) pModule->xClose(pT);
133599        if( rc==SQLITE_DONE ) rc = SQLITE_OK;
133600      }
133601    }
133602
133603    sqlite3_finalize(pStmt);
133604  }
133605
133606  *pbOk = (cksum1==cksum2);
133607  return rc;
133608}
133609
133610/*
133611** Run the integrity-check. If no error occurs and the current contents of
133612** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
133613** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
133614**
133615** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite
133616** error code.
133617**
133618** The integrity-check works as follows. For each token and indexed token
133619** prefix in the document set, a 64-bit checksum is calculated (by code
133620** in fts3ChecksumEntry()) based on the following:
133621**
133622**     + The index number (0 for the main index, 1 for the first prefix
133623**       index etc.),
133624**     + The token (or token prefix) text itself,
133625**     + The language-id of the row it appears in,
133626**     + The docid of the row it appears in,
133627**     + The column it appears in, and
133628**     + The tokens position within that column.
133629**
133630** The checksums for all entries in the index are XORed together to create
133631** a single checksum for the entire index.
133632**
133633** The integrity-check code calculates the same checksum in two ways:
133634**
133635**     1. By scanning the contents of the FTS index, and
133636**     2. By scanning and tokenizing the content table.
133637**
133638** If the two checksums are identical, the integrity-check is deemed to have
133639** passed.
133640*/
133641static int fts3DoIntegrityCheck(
133642  Fts3Table *p                    /* FTS3 table handle */
133643){
133644  int rc;
133645  int bOk = 0;
133646  rc = fts3IntegrityCheck(p, &bOk);
133647  if( rc==SQLITE_OK && bOk==0 ) rc = SQLITE_CORRUPT_VTAB;
133648  return rc;
133649}
133650
133651/*
133652** Handle a 'special' INSERT of the form:
133653**
133654**   "INSERT INTO tbl(tbl) VALUES(<expr>)"
133655**
133656** Argument pVal contains the result of <expr>. Currently the only
133657** meaningful value to insert is the text 'optimize'.
133658*/
133659static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
133660  int rc;                         /* Return Code */
133661  const char *zVal = (const char *)sqlite3_value_text(pVal);
133662  int nVal = sqlite3_value_bytes(pVal);
133663
133664  if( !zVal ){
133665    return SQLITE_NOMEM;
133666  }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
133667    rc = fts3DoOptimize(p, 0);
133668  }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
133669    rc = fts3DoRebuild(p);
133670  }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
133671    rc = fts3DoIntegrityCheck(p);
133672  }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
133673    rc = fts3DoIncrmerge(p, &zVal[6]);
133674  }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
133675    rc = fts3DoAutoincrmerge(p, &zVal[10]);
133676#ifdef SQLITE_TEST
133677  }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
133678    p->nNodeSize = atoi(&zVal[9]);
133679    rc = SQLITE_OK;
133680  }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
133681    p->nMaxPendingData = atoi(&zVal[11]);
133682    rc = SQLITE_OK;
133683#endif
133684  }else{
133685    rc = SQLITE_ERROR;
133686  }
133687
133688  return rc;
133689}
133690
133691#ifndef SQLITE_DISABLE_FTS4_DEFERRED
133692/*
133693** Delete all cached deferred doclists. Deferred doclists are cached
133694** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
133695*/
133696SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
133697  Fts3DeferredToken *pDef;
133698  for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
133699    fts3PendingListDelete(pDef->pList);
133700    pDef->pList = 0;
133701  }
133702}
133703
133704/*
133705** Free all entries in the pCsr->pDeffered list. Entries are added to
133706** this list using sqlite3Fts3DeferToken().
133707*/
133708SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
133709  Fts3DeferredToken *pDef;
133710  Fts3DeferredToken *pNext;
133711  for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
133712    pNext = pDef->pNext;
133713    fts3PendingListDelete(pDef->pList);
133714    sqlite3_free(pDef);
133715  }
133716  pCsr->pDeferred = 0;
133717}
133718
133719/*
133720** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
133721** based on the row that pCsr currently points to.
133722**
133723** A deferred-doclist is like any other doclist with position information
133724** included, except that it only contains entries for a single row of the
133725** table, not for all rows.
133726*/
133727SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
133728  int rc = SQLITE_OK;             /* Return code */
133729  if( pCsr->pDeferred ){
133730    int i;                        /* Used to iterate through table columns */
133731    sqlite3_int64 iDocid;         /* Docid of the row pCsr points to */
133732    Fts3DeferredToken *pDef;      /* Used to iterate through deferred tokens */
133733
133734    Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
133735    sqlite3_tokenizer *pT = p->pTokenizer;
133736    sqlite3_tokenizer_module const *pModule = pT->pModule;
133737
133738    assert( pCsr->isRequireSeek==0 );
133739    iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
133740
133741    for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
133742      const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
133743      sqlite3_tokenizer_cursor *pTC = 0;
133744
133745      rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
133746      while( rc==SQLITE_OK ){
133747        char const *zToken;       /* Buffer containing token */
133748        int nToken = 0;           /* Number of bytes in token */
133749        int iDum1 = 0, iDum2 = 0; /* Dummy variables */
133750        int iPos = 0;             /* Position of token in zText */
133751
133752        rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
133753        for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
133754          Fts3PhraseToken *pPT = pDef->pToken;
133755          if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
133756           && (pPT->bFirst==0 || iPos==0)
133757           && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
133758           && (0==memcmp(zToken, pPT->z, pPT->n))
133759          ){
133760            fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
133761          }
133762        }
133763      }
133764      if( pTC ) pModule->xClose(pTC);
133765      if( rc==SQLITE_DONE ) rc = SQLITE_OK;
133766    }
133767
133768    for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
133769      if( pDef->pList ){
133770        rc = fts3PendingListAppendVarint(&pDef->pList, 0);
133771      }
133772    }
133773  }
133774
133775  return rc;
133776}
133777
133778SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
133779  Fts3DeferredToken *p,
133780  char **ppData,
133781  int *pnData
133782){
133783  char *pRet;
133784  int nSkip;
133785  sqlite3_int64 dummy;
133786
133787  *ppData = 0;
133788  *pnData = 0;
133789
133790  if( p->pList==0 ){
133791    return SQLITE_OK;
133792  }
133793
133794  pRet = (char *)sqlite3_malloc(p->pList->nData);
133795  if( !pRet ) return SQLITE_NOMEM;
133796
133797  nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
133798  *pnData = p->pList->nData - nSkip;
133799  *ppData = pRet;
133800
133801  memcpy(pRet, &p->pList->aData[nSkip], *pnData);
133802  return SQLITE_OK;
133803}
133804
133805/*
133806** Add an entry for token pToken to the pCsr->pDeferred list.
133807*/
133808SQLITE_PRIVATE int sqlite3Fts3DeferToken(
133809  Fts3Cursor *pCsr,               /* Fts3 table cursor */
133810  Fts3PhraseToken *pToken,        /* Token to defer */
133811  int iCol                        /* Column that token must appear in (or -1) */
133812){
133813  Fts3DeferredToken *pDeferred;
133814  pDeferred = sqlite3_malloc(sizeof(*pDeferred));
133815  if( !pDeferred ){
133816    return SQLITE_NOMEM;
133817  }
133818  memset(pDeferred, 0, sizeof(*pDeferred));
133819  pDeferred->pToken = pToken;
133820  pDeferred->pNext = pCsr->pDeferred;
133821  pDeferred->iCol = iCol;
133822  pCsr->pDeferred = pDeferred;
133823
133824  assert( pToken->pDeferred==0 );
133825  pToken->pDeferred = pDeferred;
133826
133827  return SQLITE_OK;
133828}
133829#endif
133830
133831/*
133832** SQLite value pRowid contains the rowid of a row that may or may not be
133833** present in the FTS3 table. If it is, delete it and adjust the contents
133834** of subsiduary data structures accordingly.
133835*/
133836static int fts3DeleteByRowid(
133837  Fts3Table *p,
133838  sqlite3_value *pRowid,
133839  int *pnChng,                    /* IN/OUT: Decrement if row is deleted */
133840  u32 *aSzDel
133841){
133842  int rc = SQLITE_OK;             /* Return code */
133843  int bFound = 0;                 /* True if *pRowid really is in the table */
133844
133845  fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
133846  if( bFound && rc==SQLITE_OK ){
133847    int isEmpty = 0;              /* Deleting *pRowid leaves the table empty */
133848    rc = fts3IsEmpty(p, pRowid, &isEmpty);
133849    if( rc==SQLITE_OK ){
133850      if( isEmpty ){
133851        /* Deleting this row means the whole table is empty. In this case
133852        ** delete the contents of all three tables and throw away any
133853        ** data in the pendingTerms hash table.  */
133854        rc = fts3DeleteAll(p, 1);
133855        *pnChng = 0;
133856        memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
133857      }else{
133858        *pnChng = *pnChng - 1;
133859        if( p->zContentTbl==0 ){
133860          fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
133861        }
133862        if( p->bHasDocsize ){
133863          fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
133864        }
133865      }
133866    }
133867  }
133868
133869  return rc;
133870}
133871
133872/*
133873** This function does the work for the xUpdate method of FTS3 virtual
133874** tables. The schema of the virtual table being:
133875**
133876**     CREATE TABLE <table name>(
133877**       <user columns>,
133878**       <table name> HIDDEN,
133879**       docid HIDDEN,
133880**       <langid> HIDDEN
133881**     );
133882**
133883**
133884*/
133885SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
133886  sqlite3_vtab *pVtab,            /* FTS3 vtab object */
133887  int nArg,                       /* Size of argument array */
133888  sqlite3_value **apVal,          /* Array of arguments */
133889  sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
133890){
133891  Fts3Table *p = (Fts3Table *)pVtab;
133892  int rc = SQLITE_OK;             /* Return Code */
133893  int isRemove = 0;               /* True for an UPDATE or DELETE */
133894  u32 *aSzIns = 0;                /* Sizes of inserted documents */
133895  u32 *aSzDel = 0;                /* Sizes of deleted documents */
133896  int nChng = 0;                  /* Net change in number of documents */
133897  int bInsertDone = 0;
133898
133899  assert( p->pSegments==0 );
133900  assert(
133901      nArg==1                     /* DELETE operations */
133902   || nArg==(2 + p->nColumn + 3)  /* INSERT or UPDATE operations */
133903  );
133904
133905  /* Check for a "special" INSERT operation. One of the form:
133906  **
133907  **   INSERT INTO xyz(xyz) VALUES('command');
133908  */
133909  if( nArg>1
133910   && sqlite3_value_type(apVal[0])==SQLITE_NULL
133911   && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
133912  ){
133913    rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
133914    goto update_out;
133915  }
133916
133917  if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
133918    rc = SQLITE_CONSTRAINT;
133919    goto update_out;
133920  }
133921
133922  /* Allocate space to hold the change in document sizes */
133923  aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 );
133924  if( aSzDel==0 ){
133925    rc = SQLITE_NOMEM;
133926    goto update_out;
133927  }
133928  aSzIns = &aSzDel[p->nColumn+1];
133929  memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
133930
133931  /* If this is an INSERT operation, or an UPDATE that modifies the rowid
133932  ** value, then this operation requires constraint handling.
133933  **
133934  ** If the on-conflict mode is REPLACE, this means that the existing row
133935  ** should be deleted from the database before inserting the new row. Or,
133936  ** if the on-conflict mode is other than REPLACE, then this method must
133937  ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
133938  ** modify the database file.
133939  */
133940  if( nArg>1 && p->zContentTbl==0 ){
133941    /* Find the value object that holds the new rowid value. */
133942    sqlite3_value *pNewRowid = apVal[3+p->nColumn];
133943    if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
133944      pNewRowid = apVal[1];
133945    }
133946
133947    if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
133948        sqlite3_value_type(apVal[0])==SQLITE_NULL
133949     || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
133950    )){
133951      /* The new rowid is not NULL (in this case the rowid will be
133952      ** automatically assigned and there is no chance of a conflict), and
133953      ** the statement is either an INSERT or an UPDATE that modifies the
133954      ** rowid column. So if the conflict mode is REPLACE, then delete any
133955      ** existing row with rowid=pNewRowid.
133956      **
133957      ** Or, if the conflict mode is not REPLACE, insert the new record into
133958      ** the %_content table. If we hit the duplicate rowid constraint (or any
133959      ** other error) while doing so, return immediately.
133960      **
133961      ** This branch may also run if pNewRowid contains a value that cannot
133962      ** be losslessly converted to an integer. In this case, the eventual
133963      ** call to fts3InsertData() (either just below or further on in this
133964      ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
133965      ** invoked, it will delete zero rows (since no row will have
133966      ** docid=$pNewRowid if $pNewRowid is not an integer value).
133967      */
133968      if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
133969        rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
133970      }else{
133971        rc = fts3InsertData(p, apVal, pRowid);
133972        bInsertDone = 1;
133973      }
133974    }
133975  }
133976  if( rc!=SQLITE_OK ){
133977    goto update_out;
133978  }
133979
133980  /* If this is a DELETE or UPDATE operation, remove the old record. */
133981  if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
133982    assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
133983    rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
133984    isRemove = 1;
133985  }
133986
133987  /* If this is an INSERT or UPDATE operation, insert the new record. */
133988  if( nArg>1 && rc==SQLITE_OK ){
133989    int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
133990    if( bInsertDone==0 ){
133991      rc = fts3InsertData(p, apVal, pRowid);
133992      if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
133993        rc = FTS_CORRUPT_VTAB;
133994      }
133995    }
133996    if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
133997      rc = fts3PendingTermsDocid(p, iLangid, *pRowid);
133998    }
133999    if( rc==SQLITE_OK ){
134000      assert( p->iPrevDocid==*pRowid );
134001      rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
134002    }
134003    if( p->bHasDocsize ){
134004      fts3InsertDocsize(&rc, p, aSzIns);
134005    }
134006    nChng++;
134007  }
134008
134009  if( p->bFts4 ){
134010    fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
134011  }
134012
134013 update_out:
134014  sqlite3_free(aSzDel);
134015  sqlite3Fts3SegmentsClose(p);
134016  return rc;
134017}
134018
134019/*
134020** Flush any data in the pending-terms hash table to disk. If successful,
134021** merge all segments in the database (including the new segment, if
134022** there was any data to flush) into a single segment.
134023*/
134024SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
134025  int rc;
134026  rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
134027  if( rc==SQLITE_OK ){
134028    rc = fts3DoOptimize(p, 1);
134029    if( rc==SQLITE_OK || rc==SQLITE_DONE ){
134030      int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
134031      if( rc2!=SQLITE_OK ) rc = rc2;
134032    }else{
134033      sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
134034      sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
134035    }
134036  }
134037  sqlite3Fts3SegmentsClose(p);
134038  return rc;
134039}
134040
134041#endif
134042
134043/************** End of fts3_write.c ******************************************/
134044/************** Begin file fts3_snippet.c ************************************/
134045/*
134046** 2009 Oct 23
134047**
134048** The author disclaims copyright to this source code.  In place of
134049** a legal notice, here is a blessing:
134050**
134051**    May you do good and not evil.
134052**    May you find forgiveness for yourself and forgive others.
134053**    May you share freely, never taking more than you give.
134054**
134055******************************************************************************
134056*/
134057
134058#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
134059
134060/* #include <string.h> */
134061/* #include <assert.h> */
134062
134063/*
134064** Characters that may appear in the second argument to matchinfo().
134065*/
134066#define FTS3_MATCHINFO_NPHRASE   'p'        /* 1 value */
134067#define FTS3_MATCHINFO_NCOL      'c'        /* 1 value */
134068#define FTS3_MATCHINFO_NDOC      'n'        /* 1 value */
134069#define FTS3_MATCHINFO_AVGLENGTH 'a'        /* nCol values */
134070#define FTS3_MATCHINFO_LENGTH    'l'        /* nCol values */
134071#define FTS3_MATCHINFO_LCS       's'        /* nCol values */
134072#define FTS3_MATCHINFO_HITS      'x'        /* 3*nCol*nPhrase values */
134073
134074/*
134075** The default value for the second argument to matchinfo().
134076*/
134077#define FTS3_MATCHINFO_DEFAULT   "pcx"
134078
134079
134080/*
134081** Used as an fts3ExprIterate() context when loading phrase doclists to
134082** Fts3Expr.aDoclist[]/nDoclist.
134083*/
134084typedef struct LoadDoclistCtx LoadDoclistCtx;
134085struct LoadDoclistCtx {
134086  Fts3Cursor *pCsr;               /* FTS3 Cursor */
134087  int nPhrase;                    /* Number of phrases seen so far */
134088  int nToken;                     /* Number of tokens seen so far */
134089};
134090
134091/*
134092** The following types are used as part of the implementation of the
134093** fts3BestSnippet() routine.
134094*/
134095typedef struct SnippetIter SnippetIter;
134096typedef struct SnippetPhrase SnippetPhrase;
134097typedef struct SnippetFragment SnippetFragment;
134098
134099struct SnippetIter {
134100  Fts3Cursor *pCsr;               /* Cursor snippet is being generated from */
134101  int iCol;                       /* Extract snippet from this column */
134102  int nSnippet;                   /* Requested snippet length (in tokens) */
134103  int nPhrase;                    /* Number of phrases in query */
134104  SnippetPhrase *aPhrase;         /* Array of size nPhrase */
134105  int iCurrent;                   /* First token of current snippet */
134106};
134107
134108struct SnippetPhrase {
134109  int nToken;                     /* Number of tokens in phrase */
134110  char *pList;                    /* Pointer to start of phrase position list */
134111  int iHead;                      /* Next value in position list */
134112  char *pHead;                    /* Position list data following iHead */
134113  int iTail;                      /* Next value in trailing position list */
134114  char *pTail;                    /* Position list data following iTail */
134115};
134116
134117struct SnippetFragment {
134118  int iCol;                       /* Column snippet is extracted from */
134119  int iPos;                       /* Index of first token in snippet */
134120  u64 covered;                    /* Mask of query phrases covered */
134121  u64 hlmask;                     /* Mask of snippet terms to highlight */
134122};
134123
134124/*
134125** This type is used as an fts3ExprIterate() context object while
134126** accumulating the data returned by the matchinfo() function.
134127*/
134128typedef struct MatchInfo MatchInfo;
134129struct MatchInfo {
134130  Fts3Cursor *pCursor;            /* FTS3 Cursor */
134131  int nCol;                       /* Number of columns in table */
134132  int nPhrase;                    /* Number of matchable phrases in query */
134133  sqlite3_int64 nDoc;             /* Number of docs in database */
134134  u32 *aMatchinfo;                /* Pre-allocated buffer */
134135};
134136
134137
134138
134139/*
134140** The snippet() and offsets() functions both return text values. An instance
134141** of the following structure is used to accumulate those values while the
134142** functions are running. See fts3StringAppend() for details.
134143*/
134144typedef struct StrBuffer StrBuffer;
134145struct StrBuffer {
134146  char *z;                        /* Pointer to buffer containing string */
134147  int n;                          /* Length of z in bytes (excl. nul-term) */
134148  int nAlloc;                     /* Allocated size of buffer z in bytes */
134149};
134150
134151
134152/*
134153** This function is used to help iterate through a position-list. A position
134154** list is a list of unique integers, sorted from smallest to largest. Each
134155** element of the list is represented by an FTS3 varint that takes the value
134156** of the difference between the current element and the previous one plus
134157** two. For example, to store the position-list:
134158**
134159**     4 9 113
134160**
134161** the three varints:
134162**
134163**     6 7 106
134164**
134165** are encoded.
134166**
134167** When this function is called, *pp points to the start of an element of
134168** the list. *piPos contains the value of the previous entry in the list.
134169** After it returns, *piPos contains the value of the next element of the
134170** list and *pp is advanced to the following varint.
134171*/
134172static void fts3GetDeltaPosition(char **pp, int *piPos){
134173  int iVal;
134174  *pp += sqlite3Fts3GetVarint32(*pp, &iVal);
134175  *piPos += (iVal-2);
134176}
134177
134178/*
134179** Helper function for fts3ExprIterate() (see below).
134180*/
134181static int fts3ExprIterate2(
134182  Fts3Expr *pExpr,                /* Expression to iterate phrases of */
134183  int *piPhrase,                  /* Pointer to phrase counter */
134184  int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
134185  void *pCtx                      /* Second argument to pass to callback */
134186){
134187  int rc;                         /* Return code */
134188  int eType = pExpr->eType;       /* Type of expression node pExpr */
134189
134190  if( eType!=FTSQUERY_PHRASE ){
134191    assert( pExpr->pLeft && pExpr->pRight );
134192    rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
134193    if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
134194      rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
134195    }
134196  }else{
134197    rc = x(pExpr, *piPhrase, pCtx);
134198    (*piPhrase)++;
134199  }
134200  return rc;
134201}
134202
134203/*
134204** Iterate through all phrase nodes in an FTS3 query, except those that
134205** are part of a sub-tree that is the right-hand-side of a NOT operator.
134206** For each phrase node found, the supplied callback function is invoked.
134207**
134208** If the callback function returns anything other than SQLITE_OK,
134209** the iteration is abandoned and the error code returned immediately.
134210** Otherwise, SQLITE_OK is returned after a callback has been made for
134211** all eligible phrase nodes.
134212*/
134213static int fts3ExprIterate(
134214  Fts3Expr *pExpr,                /* Expression to iterate phrases of */
134215  int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
134216  void *pCtx                      /* Second argument to pass to callback */
134217){
134218  int iPhrase = 0;                /* Variable used as the phrase counter */
134219  return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
134220}
134221
134222/*
134223** This is an fts3ExprIterate() callback used while loading the doclists
134224** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
134225** fts3ExprLoadDoclists().
134226*/
134227static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
134228  int rc = SQLITE_OK;
134229  Fts3Phrase *pPhrase = pExpr->pPhrase;
134230  LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
134231
134232  UNUSED_PARAMETER(iPhrase);
134233
134234  p->nPhrase++;
134235  p->nToken += pPhrase->nToken;
134236
134237  return rc;
134238}
134239
134240/*
134241** Load the doclists for each phrase in the query associated with FTS3 cursor
134242** pCsr.
134243**
134244** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
134245** phrases in the expression (all phrases except those directly or
134246** indirectly descended from the right-hand-side of a NOT operator). If
134247** pnToken is not NULL, then it is set to the number of tokens in all
134248** matchable phrases of the expression.
134249*/
134250static int fts3ExprLoadDoclists(
134251  Fts3Cursor *pCsr,               /* Fts3 cursor for current query */
134252  int *pnPhrase,                  /* OUT: Number of phrases in query */
134253  int *pnToken                    /* OUT: Number of tokens in query */
134254){
134255  int rc;                         /* Return Code */
134256  LoadDoclistCtx sCtx = {0,0,0};  /* Context for fts3ExprIterate() */
134257  sCtx.pCsr = pCsr;
134258  rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
134259  if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
134260  if( pnToken ) *pnToken = sCtx.nToken;
134261  return rc;
134262}
134263
134264static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
134265  (*(int *)ctx)++;
134266  UNUSED_PARAMETER(pExpr);
134267  UNUSED_PARAMETER(iPhrase);
134268  return SQLITE_OK;
134269}
134270static int fts3ExprPhraseCount(Fts3Expr *pExpr){
134271  int nPhrase = 0;
134272  (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
134273  return nPhrase;
134274}
134275
134276/*
134277** Advance the position list iterator specified by the first two
134278** arguments so that it points to the first element with a value greater
134279** than or equal to parameter iNext.
134280*/
134281static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
134282  char *pIter = *ppIter;
134283  if( pIter ){
134284    int iIter = *piIter;
134285
134286    while( iIter<iNext ){
134287      if( 0==(*pIter & 0xFE) ){
134288        iIter = -1;
134289        pIter = 0;
134290        break;
134291      }
134292      fts3GetDeltaPosition(&pIter, &iIter);
134293    }
134294
134295    *piIter = iIter;
134296    *ppIter = pIter;
134297  }
134298}
134299
134300/*
134301** Advance the snippet iterator to the next candidate snippet.
134302*/
134303static int fts3SnippetNextCandidate(SnippetIter *pIter){
134304  int i;                          /* Loop counter */
134305
134306  if( pIter->iCurrent<0 ){
134307    /* The SnippetIter object has just been initialized. The first snippet
134308    ** candidate always starts at offset 0 (even if this candidate has a
134309    ** score of 0.0).
134310    */
134311    pIter->iCurrent = 0;
134312
134313    /* Advance the 'head' iterator of each phrase to the first offset that
134314    ** is greater than or equal to (iNext+nSnippet).
134315    */
134316    for(i=0; i<pIter->nPhrase; i++){
134317      SnippetPhrase *pPhrase = &pIter->aPhrase[i];
134318      fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
134319    }
134320  }else{
134321    int iStart;
134322    int iEnd = 0x7FFFFFFF;
134323
134324    for(i=0; i<pIter->nPhrase; i++){
134325      SnippetPhrase *pPhrase = &pIter->aPhrase[i];
134326      if( pPhrase->pHead && pPhrase->iHead<iEnd ){
134327        iEnd = pPhrase->iHead;
134328      }
134329    }
134330    if( iEnd==0x7FFFFFFF ){
134331      return 1;
134332    }
134333
134334    pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
134335    for(i=0; i<pIter->nPhrase; i++){
134336      SnippetPhrase *pPhrase = &pIter->aPhrase[i];
134337      fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
134338      fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
134339    }
134340  }
134341
134342  return 0;
134343}
134344
134345/*
134346** Retrieve information about the current candidate snippet of snippet
134347** iterator pIter.
134348*/
134349static void fts3SnippetDetails(
134350  SnippetIter *pIter,             /* Snippet iterator */
134351  u64 mCovered,                   /* Bitmask of phrases already covered */
134352  int *piToken,                   /* OUT: First token of proposed snippet */
134353  int *piScore,                   /* OUT: "Score" for this snippet */
134354  u64 *pmCover,                   /* OUT: Bitmask of phrases covered */
134355  u64 *pmHighlight                /* OUT: Bitmask of terms to highlight */
134356){
134357  int iStart = pIter->iCurrent;   /* First token of snippet */
134358  int iScore = 0;                 /* Score of this snippet */
134359  int i;                          /* Loop counter */
134360  u64 mCover = 0;                 /* Mask of phrases covered by this snippet */
134361  u64 mHighlight = 0;             /* Mask of tokens to highlight in snippet */
134362
134363  for(i=0; i<pIter->nPhrase; i++){
134364    SnippetPhrase *pPhrase = &pIter->aPhrase[i];
134365    if( pPhrase->pTail ){
134366      char *pCsr = pPhrase->pTail;
134367      int iCsr = pPhrase->iTail;
134368
134369      while( iCsr<(iStart+pIter->nSnippet) ){
134370        int j;
134371        u64 mPhrase = (u64)1 << i;
134372        u64 mPos = (u64)1 << (iCsr - iStart);
134373        assert( iCsr>=iStart );
134374        if( (mCover|mCovered)&mPhrase ){
134375          iScore++;
134376        }else{
134377          iScore += 1000;
134378        }
134379        mCover |= mPhrase;
134380
134381        for(j=0; j<pPhrase->nToken; j++){
134382          mHighlight |= (mPos>>j);
134383        }
134384
134385        if( 0==(*pCsr & 0x0FE) ) break;
134386        fts3GetDeltaPosition(&pCsr, &iCsr);
134387      }
134388    }
134389  }
134390
134391  /* Set the output variables before returning. */
134392  *piToken = iStart;
134393  *piScore = iScore;
134394  *pmCover = mCover;
134395  *pmHighlight = mHighlight;
134396}
134397
134398/*
134399** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
134400** Each invocation populates an element of the SnippetIter.aPhrase[] array.
134401*/
134402static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
134403  SnippetIter *p = (SnippetIter *)ctx;
134404  SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
134405  char *pCsr;
134406  int rc;
134407
134408  pPhrase->nToken = pExpr->pPhrase->nToken;
134409  rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
134410  assert( rc==SQLITE_OK || pCsr==0 );
134411  if( pCsr ){
134412    int iFirst = 0;
134413    pPhrase->pList = pCsr;
134414    fts3GetDeltaPosition(&pCsr, &iFirst);
134415    assert( iFirst>=0 );
134416    pPhrase->pHead = pCsr;
134417    pPhrase->pTail = pCsr;
134418    pPhrase->iHead = iFirst;
134419    pPhrase->iTail = iFirst;
134420  }else{
134421    assert( rc!=SQLITE_OK || (
134422       pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0
134423    ));
134424  }
134425
134426  return rc;
134427}
134428
134429/*
134430** Select the fragment of text consisting of nFragment contiguous tokens
134431** from column iCol that represent the "best" snippet. The best snippet
134432** is the snippet with the highest score, where scores are calculated
134433** by adding:
134434**
134435**   (a) +1 point for each occurrence of a matchable phrase in the snippet.
134436**
134437**   (b) +1000 points for the first occurrence of each matchable phrase in
134438**       the snippet for which the corresponding mCovered bit is not set.
134439**
134440** The selected snippet parameters are stored in structure *pFragment before
134441** returning. The score of the selected snippet is stored in *piScore
134442** before returning.
134443*/
134444static int fts3BestSnippet(
134445  int nSnippet,                   /* Desired snippet length */
134446  Fts3Cursor *pCsr,               /* Cursor to create snippet for */
134447  int iCol,                       /* Index of column to create snippet from */
134448  u64 mCovered,                   /* Mask of phrases already covered */
134449  u64 *pmSeen,                    /* IN/OUT: Mask of phrases seen */
134450  SnippetFragment *pFragment,     /* OUT: Best snippet found */
134451  int *piScore                    /* OUT: Score of snippet pFragment */
134452){
134453  int rc;                         /* Return Code */
134454  int nList;                      /* Number of phrases in expression */
134455  SnippetIter sIter;              /* Iterates through snippet candidates */
134456  int nByte;                      /* Number of bytes of space to allocate */
134457  int iBestScore = -1;            /* Best snippet score found so far */
134458  int i;                          /* Loop counter */
134459
134460  memset(&sIter, 0, sizeof(sIter));
134461
134462  /* Iterate through the phrases in the expression to count them. The same
134463  ** callback makes sure the doclists are loaded for each phrase.
134464  */
134465  rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
134466  if( rc!=SQLITE_OK ){
134467    return rc;
134468  }
134469
134470  /* Now that it is known how many phrases there are, allocate and zero
134471  ** the required space using malloc().
134472  */
134473  nByte = sizeof(SnippetPhrase) * nList;
134474  sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
134475  if( !sIter.aPhrase ){
134476    return SQLITE_NOMEM;
134477  }
134478  memset(sIter.aPhrase, 0, nByte);
134479
134480  /* Initialize the contents of the SnippetIter object. Then iterate through
134481  ** the set of phrases in the expression to populate the aPhrase[] array.
134482  */
134483  sIter.pCsr = pCsr;
134484  sIter.iCol = iCol;
134485  sIter.nSnippet = nSnippet;
134486  sIter.nPhrase = nList;
134487  sIter.iCurrent = -1;
134488  (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter);
134489
134490  /* Set the *pmSeen output variable. */
134491  for(i=0; i<nList; i++){
134492    if( sIter.aPhrase[i].pHead ){
134493      *pmSeen |= (u64)1 << i;
134494    }
134495  }
134496
134497  /* Loop through all candidate snippets. Store the best snippet in
134498  ** *pFragment. Store its associated 'score' in iBestScore.
134499  */
134500  pFragment->iCol = iCol;
134501  while( !fts3SnippetNextCandidate(&sIter) ){
134502    int iPos;
134503    int iScore;
134504    u64 mCover;
134505    u64 mHighlight;
134506    fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover, &mHighlight);
134507    assert( iScore>=0 );
134508    if( iScore>iBestScore ){
134509      pFragment->iPos = iPos;
134510      pFragment->hlmask = mHighlight;
134511      pFragment->covered = mCover;
134512      iBestScore = iScore;
134513    }
134514  }
134515
134516  sqlite3_free(sIter.aPhrase);
134517  *piScore = iBestScore;
134518  return SQLITE_OK;
134519}
134520
134521
134522/*
134523** Append a string to the string-buffer passed as the first argument.
134524**
134525** If nAppend is negative, then the length of the string zAppend is
134526** determined using strlen().
134527*/
134528static int fts3StringAppend(
134529  StrBuffer *pStr,                /* Buffer to append to */
134530  const char *zAppend,            /* Pointer to data to append to buffer */
134531  int nAppend                     /* Size of zAppend in bytes (or -1) */
134532){
134533  if( nAppend<0 ){
134534    nAppend = (int)strlen(zAppend);
134535  }
134536
134537  /* If there is insufficient space allocated at StrBuffer.z, use realloc()
134538  ** to grow the buffer until so that it is big enough to accomadate the
134539  ** appended data.
134540  */
134541  if( pStr->n+nAppend+1>=pStr->nAlloc ){
134542    int nAlloc = pStr->nAlloc+nAppend+100;
134543    char *zNew = sqlite3_realloc(pStr->z, nAlloc);
134544    if( !zNew ){
134545      return SQLITE_NOMEM;
134546    }
134547    pStr->z = zNew;
134548    pStr->nAlloc = nAlloc;
134549  }
134550
134551  /* Append the data to the string buffer. */
134552  memcpy(&pStr->z[pStr->n], zAppend, nAppend);
134553  pStr->n += nAppend;
134554  pStr->z[pStr->n] = '\0';
134555
134556  return SQLITE_OK;
134557}
134558
134559/*
134560** The fts3BestSnippet() function often selects snippets that end with a
134561** query term. That is, the final term of the snippet is always a term
134562** that requires highlighting. For example, if 'X' is a highlighted term
134563** and '.' is a non-highlighted term, BestSnippet() may select:
134564**
134565**     ........X.....X
134566**
134567** This function "shifts" the beginning of the snippet forward in the
134568** document so that there are approximately the same number of
134569** non-highlighted terms to the right of the final highlighted term as there
134570** are to the left of the first highlighted term. For example, to this:
134571**
134572**     ....X.....X....
134573**
134574** This is done as part of extracting the snippet text, not when selecting
134575** the snippet. Snippet selection is done based on doclists only, so there
134576** is no way for fts3BestSnippet() to know whether or not the document
134577** actually contains terms that follow the final highlighted term.
134578*/
134579static int fts3SnippetShift(
134580  Fts3Table *pTab,                /* FTS3 table snippet comes from */
134581  int iLangid,                    /* Language id to use in tokenizing */
134582  int nSnippet,                   /* Number of tokens desired for snippet */
134583  const char *zDoc,               /* Document text to extract snippet from */
134584  int nDoc,                       /* Size of buffer zDoc in bytes */
134585  int *piPos,                     /* IN/OUT: First token of snippet */
134586  u64 *pHlmask                    /* IN/OUT: Mask of tokens to highlight */
134587){
134588  u64 hlmask = *pHlmask;          /* Local copy of initial highlight-mask */
134589
134590  if( hlmask ){
134591    int nLeft;                    /* Tokens to the left of first highlight */
134592    int nRight;                   /* Tokens to the right of last highlight */
134593    int nDesired;                 /* Ideal number of tokens to shift forward */
134594
134595    for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
134596    for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
134597    nDesired = (nLeft-nRight)/2;
134598
134599    /* Ideally, the start of the snippet should be pushed forward in the
134600    ** document nDesired tokens. This block checks if there are actually
134601    ** nDesired tokens to the right of the snippet. If so, *piPos and
134602    ** *pHlMask are updated to shift the snippet nDesired tokens to the
134603    ** right. Otherwise, the snippet is shifted by the number of tokens
134604    ** available.
134605    */
134606    if( nDesired>0 ){
134607      int nShift;                 /* Number of tokens to shift snippet by */
134608      int iCurrent = 0;           /* Token counter */
134609      int rc;                     /* Return Code */
134610      sqlite3_tokenizer_module *pMod;
134611      sqlite3_tokenizer_cursor *pC;
134612      pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
134613
134614      /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
134615      ** or more tokens in zDoc/nDoc.
134616      */
134617      rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
134618      if( rc!=SQLITE_OK ){
134619        return rc;
134620      }
134621      while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
134622        const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
134623        rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
134624      }
134625      pMod->xClose(pC);
134626      if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
134627
134628      nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
134629      assert( nShift<=nDesired );
134630      if( nShift>0 ){
134631        *piPos += nShift;
134632        *pHlmask = hlmask >> nShift;
134633      }
134634    }
134635  }
134636  return SQLITE_OK;
134637}
134638
134639/*
134640** Extract the snippet text for fragment pFragment from cursor pCsr and
134641** append it to string buffer pOut.
134642*/
134643static int fts3SnippetText(
134644  Fts3Cursor *pCsr,               /* FTS3 Cursor */
134645  SnippetFragment *pFragment,     /* Snippet to extract */
134646  int iFragment,                  /* Fragment number */
134647  int isLast,                     /* True for final fragment in snippet */
134648  int nSnippet,                   /* Number of tokens in extracted snippet */
134649  const char *zOpen,              /* String inserted before highlighted term */
134650  const char *zClose,             /* String inserted after highlighted term */
134651  const char *zEllipsis,          /* String inserted between snippets */
134652  StrBuffer *pOut                 /* Write output here */
134653){
134654  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
134655  int rc;                         /* Return code */
134656  const char *zDoc;               /* Document text to extract snippet from */
134657  int nDoc;                       /* Size of zDoc in bytes */
134658  int iCurrent = 0;               /* Current token number of document */
134659  int iEnd = 0;                   /* Byte offset of end of current token */
134660  int isShiftDone = 0;            /* True after snippet is shifted */
134661  int iPos = pFragment->iPos;     /* First token of snippet */
134662  u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
134663  int iCol = pFragment->iCol+1;   /* Query column to extract text from */
134664  sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
134665  sqlite3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */
134666
134667  zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
134668  if( zDoc==0 ){
134669    if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
134670      return SQLITE_NOMEM;
134671    }
134672    return SQLITE_OK;
134673  }
134674  nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
134675
134676  /* Open a token cursor on the document. */
134677  pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
134678  rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
134679  if( rc!=SQLITE_OK ){
134680    return rc;
134681  }
134682
134683  while( rc==SQLITE_OK ){
134684    const char *ZDUMMY;           /* Dummy argument used with tokenizer */
134685    int DUMMY1 = -1;              /* Dummy argument used with tokenizer */
134686    int iBegin = 0;               /* Offset in zDoc of start of token */
134687    int iFin = 0;                 /* Offset in zDoc of end of token */
134688    int isHighlight = 0;          /* True for highlighted terms */
134689
134690    /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
134691    ** in the FTS code the variable that the third argument to xNext points to
134692    ** is initialized to zero before the first (*but not necessarily
134693    ** subsequent*) call to xNext(). This is done for a particular application
134694    ** that needs to know whether or not the tokenizer is being used for
134695    ** snippet generation or for some other purpose.
134696    **
134697    ** Extreme care is required when writing code to depend on this
134698    ** initialization. It is not a documented part of the tokenizer interface.
134699    ** If a tokenizer is used directly by any code outside of FTS, this
134700    ** convention might not be respected.  */
134701    rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
134702    if( rc!=SQLITE_OK ){
134703      if( rc==SQLITE_DONE ){
134704        /* Special case - the last token of the snippet is also the last token
134705        ** of the column. Append any punctuation that occurred between the end
134706        ** of the previous token and the end of the document to the output.
134707        ** Then break out of the loop. */
134708        rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
134709      }
134710      break;
134711    }
134712    if( iCurrent<iPos ){ continue; }
134713
134714    if( !isShiftDone ){
134715      int n = nDoc - iBegin;
134716      rc = fts3SnippetShift(
134717          pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
134718      );
134719      isShiftDone = 1;
134720
134721      /* Now that the shift has been done, check if the initial "..." are
134722      ** required. They are required if (a) this is not the first fragment,
134723      ** or (b) this fragment does not begin at position 0 of its column.
134724      */
134725      if( rc==SQLITE_OK && (iPos>0 || iFragment>0) ){
134726        rc = fts3StringAppend(pOut, zEllipsis, -1);
134727      }
134728      if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
134729    }
134730
134731    if( iCurrent>=(iPos+nSnippet) ){
134732      if( isLast ){
134733        rc = fts3StringAppend(pOut, zEllipsis, -1);
134734      }
134735      break;
134736    }
134737
134738    /* Set isHighlight to true if this term should be highlighted. */
134739    isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
134740
134741    if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
134742    if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
134743    if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
134744    if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
134745
134746    iEnd = iFin;
134747  }
134748
134749  pMod->xClose(pC);
134750  return rc;
134751}
134752
134753
134754/*
134755** This function is used to count the entries in a column-list (a
134756** delta-encoded list of term offsets within a single column of a single
134757** row). When this function is called, *ppCollist should point to the
134758** beginning of the first varint in the column-list (the varint that
134759** contains the position of the first matching term in the column data).
134760** Before returning, *ppCollist is set to point to the first byte after
134761** the last varint in the column-list (either the 0x00 signifying the end
134762** of the position-list, or the 0x01 that precedes the column number of
134763** the next column in the position-list).
134764**
134765** The number of elements in the column-list is returned.
134766*/
134767static int fts3ColumnlistCount(char **ppCollist){
134768  char *pEnd = *ppCollist;
134769  char c = 0;
134770  int nEntry = 0;
134771
134772  /* A column-list is terminated by either a 0x01 or 0x00. */
134773  while( 0xFE & (*pEnd | c) ){
134774    c = *pEnd++ & 0x80;
134775    if( !c ) nEntry++;
134776  }
134777
134778  *ppCollist = pEnd;
134779  return nEntry;
134780}
134781
134782/*
134783** fts3ExprIterate() callback used to collect the "global" matchinfo stats
134784** for a single query.
134785**
134786** fts3ExprIterate() callback to load the 'global' elements of a
134787** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
134788** of the matchinfo array that are constant for all rows returned by the
134789** current query.
134790**
134791** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
134792** function populates Matchinfo.aMatchinfo[] as follows:
134793**
134794**   for(iCol=0; iCol<nCol; iCol++){
134795**     aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
134796**     aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
134797**   }
134798**
134799** where X is the number of matches for phrase iPhrase is column iCol of all
134800** rows of the table. Y is the number of rows for which column iCol contains
134801** at least one instance of phrase iPhrase.
134802**
134803** If the phrase pExpr consists entirely of deferred tokens, then all X and
134804** Y values are set to nDoc, where nDoc is the number of documents in the
134805** file system. This is done because the full-text index doclist is required
134806** to calculate these values properly, and the full-text index doclist is
134807** not available for deferred tokens.
134808*/
134809static int fts3ExprGlobalHitsCb(
134810  Fts3Expr *pExpr,                /* Phrase expression node */
134811  int iPhrase,                    /* Phrase number (numbered from zero) */
134812  void *pCtx                      /* Pointer to MatchInfo structure */
134813){
134814  MatchInfo *p = (MatchInfo *)pCtx;
134815  return sqlite3Fts3EvalPhraseStats(
134816      p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
134817  );
134818}
134819
134820/*
134821** fts3ExprIterate() callback used to collect the "local" part of the
134822** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
134823** array that are different for each row returned by the query.
134824*/
134825static int fts3ExprLocalHitsCb(
134826  Fts3Expr *pExpr,                /* Phrase expression node */
134827  int iPhrase,                    /* Phrase number */
134828  void *pCtx                      /* Pointer to MatchInfo structure */
134829){
134830  int rc = SQLITE_OK;
134831  MatchInfo *p = (MatchInfo *)pCtx;
134832  int iStart = iPhrase * p->nCol * 3;
134833  int i;
134834
134835  for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
134836    char *pCsr;
134837    rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
134838    if( pCsr ){
134839      p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
134840    }else{
134841      p->aMatchinfo[iStart+i*3] = 0;
134842    }
134843  }
134844
134845  return rc;
134846}
134847
134848static int fts3MatchinfoCheck(
134849  Fts3Table *pTab,
134850  char cArg,
134851  char **pzErr
134852){
134853  if( (cArg==FTS3_MATCHINFO_NPHRASE)
134854   || (cArg==FTS3_MATCHINFO_NCOL)
134855   || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
134856   || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
134857   || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
134858   || (cArg==FTS3_MATCHINFO_LCS)
134859   || (cArg==FTS3_MATCHINFO_HITS)
134860  ){
134861    return SQLITE_OK;
134862  }
134863  *pzErr = sqlite3_mprintf("unrecognized matchinfo request: %c", cArg);
134864  return SQLITE_ERROR;
134865}
134866
134867static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
134868  int nVal;                       /* Number of integers output by cArg */
134869
134870  switch( cArg ){
134871    case FTS3_MATCHINFO_NDOC:
134872    case FTS3_MATCHINFO_NPHRASE:
134873    case FTS3_MATCHINFO_NCOL:
134874      nVal = 1;
134875      break;
134876
134877    case FTS3_MATCHINFO_AVGLENGTH:
134878    case FTS3_MATCHINFO_LENGTH:
134879    case FTS3_MATCHINFO_LCS:
134880      nVal = pInfo->nCol;
134881      break;
134882
134883    default:
134884      assert( cArg==FTS3_MATCHINFO_HITS );
134885      nVal = pInfo->nCol * pInfo->nPhrase * 3;
134886      break;
134887  }
134888
134889  return nVal;
134890}
134891
134892static int fts3MatchinfoSelectDoctotal(
134893  Fts3Table *pTab,
134894  sqlite3_stmt **ppStmt,
134895  sqlite3_int64 *pnDoc,
134896  const char **paLen
134897){
134898  sqlite3_stmt *pStmt;
134899  const char *a;
134900  sqlite3_int64 nDoc;
134901
134902  if( !*ppStmt ){
134903    int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
134904    if( rc!=SQLITE_OK ) return rc;
134905  }
134906  pStmt = *ppStmt;
134907  assert( sqlite3_data_count(pStmt)==1 );
134908
134909  a = sqlite3_column_blob(pStmt, 0);
134910  a += sqlite3Fts3GetVarint(a, &nDoc);
134911  if( nDoc==0 ) return FTS_CORRUPT_VTAB;
134912  *pnDoc = (u32)nDoc;
134913
134914  if( paLen ) *paLen = a;
134915  return SQLITE_OK;
134916}
134917
134918/*
134919** An instance of the following structure is used to store state while
134920** iterating through a multi-column position-list corresponding to the
134921** hits for a single phrase on a single row in order to calculate the
134922** values for a matchinfo() FTS3_MATCHINFO_LCS request.
134923*/
134924typedef struct LcsIterator LcsIterator;
134925struct LcsIterator {
134926  Fts3Expr *pExpr;                /* Pointer to phrase expression */
134927  int iPosOffset;                 /* Tokens count up to end of this phrase */
134928  char *pRead;                    /* Cursor used to iterate through aDoclist */
134929  int iPos;                       /* Current position */
134930};
134931
134932/*
134933** If LcsIterator.iCol is set to the following value, the iterator has
134934** finished iterating through all offsets for all columns.
134935*/
134936#define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
134937
134938static int fts3MatchinfoLcsCb(
134939  Fts3Expr *pExpr,                /* Phrase expression node */
134940  int iPhrase,                    /* Phrase number (numbered from zero) */
134941  void *pCtx                      /* Pointer to MatchInfo structure */
134942){
134943  LcsIterator *aIter = (LcsIterator *)pCtx;
134944  aIter[iPhrase].pExpr = pExpr;
134945  return SQLITE_OK;
134946}
134947
134948/*
134949** Advance the iterator passed as an argument to the next position. Return
134950** 1 if the iterator is at EOF or if it now points to the start of the
134951** position list for the next column.
134952*/
134953static int fts3LcsIteratorAdvance(LcsIterator *pIter){
134954  char *pRead = pIter->pRead;
134955  sqlite3_int64 iRead;
134956  int rc = 0;
134957
134958  pRead += sqlite3Fts3GetVarint(pRead, &iRead);
134959  if( iRead==0 || iRead==1 ){
134960    pRead = 0;
134961    rc = 1;
134962  }else{
134963    pIter->iPos += (int)(iRead-2);
134964  }
134965
134966  pIter->pRead = pRead;
134967  return rc;
134968}
134969
134970/*
134971** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
134972**
134973** If the call is successful, the longest-common-substring lengths for each
134974** column are written into the first nCol elements of the pInfo->aMatchinfo[]
134975** array before returning. SQLITE_OK is returned in this case.
134976**
134977** Otherwise, if an error occurs, an SQLite error code is returned and the
134978** data written to the first nCol elements of pInfo->aMatchinfo[] is
134979** undefined.
134980*/
134981static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
134982  LcsIterator *aIter;
134983  int i;
134984  int iCol;
134985  int nToken = 0;
134986
134987  /* Allocate and populate the array of LcsIterator objects. The array
134988  ** contains one element for each matchable phrase in the query.
134989  **/
134990  aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
134991  if( !aIter ) return SQLITE_NOMEM;
134992  memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
134993  (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
134994
134995  for(i=0; i<pInfo->nPhrase; i++){
134996    LcsIterator *pIter = &aIter[i];
134997    nToken -= pIter->pExpr->pPhrase->nToken;
134998    pIter->iPosOffset = nToken;
134999  }
135000
135001  for(iCol=0; iCol<pInfo->nCol; iCol++){
135002    int nLcs = 0;                 /* LCS value for this column */
135003    int nLive = 0;                /* Number of iterators in aIter not at EOF */
135004
135005    for(i=0; i<pInfo->nPhrase; i++){
135006      int rc;
135007      LcsIterator *pIt = &aIter[i];
135008      rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
135009      if( rc!=SQLITE_OK ) return rc;
135010      if( pIt->pRead ){
135011        pIt->iPos = pIt->iPosOffset;
135012        fts3LcsIteratorAdvance(&aIter[i]);
135013        nLive++;
135014      }
135015    }
135016
135017    while( nLive>0 ){
135018      LcsIterator *pAdv = 0;      /* The iterator to advance by one position */
135019      int nThisLcs = 0;           /* LCS for the current iterator positions */
135020
135021      for(i=0; i<pInfo->nPhrase; i++){
135022        LcsIterator *pIter = &aIter[i];
135023        if( pIter->pRead==0 ){
135024          /* This iterator is already at EOF for this column. */
135025          nThisLcs = 0;
135026        }else{
135027          if( pAdv==0 || pIter->iPos<pAdv->iPos ){
135028            pAdv = pIter;
135029          }
135030          if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
135031            nThisLcs++;
135032          }else{
135033            nThisLcs = 1;
135034          }
135035          if( nThisLcs>nLcs ) nLcs = nThisLcs;
135036        }
135037      }
135038      if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
135039    }
135040
135041    pInfo->aMatchinfo[iCol] = nLcs;
135042  }
135043
135044  sqlite3_free(aIter);
135045  return SQLITE_OK;
135046}
135047
135048/*
135049** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
135050** be returned by the matchinfo() function. Argument zArg contains the
135051** format string passed as the second argument to matchinfo (or the
135052** default value "pcx" if no second argument was specified). The format
135053** string has already been validated and the pInfo->aMatchinfo[] array
135054** is guaranteed to be large enough for the output.
135055**
135056** If bGlobal is true, then populate all fields of the matchinfo() output.
135057** If it is false, then assume that those fields that do not change between
135058** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
135059** have already been populated.
135060**
135061** Return SQLITE_OK if successful, or an SQLite error code if an error
135062** occurs. If a value other than SQLITE_OK is returned, the state the
135063** pInfo->aMatchinfo[] buffer is left in is undefined.
135064*/
135065static int fts3MatchinfoValues(
135066  Fts3Cursor *pCsr,               /* FTS3 cursor object */
135067  int bGlobal,                    /* True to grab the global stats */
135068  MatchInfo *pInfo,               /* Matchinfo context object */
135069  const char *zArg                /* Matchinfo format string */
135070){
135071  int rc = SQLITE_OK;
135072  int i;
135073  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
135074  sqlite3_stmt *pSelect = 0;
135075
135076  for(i=0; rc==SQLITE_OK && zArg[i]; i++){
135077
135078    switch( zArg[i] ){
135079      case FTS3_MATCHINFO_NPHRASE:
135080        if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
135081        break;
135082
135083      case FTS3_MATCHINFO_NCOL:
135084        if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
135085        break;
135086
135087      case FTS3_MATCHINFO_NDOC:
135088        if( bGlobal ){
135089          sqlite3_int64 nDoc = 0;
135090          rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
135091          pInfo->aMatchinfo[0] = (u32)nDoc;
135092        }
135093        break;
135094
135095      case FTS3_MATCHINFO_AVGLENGTH:
135096        if( bGlobal ){
135097          sqlite3_int64 nDoc;     /* Number of rows in table */
135098          const char *a;          /* Aggregate column length array */
135099
135100          rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
135101          if( rc==SQLITE_OK ){
135102            int iCol;
135103            for(iCol=0; iCol<pInfo->nCol; iCol++){
135104              u32 iVal;
135105              sqlite3_int64 nToken;
135106              a += sqlite3Fts3GetVarint(a, &nToken);
135107              iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
135108              pInfo->aMatchinfo[iCol] = iVal;
135109            }
135110          }
135111        }
135112        break;
135113
135114      case FTS3_MATCHINFO_LENGTH: {
135115        sqlite3_stmt *pSelectDocsize = 0;
135116        rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
135117        if( rc==SQLITE_OK ){
135118          int iCol;
135119          const char *a = sqlite3_column_blob(pSelectDocsize, 0);
135120          for(iCol=0; iCol<pInfo->nCol; iCol++){
135121            sqlite3_int64 nToken;
135122            a += sqlite3Fts3GetVarint(a, &nToken);
135123            pInfo->aMatchinfo[iCol] = (u32)nToken;
135124          }
135125        }
135126        sqlite3_reset(pSelectDocsize);
135127        break;
135128      }
135129
135130      case FTS3_MATCHINFO_LCS:
135131        rc = fts3ExprLoadDoclists(pCsr, 0, 0);
135132        if( rc==SQLITE_OK ){
135133          rc = fts3MatchinfoLcs(pCsr, pInfo);
135134        }
135135        break;
135136
135137      default: {
135138        Fts3Expr *pExpr;
135139        assert( zArg[i]==FTS3_MATCHINFO_HITS );
135140        pExpr = pCsr->pExpr;
135141        rc = fts3ExprLoadDoclists(pCsr, 0, 0);
135142        if( rc!=SQLITE_OK ) break;
135143        if( bGlobal ){
135144          if( pCsr->pDeferred ){
135145            rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
135146            if( rc!=SQLITE_OK ) break;
135147          }
135148          rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
135149          if( rc!=SQLITE_OK ) break;
135150        }
135151        (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
135152        break;
135153      }
135154    }
135155
135156    pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
135157  }
135158
135159  sqlite3_reset(pSelect);
135160  return rc;
135161}
135162
135163
135164/*
135165** Populate pCsr->aMatchinfo[] with data for the current row. The
135166** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
135167*/
135168static int fts3GetMatchinfo(
135169  Fts3Cursor *pCsr,               /* FTS3 Cursor object */
135170  const char *zArg                /* Second argument to matchinfo() function */
135171){
135172  MatchInfo sInfo;
135173  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
135174  int rc = SQLITE_OK;
135175  int bGlobal = 0;                /* Collect 'global' stats as well as local */
135176
135177  memset(&sInfo, 0, sizeof(MatchInfo));
135178  sInfo.pCursor = pCsr;
135179  sInfo.nCol = pTab->nColumn;
135180
135181  /* If there is cached matchinfo() data, but the format string for the
135182  ** cache does not match the format string for this request, discard
135183  ** the cached data. */
135184  if( pCsr->zMatchinfo && strcmp(pCsr->zMatchinfo, zArg) ){
135185    assert( pCsr->aMatchinfo );
135186    sqlite3_free(pCsr->aMatchinfo);
135187    pCsr->zMatchinfo = 0;
135188    pCsr->aMatchinfo = 0;
135189  }
135190
135191  /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the
135192  ** matchinfo function has been called for this query. In this case
135193  ** allocate the array used to accumulate the matchinfo data and
135194  ** initialize those elements that are constant for every row.
135195  */
135196  if( pCsr->aMatchinfo==0 ){
135197    int nMatchinfo = 0;           /* Number of u32 elements in match-info */
135198    int nArg;                     /* Bytes in zArg */
135199    int i;                        /* Used to iterate through zArg */
135200
135201    /* Determine the number of phrases in the query */
135202    pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
135203    sInfo.nPhrase = pCsr->nPhrase;
135204
135205    /* Determine the number of integers in the buffer returned by this call. */
135206    for(i=0; zArg[i]; i++){
135207      nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
135208    }
135209
135210    /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
135211    nArg = (int)strlen(zArg);
135212    pCsr->aMatchinfo = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo + nArg + 1);
135213    if( !pCsr->aMatchinfo ) return SQLITE_NOMEM;
135214
135215    pCsr->zMatchinfo = (char *)&pCsr->aMatchinfo[nMatchinfo];
135216    pCsr->nMatchinfo = nMatchinfo;
135217    memcpy(pCsr->zMatchinfo, zArg, nArg+1);
135218    memset(pCsr->aMatchinfo, 0, sizeof(u32)*nMatchinfo);
135219    pCsr->isMatchinfoNeeded = 1;
135220    bGlobal = 1;
135221  }
135222
135223  sInfo.aMatchinfo = pCsr->aMatchinfo;
135224  sInfo.nPhrase = pCsr->nPhrase;
135225  if( pCsr->isMatchinfoNeeded ){
135226    rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
135227    pCsr->isMatchinfoNeeded = 0;
135228  }
135229
135230  return rc;
135231}
135232
135233/*
135234** Implementation of snippet() function.
135235*/
135236SQLITE_PRIVATE void sqlite3Fts3Snippet(
135237  sqlite3_context *pCtx,          /* SQLite function call context */
135238  Fts3Cursor *pCsr,               /* Cursor object */
135239  const char *zStart,             /* Snippet start text - "<b>" */
135240  const char *zEnd,               /* Snippet end text - "</b>" */
135241  const char *zEllipsis,          /* Snippet ellipsis text - "<b>...</b>" */
135242  int iCol,                       /* Extract snippet from this column */
135243  int nToken                      /* Approximate number of tokens in snippet */
135244){
135245  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
135246  int rc = SQLITE_OK;
135247  int i;
135248  StrBuffer res = {0, 0, 0};
135249
135250  /* The returned text includes up to four fragments of text extracted from
135251  ** the data in the current row. The first iteration of the for(...) loop
135252  ** below attempts to locate a single fragment of text nToken tokens in
135253  ** size that contains at least one instance of all phrases in the query
135254  ** expression that appear in the current row. If such a fragment of text
135255  ** cannot be found, the second iteration of the loop attempts to locate
135256  ** a pair of fragments, and so on.
135257  */
135258  int nSnippet = 0;               /* Number of fragments in this snippet */
135259  SnippetFragment aSnippet[4];    /* Maximum of 4 fragments per snippet */
135260  int nFToken = -1;               /* Number of tokens in each fragment */
135261
135262  if( !pCsr->pExpr ){
135263    sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
135264    return;
135265  }
135266
135267  for(nSnippet=1; 1; nSnippet++){
135268
135269    int iSnip;                    /* Loop counter 0..nSnippet-1 */
135270    u64 mCovered = 0;             /* Bitmask of phrases covered by snippet */
135271    u64 mSeen = 0;                /* Bitmask of phrases seen by BestSnippet() */
135272
135273    if( nToken>=0 ){
135274      nFToken = (nToken+nSnippet-1) / nSnippet;
135275    }else{
135276      nFToken = -1 * nToken;
135277    }
135278
135279    for(iSnip=0; iSnip<nSnippet; iSnip++){
135280      int iBestScore = -1;        /* Best score of columns checked so far */
135281      int iRead;                  /* Used to iterate through columns */
135282      SnippetFragment *pFragment = &aSnippet[iSnip];
135283
135284      memset(pFragment, 0, sizeof(*pFragment));
135285
135286      /* Loop through all columns of the table being considered for snippets.
135287      ** If the iCol argument to this function was negative, this means all
135288      ** columns of the FTS3 table. Otherwise, only column iCol is considered.
135289      */
135290      for(iRead=0; iRead<pTab->nColumn; iRead++){
135291        SnippetFragment sF = {0, 0, 0, 0};
135292        int iS;
135293        if( iCol>=0 && iRead!=iCol ) continue;
135294
135295        /* Find the best snippet of nFToken tokens in column iRead. */
135296        rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
135297        if( rc!=SQLITE_OK ){
135298          goto snippet_out;
135299        }
135300        if( iS>iBestScore ){
135301          *pFragment = sF;
135302          iBestScore = iS;
135303        }
135304      }
135305
135306      mCovered |= pFragment->covered;
135307    }
135308
135309    /* If all query phrases seen by fts3BestSnippet() are present in at least
135310    ** one of the nSnippet snippet fragments, break out of the loop.
135311    */
135312    assert( (mCovered&mSeen)==mCovered );
135313    if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
135314  }
135315
135316  assert( nFToken>0 );
135317
135318  for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
135319    rc = fts3SnippetText(pCsr, &aSnippet[i],
135320        i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
135321    );
135322  }
135323
135324 snippet_out:
135325  sqlite3Fts3SegmentsClose(pTab);
135326  if( rc!=SQLITE_OK ){
135327    sqlite3_result_error_code(pCtx, rc);
135328    sqlite3_free(res.z);
135329  }else{
135330    sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
135331  }
135332}
135333
135334
135335typedef struct TermOffset TermOffset;
135336typedef struct TermOffsetCtx TermOffsetCtx;
135337
135338struct TermOffset {
135339  char *pList;                    /* Position-list */
135340  int iPos;                       /* Position just read from pList */
135341  int iOff;                       /* Offset of this term from read positions */
135342};
135343
135344struct TermOffsetCtx {
135345  Fts3Cursor *pCsr;
135346  int iCol;                       /* Column of table to populate aTerm for */
135347  int iTerm;
135348  sqlite3_int64 iDocid;
135349  TermOffset *aTerm;
135350};
135351
135352/*
135353** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
135354*/
135355static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
135356  TermOffsetCtx *p = (TermOffsetCtx *)ctx;
135357  int nTerm;                      /* Number of tokens in phrase */
135358  int iTerm;                      /* For looping through nTerm phrase terms */
135359  char *pList;                    /* Pointer to position list for phrase */
135360  int iPos = 0;                   /* First position in position-list */
135361  int rc;
135362
135363  UNUSED_PARAMETER(iPhrase);
135364  rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
135365  nTerm = pExpr->pPhrase->nToken;
135366  if( pList ){
135367    fts3GetDeltaPosition(&pList, &iPos);
135368    assert( iPos>=0 );
135369  }
135370
135371  for(iTerm=0; iTerm<nTerm; iTerm++){
135372    TermOffset *pT = &p->aTerm[p->iTerm++];
135373    pT->iOff = nTerm-iTerm-1;
135374    pT->pList = pList;
135375    pT->iPos = iPos;
135376  }
135377
135378  return rc;
135379}
135380
135381/*
135382** Implementation of offsets() function.
135383*/
135384SQLITE_PRIVATE void sqlite3Fts3Offsets(
135385  sqlite3_context *pCtx,          /* SQLite function call context */
135386  Fts3Cursor *pCsr                /* Cursor object */
135387){
135388  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
135389  sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
135390  int rc;                         /* Return Code */
135391  int nToken;                     /* Number of tokens in query */
135392  int iCol;                       /* Column currently being processed */
135393  StrBuffer res = {0, 0, 0};      /* Result string */
135394  TermOffsetCtx sCtx;             /* Context for fts3ExprTermOffsetInit() */
135395
135396  if( !pCsr->pExpr ){
135397    sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
135398    return;
135399  }
135400
135401  memset(&sCtx, 0, sizeof(sCtx));
135402  assert( pCsr->isRequireSeek==0 );
135403
135404  /* Count the number of terms in the query */
135405  rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
135406  if( rc!=SQLITE_OK ) goto offsets_out;
135407
135408  /* Allocate the array of TermOffset iterators. */
135409  sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
135410  if( 0==sCtx.aTerm ){
135411    rc = SQLITE_NOMEM;
135412    goto offsets_out;
135413  }
135414  sCtx.iDocid = pCsr->iPrevId;
135415  sCtx.pCsr = pCsr;
135416
135417  /* Loop through the table columns, appending offset information to
135418  ** string-buffer res for each column.
135419  */
135420  for(iCol=0; iCol<pTab->nColumn; iCol++){
135421    sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
135422    const char *ZDUMMY;           /* Dummy argument used with xNext() */
135423    int NDUMMY = 0;               /* Dummy argument used with xNext() */
135424    int iStart = 0;
135425    int iEnd = 0;
135426    int iCurrent = 0;
135427    const char *zDoc;
135428    int nDoc;
135429
135430    /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
135431    ** no way that this operation can fail, so the return code from
135432    ** fts3ExprIterate() can be discarded.
135433    */
135434    sCtx.iCol = iCol;
135435    sCtx.iTerm = 0;
135436    (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx);
135437
135438    /* Retreive the text stored in column iCol. If an SQL NULL is stored
135439    ** in column iCol, jump immediately to the next iteration of the loop.
135440    ** If an OOM occurs while retrieving the data (this can happen if SQLite
135441    ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
135442    ** to the caller.
135443    */
135444    zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
135445    nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
135446    if( zDoc==0 ){
135447      if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
135448        continue;
135449      }
135450      rc = SQLITE_NOMEM;
135451      goto offsets_out;
135452    }
135453
135454    /* Initialize a tokenizer iterator to iterate through column iCol. */
135455    rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
135456        zDoc, nDoc, &pC
135457    );
135458    if( rc!=SQLITE_OK ) goto offsets_out;
135459
135460    rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
135461    while( rc==SQLITE_OK ){
135462      int i;                      /* Used to loop through terms */
135463      int iMinPos = 0x7FFFFFFF;   /* Position of next token */
135464      TermOffset *pTerm = 0;      /* TermOffset associated with next token */
135465
135466      for(i=0; i<nToken; i++){
135467        TermOffset *pT = &sCtx.aTerm[i];
135468        if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
135469          iMinPos = pT->iPos-pT->iOff;
135470          pTerm = pT;
135471        }
135472      }
135473
135474      if( !pTerm ){
135475        /* All offsets for this column have been gathered. */
135476        rc = SQLITE_DONE;
135477      }else{
135478        assert( iCurrent<=iMinPos );
135479        if( 0==(0xFE&*pTerm->pList) ){
135480          pTerm->pList = 0;
135481        }else{
135482          fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
135483        }
135484        while( rc==SQLITE_OK && iCurrent<iMinPos ){
135485          rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
135486        }
135487        if( rc==SQLITE_OK ){
135488          char aBuffer[64];
135489          sqlite3_snprintf(sizeof(aBuffer), aBuffer,
135490              "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
135491          );
135492          rc = fts3StringAppend(&res, aBuffer, -1);
135493        }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
135494          rc = FTS_CORRUPT_VTAB;
135495        }
135496      }
135497    }
135498    if( rc==SQLITE_DONE ){
135499      rc = SQLITE_OK;
135500    }
135501
135502    pMod->xClose(pC);
135503    if( rc!=SQLITE_OK ) goto offsets_out;
135504  }
135505
135506 offsets_out:
135507  sqlite3_free(sCtx.aTerm);
135508  assert( rc!=SQLITE_DONE );
135509  sqlite3Fts3SegmentsClose(pTab);
135510  if( rc!=SQLITE_OK ){
135511    sqlite3_result_error_code(pCtx,  rc);
135512    sqlite3_free(res.z);
135513  }else{
135514    sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
135515  }
135516  return;
135517}
135518
135519/*
135520** Implementation of matchinfo() function.
135521*/
135522SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
135523  sqlite3_context *pContext,      /* Function call context */
135524  Fts3Cursor *pCsr,               /* FTS3 table cursor */
135525  const char *zArg                /* Second arg to matchinfo() function */
135526){
135527  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
135528  int rc;
135529  int i;
135530  const char *zFormat;
135531
135532  if( zArg ){
135533    for(i=0; zArg[i]; i++){
135534      char *zErr = 0;
135535      if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
135536        sqlite3_result_error(pContext, zErr, -1);
135537        sqlite3_free(zErr);
135538        return;
135539      }
135540    }
135541    zFormat = zArg;
135542  }else{
135543    zFormat = FTS3_MATCHINFO_DEFAULT;
135544  }
135545
135546  if( !pCsr->pExpr ){
135547    sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
135548    return;
135549  }
135550
135551  /* Retrieve matchinfo() data. */
135552  rc = fts3GetMatchinfo(pCsr, zFormat);
135553  sqlite3Fts3SegmentsClose(pTab);
135554
135555  if( rc!=SQLITE_OK ){
135556    sqlite3_result_error_code(pContext, rc);
135557  }else{
135558    int n = pCsr->nMatchinfo * sizeof(u32);
135559    sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
135560  }
135561}
135562
135563#endif
135564
135565/************** End of fts3_snippet.c ****************************************/
135566/************** Begin file fts3_unicode.c ************************************/
135567/*
135568** 2012 May 24
135569**
135570** The author disclaims copyright to this source code.  In place of
135571** a legal notice, here is a blessing:
135572**
135573**    May you do good and not evil.
135574**    May you find forgiveness for yourself and forgive others.
135575**    May you share freely, never taking more than you give.
135576**
135577******************************************************************************
135578**
135579** Implementation of the "unicode" full-text-search tokenizer.
135580*/
135581
135582#ifdef SQLITE_ENABLE_FTS4_UNICODE61
135583
135584#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
135585
135586/* #include <assert.h> */
135587/* #include <stdlib.h> */
135588/* #include <stdio.h> */
135589/* #include <string.h> */
135590
135591
135592/*
135593** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
135594** from the sqlite3 source file utf.c. If this file is compiled as part
135595** of the amalgamation, they are not required.
135596*/
135597#ifndef SQLITE_AMALGAMATION
135598
135599static const unsigned char sqlite3Utf8Trans1[] = {
135600  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
135601  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
135602  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
135603  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
135604  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
135605  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
135606  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
135607  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
135608};
135609
135610#define READ_UTF8(zIn, zTerm, c)                           \
135611  c = *(zIn++);                                            \
135612  if( c>=0xc0 ){                                           \
135613    c = sqlite3Utf8Trans1[c-0xc0];                         \
135614    while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
135615      c = (c<<6) + (0x3f & *(zIn++));                      \
135616    }                                                      \
135617    if( c<0x80                                             \
135618        || (c&0xFFFFF800)==0xD800                          \
135619        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
135620  }
135621
135622#define WRITE_UTF8(zOut, c) {                          \
135623  if( c<0x00080 ){                                     \
135624    *zOut++ = (u8)(c&0xFF);                            \
135625  }                                                    \
135626  else if( c<0x00800 ){                                \
135627    *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
135628    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
135629  }                                                    \
135630  else if( c<0x10000 ){                                \
135631    *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
135632    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
135633    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
135634  }else{                                               \
135635    *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
135636    *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
135637    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
135638    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
135639  }                                                    \
135640}
135641
135642#endif /* ifndef SQLITE_AMALGAMATION */
135643
135644typedef struct unicode_tokenizer unicode_tokenizer;
135645typedef struct unicode_cursor unicode_cursor;
135646
135647struct unicode_tokenizer {
135648  sqlite3_tokenizer base;
135649  int bRemoveDiacritic;
135650  int nException;
135651  int *aiException;
135652};
135653
135654struct unicode_cursor {
135655  sqlite3_tokenizer_cursor base;
135656  const unsigned char *aInput;    /* Input text being tokenized */
135657  int nInput;                     /* Size of aInput[] in bytes */
135658  int iOff;                       /* Current offset within aInput[] */
135659  int iToken;                     /* Index of next token to be returned */
135660  char *zToken;                   /* storage for current token */
135661  int nAlloc;                     /* space allocated at zToken */
135662};
135663
135664
135665/*
135666** Destroy a tokenizer allocated by unicodeCreate().
135667*/
135668static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
135669  if( pTokenizer ){
135670    unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
135671    sqlite3_free(p->aiException);
135672    sqlite3_free(p);
135673  }
135674  return SQLITE_OK;
135675}
135676
135677/*
135678** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
135679** statement has specified that the tokenizer for this table shall consider
135680** all characters in string zIn/nIn to be separators (if bAlnum==0) or
135681** token characters (if bAlnum==1).
135682**
135683** For each codepoint in the zIn/nIn string, this function checks if the
135684** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
135685** If so, no action is taken. Otherwise, the codepoint is added to the
135686** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
135687** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
135688** codepoints in the aiException[] array.
135689**
135690** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
135691** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
135692** It is not possible to change the behavior of the tokenizer with respect
135693** to these codepoints.
135694*/
135695static int unicodeAddExceptions(
135696  unicode_tokenizer *p,           /* Tokenizer to add exceptions to */
135697  int bAlnum,                     /* Replace Isalnum() return value with this */
135698  const char *zIn,                /* Array of characters to make exceptions */
135699  int nIn                         /* Length of z in bytes */
135700){
135701  const unsigned char *z = (const unsigned char *)zIn;
135702  const unsigned char *zTerm = &z[nIn];
135703  int iCode;
135704  int nEntry = 0;
135705
135706  assert( bAlnum==0 || bAlnum==1 );
135707
135708  while( z<zTerm ){
135709    READ_UTF8(z, zTerm, iCode);
135710    assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
135711    if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
135712     && sqlite3FtsUnicodeIsdiacritic(iCode)==0
135713    ){
135714      nEntry++;
135715    }
135716  }
135717
135718  if( nEntry ){
135719    int *aNew;                    /* New aiException[] array */
135720    int nNew;                     /* Number of valid entries in array aNew[] */
135721
135722    aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int));
135723    if( aNew==0 ) return SQLITE_NOMEM;
135724    nNew = p->nException;
135725
135726    z = (const unsigned char *)zIn;
135727    while( z<zTerm ){
135728      READ_UTF8(z, zTerm, iCode);
135729      if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
135730       && sqlite3FtsUnicodeIsdiacritic(iCode)==0
135731      ){
135732        int i, j;
135733        for(i=0; i<nNew && aNew[i]<iCode; i++);
135734        for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
135735        aNew[i] = iCode;
135736        nNew++;
135737      }
135738    }
135739    p->aiException = aNew;
135740    p->nException = nNew;
135741  }
135742
135743  return SQLITE_OK;
135744}
135745
135746/*
135747** Return true if the p->aiException[] array contains the value iCode.
135748*/
135749static int unicodeIsException(unicode_tokenizer *p, int iCode){
135750  if( p->nException>0 ){
135751    int *a = p->aiException;
135752    int iLo = 0;
135753    int iHi = p->nException-1;
135754
135755    while( iHi>=iLo ){
135756      int iTest = (iHi + iLo) / 2;
135757      if( iCode==a[iTest] ){
135758        return 1;
135759      }else if( iCode>a[iTest] ){
135760        iLo = iTest+1;
135761      }else{
135762        iHi = iTest-1;
135763      }
135764    }
135765  }
135766
135767  return 0;
135768}
135769
135770/*
135771** Return true if, for the purposes of tokenization, codepoint iCode is
135772** considered a token character (not a separator).
135773*/
135774static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
135775  assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
135776  return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
135777}
135778
135779/*
135780** Create a new tokenizer instance.
135781*/
135782static int unicodeCreate(
135783  int nArg,                       /* Size of array argv[] */
135784  const char * const *azArg,      /* Tokenizer creation arguments */
135785  sqlite3_tokenizer **pp          /* OUT: New tokenizer handle */
135786){
135787  unicode_tokenizer *pNew;        /* New tokenizer object */
135788  int i;
135789  int rc = SQLITE_OK;
135790
135791  pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
135792  if( pNew==NULL ) return SQLITE_NOMEM;
135793  memset(pNew, 0, sizeof(unicode_tokenizer));
135794  pNew->bRemoveDiacritic = 1;
135795
135796  for(i=0; rc==SQLITE_OK && i<nArg; i++){
135797    const char *z = azArg[i];
135798    int n = strlen(z);
135799
135800    if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
135801      pNew->bRemoveDiacritic = 1;
135802    }
135803    else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
135804      pNew->bRemoveDiacritic = 0;
135805    }
135806    else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
135807      rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
135808    }
135809    else if( n>=11 && memcmp("separators=", z, 11)==0 ){
135810      rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
135811    }
135812    else{
135813      /* Unrecognized argument */
135814      rc  = SQLITE_ERROR;
135815    }
135816  }
135817
135818  if( rc!=SQLITE_OK ){
135819    unicodeDestroy((sqlite3_tokenizer *)pNew);
135820    pNew = 0;
135821  }
135822  *pp = (sqlite3_tokenizer *)pNew;
135823  return rc;
135824}
135825
135826/*
135827** Prepare to begin tokenizing a particular string.  The input
135828** string to be tokenized is pInput[0..nBytes-1].  A cursor
135829** used to incrementally tokenize this string is returned in
135830** *ppCursor.
135831*/
135832static int unicodeOpen(
135833  sqlite3_tokenizer *p,           /* The tokenizer */
135834  const char *aInput,             /* Input string */
135835  int nInput,                     /* Size of string aInput in bytes */
135836  sqlite3_tokenizer_cursor **pp   /* OUT: New cursor object */
135837){
135838  unicode_cursor *pCsr;
135839
135840  pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
135841  if( pCsr==0 ){
135842    return SQLITE_NOMEM;
135843  }
135844  memset(pCsr, 0, sizeof(unicode_cursor));
135845
135846  pCsr->aInput = (const unsigned char *)aInput;
135847  if( aInput==0 ){
135848    pCsr->nInput = 0;
135849  }else if( nInput<0 ){
135850    pCsr->nInput = (int)strlen(aInput);
135851  }else{
135852    pCsr->nInput = nInput;
135853  }
135854
135855  *pp = &pCsr->base;
135856  UNUSED_PARAMETER(p);
135857  return SQLITE_OK;
135858}
135859
135860/*
135861** Close a tokenization cursor previously opened by a call to
135862** simpleOpen() above.
135863*/
135864static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
135865  unicode_cursor *pCsr = (unicode_cursor *) pCursor;
135866  sqlite3_free(pCsr->zToken);
135867  sqlite3_free(pCsr);
135868  return SQLITE_OK;
135869}
135870
135871/*
135872** Extract the next token from a tokenization cursor.  The cursor must
135873** have been opened by a prior call to simpleOpen().
135874*/
135875static int unicodeNext(
135876  sqlite3_tokenizer_cursor *pC,   /* Cursor returned by simpleOpen */
135877  const char **paToken,           /* OUT: Token text */
135878  int *pnToken,                   /* OUT: Number of bytes at *paToken */
135879  int *piStart,                   /* OUT: Starting offset of token */
135880  int *piEnd,                     /* OUT: Ending offset of token */
135881  int *piPos                      /* OUT: Position integer of token */
135882){
135883  unicode_cursor *pCsr = (unicode_cursor *)pC;
135884  unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
135885  int iCode;
135886  char *zOut;
135887  const unsigned char *z = &pCsr->aInput[pCsr->iOff];
135888  const unsigned char *zStart = z;
135889  const unsigned char *zEnd;
135890  const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
135891
135892  /* Scan past any delimiter characters before the start of the next token.
135893  ** Return SQLITE_DONE early if this takes us all the way to the end of
135894  ** the input.  */
135895  while( z<zTerm ){
135896    READ_UTF8(z, zTerm, iCode);
135897    if( unicodeIsAlnum(p, iCode) ) break;
135898    zStart = z;
135899  }
135900  if( zStart>=zTerm ) return SQLITE_DONE;
135901
135902  zOut = pCsr->zToken;
135903  do {
135904    int iOut;
135905
135906    /* Grow the output buffer if required. */
135907    if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
135908      char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64);
135909      if( !zNew ) return SQLITE_NOMEM;
135910      zOut = &zNew[zOut - pCsr->zToken];
135911      pCsr->zToken = zNew;
135912      pCsr->nAlloc += 64;
135913    }
135914
135915    /* Write the folded case of the last character read to the output */
135916    zEnd = z;
135917    iOut = sqlite3FtsUnicodeFold(iCode, p->bRemoveDiacritic);
135918    if( iOut ){
135919      WRITE_UTF8(zOut, iOut);
135920    }
135921
135922    /* If the cursor is not at EOF, read the next character */
135923    if( z>=zTerm ) break;
135924    READ_UTF8(z, zTerm, iCode);
135925  }while( unicodeIsAlnum(p, iCode)
135926       || sqlite3FtsUnicodeIsdiacritic(iCode)
135927  );
135928
135929  /* Set the output variables and return. */
135930  pCsr->iOff = (z - pCsr->aInput);
135931  *paToken = pCsr->zToken;
135932  *pnToken = zOut - pCsr->zToken;
135933  *piStart = (zStart - pCsr->aInput);
135934  *piEnd = (zEnd - pCsr->aInput);
135935  *piPos = pCsr->iToken++;
135936  return SQLITE_OK;
135937}
135938
135939/*
135940** Set *ppModule to a pointer to the sqlite3_tokenizer_module
135941** structure for the unicode tokenizer.
135942*/
135943SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
135944  static const sqlite3_tokenizer_module module = {
135945    0,
135946    unicodeCreate,
135947    unicodeDestroy,
135948    unicodeOpen,
135949    unicodeClose,
135950    unicodeNext,
135951    0,
135952  };
135953  *ppModule = &module;
135954}
135955
135956#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
135957#endif /* ifndef SQLITE_ENABLE_FTS4_UNICODE61 */
135958
135959/************** End of fts3_unicode.c ****************************************/
135960/************** Begin file fts3_unicode2.c ***********************************/
135961/*
135962** 2012 May 25
135963**
135964** The author disclaims copyright to this source code.  In place of
135965** a legal notice, here is a blessing:
135966**
135967**    May you do good and not evil.
135968**    May you find forgiveness for yourself and forgive others.
135969**    May you share freely, never taking more than you give.
135970**
135971******************************************************************************
135972*/
135973
135974/*
135975** DO NOT EDIT THIS MACHINE GENERATED FILE.
135976*/
135977
135978#if defined(SQLITE_ENABLE_FTS4_UNICODE61)
135979#if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
135980
135981/* #include <assert.h> */
135982
135983/*
135984** Return true if the argument corresponds to a unicode codepoint
135985** classified as either a letter or a number. Otherwise false.
135986**
135987** The results are undefined if the value passed to this function
135988** is less than zero.
135989*/
135990SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
135991  /* Each unsigned integer in the following array corresponds to a contiguous
135992  ** range of unicode codepoints that are not either letters or numbers (i.e.
135993  ** codepoints for which this function should return 0).
135994  **
135995  ** The most significant 22 bits in each 32-bit value contain the first
135996  ** codepoint in the range. The least significant 10 bits are used to store
135997  ** the size of the range (always at least 1). In other words, the value
135998  ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
135999  ** C. It is not possible to represent a range larger than 1023 codepoints
136000  ** using this format.
136001  */
136002  const static unsigned int aEntry[] = {
136003    0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
136004    0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
136005    0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
136006    0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
136007    0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
136008    0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
136009    0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
136010    0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
136011    0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
136012    0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
136013    0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
136014    0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
136015    0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
136016    0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
136017    0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
136018    0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
136019    0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
136020    0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
136021    0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
136022    0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
136023    0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
136024    0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
136025    0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
136026    0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
136027    0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
136028    0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
136029    0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
136030    0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
136031    0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
136032    0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
136033    0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
136034    0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
136035    0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
136036    0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
136037    0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
136038    0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
136039    0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
136040    0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
136041    0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
136042    0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
136043    0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
136044    0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
136045    0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
136046    0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
136047    0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
136048    0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
136049    0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
136050    0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
136051    0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
136052    0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
136053    0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
136054    0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
136055    0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
136056    0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
136057    0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
136058    0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
136059    0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
136060    0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
136061    0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
136062    0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
136063    0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
136064    0x037FFC02, 0x03E3FC01, 0x03EC7801, 0x03ECA401, 0x03EEC810,
136065    0x03F4F802, 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023,
136066    0x03F95013, 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807,
136067    0x03FCEC06, 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405,
136068    0x04040003, 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E,
136069    0x040E7C01, 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01,
136070    0x04280403, 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01,
136071    0x04294009, 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016,
136072    0x04420003, 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004,
136073    0x04460003, 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004,
136074    0x05BD442E, 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5,
136075    0x07480046, 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01,
136076    0x075C5401, 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401,
136077    0x075EA401, 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064,
136078    0x07C2800F, 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F,
136079    0x07C4C03C, 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009,
136080    0x07C94002, 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014,
136081    0x07CE8025, 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001,
136082    0x07D108B6, 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018,
136083    0x07D7EC46, 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401,
136084    0x38008060, 0x380400F0, 0x3C000001, 0x3FFFF401, 0x40000001,
136085    0x43FFF401,
136086  };
136087  static const unsigned int aAscii[4] = {
136088    0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
136089  };
136090
136091  if( c<128 ){
136092    return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
136093  }else if( c<(1<<22) ){
136094    unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
136095    int iRes;
136096    int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
136097    int iLo = 0;
136098    while( iHi>=iLo ){
136099      int iTest = (iHi + iLo) / 2;
136100      if( key >= aEntry[iTest] ){
136101        iRes = iTest;
136102        iLo = iTest+1;
136103      }else{
136104        iHi = iTest-1;
136105      }
136106    }
136107    assert( aEntry[0]<key );
136108    assert( key>=aEntry[iRes] );
136109    return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
136110  }
136111  return 1;
136112}
136113
136114
136115/*
136116** If the argument is a codepoint corresponding to a lowercase letter
136117** in the ASCII range with a diacritic added, return the codepoint
136118** of the ASCII letter only. For example, if passed 235 - "LATIN
136119** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
136120** E"). The resuls of passing a codepoint that corresponds to an
136121** uppercase letter are undefined.
136122*/
136123static int remove_diacritic(int c){
136124  unsigned short aDia[] = {
136125        0,  1797,  1848,  1859,  1891,  1928,  1940,  1995,
136126     2024,  2040,  2060,  2110,  2168,  2206,  2264,  2286,
136127     2344,  2383,  2472,  2488,  2516,  2596,  2668,  2732,
136128     2782,  2842,  2894,  2954,  2984,  3000,  3028,  3336,
136129     3456,  3696,  3712,  3728,  3744,  3896,  3912,  3928,
136130     3968,  4008,  4040,  4106,  4138,  4170,  4202,  4234,
136131     4266,  4296,  4312,  4344,  4408,  4424,  4472,  4504,
136132     6148,  6198,  6264,  6280,  6360,  6429,  6505,  6529,
136133    61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
136134    61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
136135    62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
136136    62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
136137    62924, 63050, 63082, 63274, 63390,
136138  };
136139  char aChar[] = {
136140    '\0', 'a',  'c',  'e',  'i',  'n',  'o',  'u',  'y',  'y',  'a',  'c',
136141    'd',  'e',  'e',  'g',  'h',  'i',  'j',  'k',  'l',  'n',  'o',  'r',
136142    's',  't',  'u',  'u',  'w',  'y',  'z',  'o',  'u',  'a',  'i',  'o',
136143    'u',  'g',  'k',  'o',  'j',  'g',  'n',  'a',  'e',  'i',  'o',  'r',
136144    'u',  's',  't',  'h',  'a',  'e',  'o',  'y',  '\0', '\0', '\0', '\0',
136145    '\0', '\0', '\0', '\0', 'a',  'b',  'd',  'd',  'e',  'f',  'g',  'h',
136146    'h',  'i',  'k',  'l',  'l',  'm',  'n',  'p',  'r',  'r',  's',  't',
136147    'u',  'v',  'w',  'w',  'x',  'y',  'z',  'h',  't',  'w',  'y',  'a',
136148    'e',  'i',  'o',  'u',  'y',
136149  };
136150
136151  unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
136152  int iRes = 0;
136153  int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
136154  int iLo = 0;
136155  while( iHi>=iLo ){
136156    int iTest = (iHi + iLo) / 2;
136157    if( key >= aDia[iTest] ){
136158      iRes = iTest;
136159      iLo = iTest+1;
136160    }else{
136161      iHi = iTest-1;
136162    }
136163  }
136164  assert( key>=aDia[iRes] );
136165  return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
136166};
136167
136168
136169/*
136170** Return true if the argument interpreted as a unicode codepoint
136171** is a diacritical modifier character.
136172*/
136173SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
136174  unsigned int mask0 = 0x08029FDF;
136175  unsigned int mask1 = 0x000361F8;
136176  if( c<768 || c>817 ) return 0;
136177  return (c < 768+32) ?
136178      (mask0 & (1 << (c-768))) :
136179      (mask1 & (1 << (c-768-32)));
136180}
136181
136182
136183/*
136184** Interpret the argument as a unicode codepoint. If the codepoint
136185** is an upper case character that has a lower case equivalent,
136186** return the codepoint corresponding to the lower case version.
136187** Otherwise, return a copy of the argument.
136188**
136189** The results are undefined if the value passed to this function
136190** is less than zero.
136191*/
136192SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){
136193  /* Each entry in the following array defines a rule for folding a range
136194  ** of codepoints to lower case. The rule applies to a range of nRange
136195  ** codepoints starting at codepoint iCode.
136196  **
136197  ** If the least significant bit in flags is clear, then the rule applies
136198  ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
136199  ** need to be folded). Or, if it is set, then the rule only applies to
136200  ** every second codepoint in the range, starting with codepoint C.
136201  **
136202  ** The 7 most significant bits in flags are an index into the aiOff[]
136203  ** array. If a specific codepoint C does require folding, then its lower
136204  ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
136205  **
136206  ** The contents of this array are generated by parsing the CaseFolding.txt
136207  ** file distributed as part of the "Unicode Character Database". See
136208  ** http://www.unicode.org for details.
136209  */
136210  static const struct TableEntry {
136211    unsigned short iCode;
136212    unsigned char flags;
136213    unsigned char nRange;
136214  } aEntry[] = {
136215    {65, 14, 26},          {181, 64, 1},          {192, 14, 23},
136216    {216, 14, 7},          {256, 1, 48},          {306, 1, 6},
136217    {313, 1, 16},          {330, 1, 46},          {376, 116, 1},
136218    {377, 1, 6},           {383, 104, 1},         {385, 50, 1},
136219    {386, 1, 4},           {390, 44, 1},          {391, 0, 1},
136220    {393, 42, 2},          {395, 0, 1},           {398, 32, 1},
136221    {399, 38, 1},          {400, 40, 1},          {401, 0, 1},
136222    {403, 42, 1},          {404, 46, 1},          {406, 52, 1},
136223    {407, 48, 1},          {408, 0, 1},           {412, 52, 1},
136224    {413, 54, 1},          {415, 56, 1},          {416, 1, 6},
136225    {422, 60, 1},          {423, 0, 1},           {425, 60, 1},
136226    {428, 0, 1},           {430, 60, 1},          {431, 0, 1},
136227    {433, 58, 2},          {435, 1, 4},           {439, 62, 1},
136228    {440, 0, 1},           {444, 0, 1},           {452, 2, 1},
136229    {453, 0, 1},           {455, 2, 1},           {456, 0, 1},
136230    {458, 2, 1},           {459, 1, 18},          {478, 1, 18},
136231    {497, 2, 1},           {498, 1, 4},           {502, 122, 1},
136232    {503, 134, 1},         {504, 1, 40},          {544, 110, 1},
136233    {546, 1, 18},          {570, 70, 1},          {571, 0, 1},
136234    {573, 108, 1},         {574, 68, 1},          {577, 0, 1},
136235    {579, 106, 1},         {580, 28, 1},          {581, 30, 1},
136236    {582, 1, 10},          {837, 36, 1},          {880, 1, 4},
136237    {886, 0, 1},           {902, 18, 1},          {904, 16, 3},
136238    {908, 26, 1},          {910, 24, 2},          {913, 14, 17},
136239    {931, 14, 9},          {962, 0, 1},           {975, 4, 1},
136240    {976, 140, 1},         {977, 142, 1},         {981, 146, 1},
136241    {982, 144, 1},         {984, 1, 24},          {1008, 136, 1},
136242    {1009, 138, 1},        {1012, 130, 1},        {1013, 128, 1},
136243    {1015, 0, 1},          {1017, 152, 1},        {1018, 0, 1},
136244    {1021, 110, 3},        {1024, 34, 16},        {1040, 14, 32},
136245    {1120, 1, 34},         {1162, 1, 54},         {1216, 6, 1},
136246    {1217, 1, 14},         {1232, 1, 88},         {1329, 22, 38},
136247    {4256, 66, 38},        {4295, 66, 1},         {4301, 66, 1},
136248    {7680, 1, 150},        {7835, 132, 1},        {7838, 96, 1},
136249    {7840, 1, 96},         {7944, 150, 8},        {7960, 150, 6},
136250    {7976, 150, 8},        {7992, 150, 8},        {8008, 150, 6},
136251    {8025, 151, 8},        {8040, 150, 8},        {8072, 150, 8},
136252    {8088, 150, 8},        {8104, 150, 8},        {8120, 150, 2},
136253    {8122, 126, 2},        {8124, 148, 1},        {8126, 100, 1},
136254    {8136, 124, 4},        {8140, 148, 1},        {8152, 150, 2},
136255    {8154, 120, 2},        {8168, 150, 2},        {8170, 118, 2},
136256    {8172, 152, 1},        {8184, 112, 2},        {8186, 114, 2},
136257    {8188, 148, 1},        {8486, 98, 1},         {8490, 92, 1},
136258    {8491, 94, 1},         {8498, 12, 1},         {8544, 8, 16},
136259    {8579, 0, 1},          {9398, 10, 26},        {11264, 22, 47},
136260    {11360, 0, 1},         {11362, 88, 1},        {11363, 102, 1},
136261    {11364, 90, 1},        {11367, 1, 6},         {11373, 84, 1},
136262    {11374, 86, 1},        {11375, 80, 1},        {11376, 82, 1},
136263    {11378, 0, 1},         {11381, 0, 1},         {11390, 78, 2},
136264    {11392, 1, 100},       {11499, 1, 4},         {11506, 0, 1},
136265    {42560, 1, 46},        {42624, 1, 24},        {42786, 1, 14},
136266    {42802, 1, 62},        {42873, 1, 4},         {42877, 76, 1},
136267    {42878, 1, 10},        {42891, 0, 1},         {42893, 74, 1},
136268    {42896, 1, 4},         {42912, 1, 10},        {42922, 72, 1},
136269    {65313, 14, 26},
136270  };
136271  static const unsigned short aiOff[] = {
136272   1,     2,     8,     15,    16,    26,    28,    32,
136273   37,    38,    40,    48,    63,    64,    69,    71,
136274   79,    80,    116,   202,   203,   205,   206,   207,
136275   209,   210,   211,   213,   214,   217,   218,   219,
136276   775,   7264,  10792, 10795, 23228, 23256, 30204, 54721,
136277   54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
136278   57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
136279   65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
136280   65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
136281   65514, 65521, 65527, 65528, 65529,
136282  };
136283
136284  int ret = c;
136285
136286  assert( c>=0 );
136287  assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
136288
136289  if( c<128 ){
136290    if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
136291  }else if( c<65536 ){
136292    int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
136293    int iLo = 0;
136294    int iRes = -1;
136295
136296    while( iHi>=iLo ){
136297      int iTest = (iHi + iLo) / 2;
136298      int cmp = (c - aEntry[iTest].iCode);
136299      if( cmp>=0 ){
136300        iRes = iTest;
136301        iLo = iTest+1;
136302      }else{
136303        iHi = iTest-1;
136304      }
136305    }
136306    assert( iRes<0 || c>=aEntry[iRes].iCode );
136307
136308    if( iRes>=0 ){
136309      const struct TableEntry *p = &aEntry[iRes];
136310      if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
136311        ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
136312        assert( ret>0 );
136313      }
136314    }
136315
136316    if( bRemoveDiacritic ) ret = remove_diacritic(ret);
136317  }
136318
136319  else if( c>=66560 && c<66600 ){
136320    ret = c + 40;
136321  }
136322
136323  return ret;
136324}
136325#endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
136326#endif /* !defined(SQLITE_ENABLE_FTS4_UNICODE61) */
136327
136328/************** End of fts3_unicode2.c ***************************************/
136329/************** Begin file rtree.c *******************************************/
136330/*
136331** 2001 September 15
136332**
136333** The author disclaims copyright to this source code.  In place of
136334** a legal notice, here is a blessing:
136335**
136336**    May you do good and not evil.
136337**    May you find forgiveness for yourself and forgive others.
136338**    May you share freely, never taking more than you give.
136339**
136340*************************************************************************
136341** This file contains code for implementations of the r-tree and r*-tree
136342** algorithms packaged as an SQLite virtual table module.
136343*/
136344
136345/*
136346** Database Format of R-Tree Tables
136347** --------------------------------
136348**
136349** The data structure for a single virtual r-tree table is stored in three
136350** native SQLite tables declared as follows. In each case, the '%' character
136351** in the table name is replaced with the user-supplied name of the r-tree
136352** table.
136353**
136354**   CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
136355**   CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
136356**   CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
136357**
136358** The data for each node of the r-tree structure is stored in the %_node
136359** table. For each node that is not the root node of the r-tree, there is
136360** an entry in the %_parent table associating the node with its parent.
136361** And for each row of data in the table, there is an entry in the %_rowid
136362** table that maps from the entries rowid to the id of the node that it
136363** is stored on.
136364**
136365** The root node of an r-tree always exists, even if the r-tree table is
136366** empty. The nodeno of the root node is always 1. All other nodes in the
136367** table must be the same size as the root node. The content of each node
136368** is formatted as follows:
136369**
136370**   1. If the node is the root node (node 1), then the first 2 bytes
136371**      of the node contain the tree depth as a big-endian integer.
136372**      For non-root nodes, the first 2 bytes are left unused.
136373**
136374**   2. The next 2 bytes contain the number of entries currently
136375**      stored in the node.
136376**
136377**   3. The remainder of the node contains the node entries. Each entry
136378**      consists of a single 8-byte integer followed by an even number
136379**      of 4-byte coordinates. For leaf nodes the integer is the rowid
136380**      of a record. For internal nodes it is the node number of a
136381**      child page.
136382*/
136383
136384#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
136385
136386/*
136387** This file contains an implementation of a couple of different variants
136388** of the r-tree algorithm. See the README file for further details. The
136389** same data-structure is used for all, but the algorithms for insert and
136390** delete operations vary. The variants used are selected at compile time
136391** by defining the following symbols:
136392*/
136393
136394/* Either, both or none of the following may be set to activate
136395** r*tree variant algorithms.
136396*/
136397#define VARIANT_RSTARTREE_CHOOSESUBTREE 0
136398#define VARIANT_RSTARTREE_REINSERT      1
136399
136400/*
136401** Exactly one of the following must be set to 1.
136402*/
136403#define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
136404#define VARIANT_GUTTMAN_LINEAR_SPLIT    0
136405#define VARIANT_RSTARTREE_SPLIT         1
136406
136407#define VARIANT_GUTTMAN_SPLIT \
136408        (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
136409
136410#if VARIANT_GUTTMAN_QUADRATIC_SPLIT
136411  #define PickNext QuadraticPickNext
136412  #define PickSeeds QuadraticPickSeeds
136413  #define AssignCells splitNodeGuttman
136414#endif
136415#if VARIANT_GUTTMAN_LINEAR_SPLIT
136416  #define PickNext LinearPickNext
136417  #define PickSeeds LinearPickSeeds
136418  #define AssignCells splitNodeGuttman
136419#endif
136420#if VARIANT_RSTARTREE_SPLIT
136421  #define AssignCells splitNodeStartree
136422#endif
136423
136424#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
136425# define NDEBUG 1
136426#endif
136427
136428#ifndef SQLITE_CORE
136429  SQLITE_EXTENSION_INIT1
136430#else
136431#endif
136432
136433/* #include <string.h> */
136434/* #include <assert.h> */
136435
136436#ifndef SQLITE_AMALGAMATION
136437#include "sqlite3rtree.h"
136438typedef sqlite3_int64 i64;
136439typedef unsigned char u8;
136440typedef unsigned int u32;
136441#endif
136442
136443/*  The following macro is used to suppress compiler warnings.
136444*/
136445#ifndef UNUSED_PARAMETER
136446# define UNUSED_PARAMETER(x) (void)(x)
136447#endif
136448
136449typedef struct Rtree Rtree;
136450typedef struct RtreeCursor RtreeCursor;
136451typedef struct RtreeNode RtreeNode;
136452typedef struct RtreeCell RtreeCell;
136453typedef struct RtreeConstraint RtreeConstraint;
136454typedef struct RtreeMatchArg RtreeMatchArg;
136455typedef struct RtreeGeomCallback RtreeGeomCallback;
136456typedef union RtreeCoord RtreeCoord;
136457
136458/* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
136459#define RTREE_MAX_DIMENSIONS 5
136460
136461/* Size of hash table Rtree.aHash. This hash table is not expected to
136462** ever contain very many entries, so a fixed number of buckets is
136463** used.
136464*/
136465#define HASHSIZE 128
136466
136467/*
136468** An rtree virtual-table object.
136469*/
136470struct Rtree {
136471  sqlite3_vtab base;
136472  sqlite3 *db;                /* Host database connection */
136473  int iNodeSize;              /* Size in bytes of each node in the node table */
136474  int nDim;                   /* Number of dimensions */
136475  int nBytesPerCell;          /* Bytes consumed per cell */
136476  int iDepth;                 /* Current depth of the r-tree structure */
136477  char *zDb;                  /* Name of database containing r-tree table */
136478  char *zName;                /* Name of r-tree table */
136479  RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
136480  int nBusy;                  /* Current number of users of this structure */
136481
136482  /* List of nodes removed during a CondenseTree operation. List is
136483  ** linked together via the pointer normally used for hash chains -
136484  ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
136485  ** headed by the node (leaf nodes have RtreeNode.iNode==0).
136486  */
136487  RtreeNode *pDeleted;
136488  int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
136489
136490  /* Statements to read/write/delete a record from xxx_node */
136491  sqlite3_stmt *pReadNode;
136492  sqlite3_stmt *pWriteNode;
136493  sqlite3_stmt *pDeleteNode;
136494
136495  /* Statements to read/write/delete a record from xxx_rowid */
136496  sqlite3_stmt *pReadRowid;
136497  sqlite3_stmt *pWriteRowid;
136498  sqlite3_stmt *pDeleteRowid;
136499
136500  /* Statements to read/write/delete a record from xxx_parent */
136501  sqlite3_stmt *pReadParent;
136502  sqlite3_stmt *pWriteParent;
136503  sqlite3_stmt *pDeleteParent;
136504
136505  int eCoordType;
136506};
136507
136508/* Possible values for eCoordType: */
136509#define RTREE_COORD_REAL32 0
136510#define RTREE_COORD_INT32  1
136511
136512/*
136513** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
136514** only deal with integer coordinates.  No floating point operations
136515** will be done.
136516*/
136517#ifdef SQLITE_RTREE_INT_ONLY
136518  typedef sqlite3_int64 RtreeDValue;       /* High accuracy coordinate */
136519  typedef int RtreeValue;                  /* Low accuracy coordinate */
136520#else
136521  typedef double RtreeDValue;              /* High accuracy coordinate */
136522  typedef float RtreeValue;                /* Low accuracy coordinate */
136523#endif
136524
136525/*
136526** The minimum number of cells allowed for a node is a third of the
136527** maximum. In Gutman's notation:
136528**
136529**     m = M/3
136530**
136531** If an R*-tree "Reinsert" operation is required, the same number of
136532** cells are removed from the overfull node and reinserted into the tree.
136533*/
136534#define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
136535#define RTREE_REINSERT(p) RTREE_MINCELLS(p)
136536#define RTREE_MAXCELLS 51
136537
136538/*
136539** The smallest possible node-size is (512-64)==448 bytes. And the largest
136540** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
136541** Therefore all non-root nodes must contain at least 3 entries. Since
136542** 2^40 is greater than 2^64, an r-tree structure always has a depth of
136543** 40 or less.
136544*/
136545#define RTREE_MAX_DEPTH 40
136546
136547/*
136548** An rtree cursor object.
136549*/
136550struct RtreeCursor {
136551  sqlite3_vtab_cursor base;
136552  RtreeNode *pNode;                 /* Node cursor is currently pointing at */
136553  int iCell;                        /* Index of current cell in pNode */
136554  int iStrategy;                    /* Copy of idxNum search parameter */
136555  int nConstraint;                  /* Number of entries in aConstraint */
136556  RtreeConstraint *aConstraint;     /* Search constraints. */
136557};
136558
136559union RtreeCoord {
136560  RtreeValue f;
136561  int i;
136562};
136563
136564/*
136565** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
136566** formatted as a RtreeDValue (double or int64). This macro assumes that local
136567** variable pRtree points to the Rtree structure associated with the
136568** RtreeCoord.
136569*/
136570#ifdef SQLITE_RTREE_INT_ONLY
136571# define DCOORD(coord) ((RtreeDValue)coord.i)
136572#else
136573# define DCOORD(coord) (                           \
136574    (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
136575      ((double)coord.f) :                           \
136576      ((double)coord.i)                             \
136577  )
136578#endif
136579
136580/*
136581** A search constraint.
136582*/
136583struct RtreeConstraint {
136584  int iCoord;                     /* Index of constrained coordinate */
136585  int op;                         /* Constraining operation */
136586  RtreeDValue rValue;             /* Constraint value. */
136587  int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
136588  sqlite3_rtree_geometry *pGeom;  /* Constraint callback argument for a MATCH */
136589};
136590
136591/* Possible values for RtreeConstraint.op */
136592#define RTREE_EQ    0x41
136593#define RTREE_LE    0x42
136594#define RTREE_LT    0x43
136595#define RTREE_GE    0x44
136596#define RTREE_GT    0x45
136597#define RTREE_MATCH 0x46
136598
136599/*
136600** An rtree structure node.
136601*/
136602struct RtreeNode {
136603  RtreeNode *pParent;               /* Parent node */
136604  i64 iNode;
136605  int nRef;
136606  int isDirty;
136607  u8 *zData;
136608  RtreeNode *pNext;                 /* Next node in this hash chain */
136609};
136610#define NCELL(pNode) readInt16(&(pNode)->zData[2])
136611
136612/*
136613** Structure to store a deserialized rtree record.
136614*/
136615struct RtreeCell {
136616  i64 iRowid;
136617  RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
136618};
136619
136620
136621/*
136622** Value for the first field of every RtreeMatchArg object. The MATCH
136623** operator tests that the first field of a blob operand matches this
136624** value to avoid operating on invalid blobs (which could cause a segfault).
136625*/
136626#define RTREE_GEOMETRY_MAGIC 0x891245AB
136627
136628/*
136629** An instance of this structure must be supplied as a blob argument to
136630** the right-hand-side of an SQL MATCH operator used to constrain an
136631** r-tree query.
136632*/
136633struct RtreeMatchArg {
136634  u32 magic;                      /* Always RTREE_GEOMETRY_MAGIC */
136635  int (*xGeom)(sqlite3_rtree_geometry *, int, RtreeDValue*, int *);
136636  void *pContext;
136637  int nParam;
136638  RtreeDValue aParam[1];
136639};
136640
136641/*
136642** When a geometry callback is created (see sqlite3_rtree_geometry_callback),
136643** a single instance of the following structure is allocated. It is used
136644** as the context for the user-function created by by s_r_g_c(). The object
136645** is eventually deleted by the destructor mechanism provided by
136646** sqlite3_create_function_v2() (which is called by s_r_g_c() to create
136647** the geometry callback function).
136648*/
136649struct RtreeGeomCallback {
136650  int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
136651  void *pContext;
136652};
136653
136654#ifndef MAX
136655# define MAX(x,y) ((x) < (y) ? (y) : (x))
136656#endif
136657#ifndef MIN
136658# define MIN(x,y) ((x) > (y) ? (y) : (x))
136659#endif
136660
136661/*
136662** Functions to deserialize a 16 bit integer, 32 bit real number and
136663** 64 bit integer. The deserialized value is returned.
136664*/
136665static int readInt16(u8 *p){
136666  return (p[0]<<8) + p[1];
136667}
136668static void readCoord(u8 *p, RtreeCoord *pCoord){
136669  u32 i = (
136670    (((u32)p[0]) << 24) +
136671    (((u32)p[1]) << 16) +
136672    (((u32)p[2]) <<  8) +
136673    (((u32)p[3]) <<  0)
136674  );
136675  *(u32 *)pCoord = i;
136676}
136677static i64 readInt64(u8 *p){
136678  return (
136679    (((i64)p[0]) << 56) +
136680    (((i64)p[1]) << 48) +
136681    (((i64)p[2]) << 40) +
136682    (((i64)p[3]) << 32) +
136683    (((i64)p[4]) << 24) +
136684    (((i64)p[5]) << 16) +
136685    (((i64)p[6]) <<  8) +
136686    (((i64)p[7]) <<  0)
136687  );
136688}
136689
136690/*
136691** Functions to serialize a 16 bit integer, 32 bit real number and
136692** 64 bit integer. The value returned is the number of bytes written
136693** to the argument buffer (always 2, 4 and 8 respectively).
136694*/
136695static int writeInt16(u8 *p, int i){
136696  p[0] = (i>> 8)&0xFF;
136697  p[1] = (i>> 0)&0xFF;
136698  return 2;
136699}
136700static int writeCoord(u8 *p, RtreeCoord *pCoord){
136701  u32 i;
136702  assert( sizeof(RtreeCoord)==4 );
136703  assert( sizeof(u32)==4 );
136704  i = *(u32 *)pCoord;
136705  p[0] = (i>>24)&0xFF;
136706  p[1] = (i>>16)&0xFF;
136707  p[2] = (i>> 8)&0xFF;
136708  p[3] = (i>> 0)&0xFF;
136709  return 4;
136710}
136711static int writeInt64(u8 *p, i64 i){
136712  p[0] = (i>>56)&0xFF;
136713  p[1] = (i>>48)&0xFF;
136714  p[2] = (i>>40)&0xFF;
136715  p[3] = (i>>32)&0xFF;
136716  p[4] = (i>>24)&0xFF;
136717  p[5] = (i>>16)&0xFF;
136718  p[6] = (i>> 8)&0xFF;
136719  p[7] = (i>> 0)&0xFF;
136720  return 8;
136721}
136722
136723/*
136724** Increment the reference count of node p.
136725*/
136726static void nodeReference(RtreeNode *p){
136727  if( p ){
136728    p->nRef++;
136729  }
136730}
136731
136732/*
136733** Clear the content of node p (set all bytes to 0x00).
136734*/
136735static void nodeZero(Rtree *pRtree, RtreeNode *p){
136736  memset(&p->zData[2], 0, pRtree->iNodeSize-2);
136737  p->isDirty = 1;
136738}
136739
136740/*
136741** Given a node number iNode, return the corresponding key to use
136742** in the Rtree.aHash table.
136743*/
136744static int nodeHash(i64 iNode){
136745  return (
136746    (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^
136747    (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
136748  ) % HASHSIZE;
136749}
136750
136751/*
136752** Search the node hash table for node iNode. If found, return a pointer
136753** to it. Otherwise, return 0.
136754*/
136755static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
136756  RtreeNode *p;
136757  for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
136758  return p;
136759}
136760
136761/*
136762** Add node pNode to the node hash table.
136763*/
136764static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
136765  int iHash;
136766  assert( pNode->pNext==0 );
136767  iHash = nodeHash(pNode->iNode);
136768  pNode->pNext = pRtree->aHash[iHash];
136769  pRtree->aHash[iHash] = pNode;
136770}
136771
136772/*
136773** Remove node pNode from the node hash table.
136774*/
136775static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
136776  RtreeNode **pp;
136777  if( pNode->iNode!=0 ){
136778    pp = &pRtree->aHash[nodeHash(pNode->iNode)];
136779    for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
136780    *pp = pNode->pNext;
136781    pNode->pNext = 0;
136782  }
136783}
136784
136785/*
136786** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
136787** indicating that node has not yet been assigned a node number. It is
136788** assigned a node number when nodeWrite() is called to write the
136789** node contents out to the database.
136790*/
136791static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
136792  RtreeNode *pNode;
136793  pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
136794  if( pNode ){
136795    memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
136796    pNode->zData = (u8 *)&pNode[1];
136797    pNode->nRef = 1;
136798    pNode->pParent = pParent;
136799    pNode->isDirty = 1;
136800    nodeReference(pParent);
136801  }
136802  return pNode;
136803}
136804
136805/*
136806** Obtain a reference to an r-tree node.
136807*/
136808static int
136809nodeAcquire(
136810  Rtree *pRtree,             /* R-tree structure */
136811  i64 iNode,                 /* Node number to load */
136812  RtreeNode *pParent,        /* Either the parent node or NULL */
136813  RtreeNode **ppNode         /* OUT: Acquired node */
136814){
136815  int rc;
136816  int rc2 = SQLITE_OK;
136817  RtreeNode *pNode;
136818
136819  /* Check if the requested node is already in the hash table. If so,
136820  ** increase its reference count and return it.
136821  */
136822  if( (pNode = nodeHashLookup(pRtree, iNode)) ){
136823    assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
136824    if( pParent && !pNode->pParent ){
136825      nodeReference(pParent);
136826      pNode->pParent = pParent;
136827    }
136828    pNode->nRef++;
136829    *ppNode = pNode;
136830    return SQLITE_OK;
136831  }
136832
136833  sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
136834  rc = sqlite3_step(pRtree->pReadNode);
136835  if( rc==SQLITE_ROW ){
136836    const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
136837    if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
136838      pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
136839      if( !pNode ){
136840        rc2 = SQLITE_NOMEM;
136841      }else{
136842        pNode->pParent = pParent;
136843        pNode->zData = (u8 *)&pNode[1];
136844        pNode->nRef = 1;
136845        pNode->iNode = iNode;
136846        pNode->isDirty = 0;
136847        pNode->pNext = 0;
136848        memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
136849        nodeReference(pParent);
136850      }
136851    }
136852  }
136853  rc = sqlite3_reset(pRtree->pReadNode);
136854  if( rc==SQLITE_OK ) rc = rc2;
136855
136856  /* If the root node was just loaded, set pRtree->iDepth to the height
136857  ** of the r-tree structure. A height of zero means all data is stored on
136858  ** the root node. A height of one means the children of the root node
136859  ** are the leaves, and so on. If the depth as specified on the root node
136860  ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
136861  */
136862  if( pNode && iNode==1 ){
136863    pRtree->iDepth = readInt16(pNode->zData);
136864    if( pRtree->iDepth>RTREE_MAX_DEPTH ){
136865      rc = SQLITE_CORRUPT_VTAB;
136866    }
136867  }
136868
136869  /* If no error has occurred so far, check if the "number of entries"
136870  ** field on the node is too large. If so, set the return code to
136871  ** SQLITE_CORRUPT_VTAB.
136872  */
136873  if( pNode && rc==SQLITE_OK ){
136874    if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
136875      rc = SQLITE_CORRUPT_VTAB;
136876    }
136877  }
136878
136879  if( rc==SQLITE_OK ){
136880    if( pNode!=0 ){
136881      nodeHashInsert(pRtree, pNode);
136882    }else{
136883      rc = SQLITE_CORRUPT_VTAB;
136884    }
136885    *ppNode = pNode;
136886  }else{
136887    sqlite3_free(pNode);
136888    *ppNode = 0;
136889  }
136890
136891  return rc;
136892}
136893
136894/*
136895** Overwrite cell iCell of node pNode with the contents of pCell.
136896*/
136897static void nodeOverwriteCell(
136898  Rtree *pRtree,
136899  RtreeNode *pNode,
136900  RtreeCell *pCell,
136901  int iCell
136902){
136903  int ii;
136904  u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
136905  p += writeInt64(p, pCell->iRowid);
136906  for(ii=0; ii<(pRtree->nDim*2); ii++){
136907    p += writeCoord(p, &pCell->aCoord[ii]);
136908  }
136909  pNode->isDirty = 1;
136910}
136911
136912/*
136913** Remove cell the cell with index iCell from node pNode.
136914*/
136915static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
136916  u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
136917  u8 *pSrc = &pDst[pRtree->nBytesPerCell];
136918  int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
136919  memmove(pDst, pSrc, nByte);
136920  writeInt16(&pNode->zData[2], NCELL(pNode)-1);
136921  pNode->isDirty = 1;
136922}
136923
136924/*
136925** Insert the contents of cell pCell into node pNode. If the insert
136926** is successful, return SQLITE_OK.
136927**
136928** If there is not enough free space in pNode, return SQLITE_FULL.
136929*/
136930static int
136931nodeInsertCell(
136932  Rtree *pRtree,
136933  RtreeNode *pNode,
136934  RtreeCell *pCell
136935){
136936  int nCell;                    /* Current number of cells in pNode */
136937  int nMaxCell;                 /* Maximum number of cells for pNode */
136938
136939  nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
136940  nCell = NCELL(pNode);
136941
136942  assert( nCell<=nMaxCell );
136943  if( nCell<nMaxCell ){
136944    nodeOverwriteCell(pRtree, pNode, pCell, nCell);
136945    writeInt16(&pNode->zData[2], nCell+1);
136946    pNode->isDirty = 1;
136947  }
136948
136949  return (nCell==nMaxCell);
136950}
136951
136952/*
136953** If the node is dirty, write it out to the database.
136954*/
136955static int
136956nodeWrite(Rtree *pRtree, RtreeNode *pNode){
136957  int rc = SQLITE_OK;
136958  if( pNode->isDirty ){
136959    sqlite3_stmt *p = pRtree->pWriteNode;
136960    if( pNode->iNode ){
136961      sqlite3_bind_int64(p, 1, pNode->iNode);
136962    }else{
136963      sqlite3_bind_null(p, 1);
136964    }
136965    sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
136966    sqlite3_step(p);
136967    pNode->isDirty = 0;
136968    rc = sqlite3_reset(p);
136969    if( pNode->iNode==0 && rc==SQLITE_OK ){
136970      pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
136971      nodeHashInsert(pRtree, pNode);
136972    }
136973  }
136974  return rc;
136975}
136976
136977/*
136978** Release a reference to a node. If the node is dirty and the reference
136979** count drops to zero, the node data is written to the database.
136980*/
136981static int
136982nodeRelease(Rtree *pRtree, RtreeNode *pNode){
136983  int rc = SQLITE_OK;
136984  if( pNode ){
136985    assert( pNode->nRef>0 );
136986    pNode->nRef--;
136987    if( pNode->nRef==0 ){
136988      if( pNode->iNode==1 ){
136989        pRtree->iDepth = -1;
136990      }
136991      if( pNode->pParent ){
136992        rc = nodeRelease(pRtree, pNode->pParent);
136993      }
136994      if( rc==SQLITE_OK ){
136995        rc = nodeWrite(pRtree, pNode);
136996      }
136997      nodeHashDelete(pRtree, pNode);
136998      sqlite3_free(pNode);
136999    }
137000  }
137001  return rc;
137002}
137003
137004/*
137005** Return the 64-bit integer value associated with cell iCell of
137006** node pNode. If pNode is a leaf node, this is a rowid. If it is
137007** an internal node, then the 64-bit integer is a child page number.
137008*/
137009static i64 nodeGetRowid(
137010  Rtree *pRtree,
137011  RtreeNode *pNode,
137012  int iCell
137013){
137014  assert( iCell<NCELL(pNode) );
137015  return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
137016}
137017
137018/*
137019** Return coordinate iCoord from cell iCell in node pNode.
137020*/
137021static void nodeGetCoord(
137022  Rtree *pRtree,
137023  RtreeNode *pNode,
137024  int iCell,
137025  int iCoord,
137026  RtreeCoord *pCoord           /* Space to write result to */
137027){
137028  readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
137029}
137030
137031/*
137032** Deserialize cell iCell of node pNode. Populate the structure pointed
137033** to by pCell with the results.
137034*/
137035static void nodeGetCell(
137036  Rtree *pRtree,
137037  RtreeNode *pNode,
137038  int iCell,
137039  RtreeCell *pCell
137040){
137041  int ii;
137042  pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
137043  for(ii=0; ii<pRtree->nDim*2; ii++){
137044    nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
137045  }
137046}
137047
137048
137049/* Forward declaration for the function that does the work of
137050** the virtual table module xCreate() and xConnect() methods.
137051*/
137052static int rtreeInit(
137053  sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
137054);
137055
137056/*
137057** Rtree virtual table module xCreate method.
137058*/
137059static int rtreeCreate(
137060  sqlite3 *db,
137061  void *pAux,
137062  int argc, const char *const*argv,
137063  sqlite3_vtab **ppVtab,
137064  char **pzErr
137065){
137066  return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
137067}
137068
137069/*
137070** Rtree virtual table module xConnect method.
137071*/
137072static int rtreeConnect(
137073  sqlite3 *db,
137074  void *pAux,
137075  int argc, const char *const*argv,
137076  sqlite3_vtab **ppVtab,
137077  char **pzErr
137078){
137079  return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
137080}
137081
137082/*
137083** Increment the r-tree reference count.
137084*/
137085static void rtreeReference(Rtree *pRtree){
137086  pRtree->nBusy++;
137087}
137088
137089/*
137090** Decrement the r-tree reference count. When the reference count reaches
137091** zero the structure is deleted.
137092*/
137093static void rtreeRelease(Rtree *pRtree){
137094  pRtree->nBusy--;
137095  if( pRtree->nBusy==0 ){
137096    sqlite3_finalize(pRtree->pReadNode);
137097    sqlite3_finalize(pRtree->pWriteNode);
137098    sqlite3_finalize(pRtree->pDeleteNode);
137099    sqlite3_finalize(pRtree->pReadRowid);
137100    sqlite3_finalize(pRtree->pWriteRowid);
137101    sqlite3_finalize(pRtree->pDeleteRowid);
137102    sqlite3_finalize(pRtree->pReadParent);
137103    sqlite3_finalize(pRtree->pWriteParent);
137104    sqlite3_finalize(pRtree->pDeleteParent);
137105    sqlite3_free(pRtree);
137106  }
137107}
137108
137109/*
137110** Rtree virtual table module xDisconnect method.
137111*/
137112static int rtreeDisconnect(sqlite3_vtab *pVtab){
137113  rtreeRelease((Rtree *)pVtab);
137114  return SQLITE_OK;
137115}
137116
137117/*
137118** Rtree virtual table module xDestroy method.
137119*/
137120static int rtreeDestroy(sqlite3_vtab *pVtab){
137121  Rtree *pRtree = (Rtree *)pVtab;
137122  int rc;
137123  char *zCreate = sqlite3_mprintf(
137124    "DROP TABLE '%q'.'%q_node';"
137125    "DROP TABLE '%q'.'%q_rowid';"
137126    "DROP TABLE '%q'.'%q_parent';",
137127    pRtree->zDb, pRtree->zName,
137128    pRtree->zDb, pRtree->zName,
137129    pRtree->zDb, pRtree->zName
137130  );
137131  if( !zCreate ){
137132    rc = SQLITE_NOMEM;
137133  }else{
137134    rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
137135    sqlite3_free(zCreate);
137136  }
137137  if( rc==SQLITE_OK ){
137138    rtreeRelease(pRtree);
137139  }
137140
137141  return rc;
137142}
137143
137144/*
137145** Rtree virtual table module xOpen method.
137146*/
137147static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
137148  int rc = SQLITE_NOMEM;
137149  RtreeCursor *pCsr;
137150
137151  pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
137152  if( pCsr ){
137153    memset(pCsr, 0, sizeof(RtreeCursor));
137154    pCsr->base.pVtab = pVTab;
137155    rc = SQLITE_OK;
137156  }
137157  *ppCursor = (sqlite3_vtab_cursor *)pCsr;
137158
137159  return rc;
137160}
137161
137162
137163/*
137164** Free the RtreeCursor.aConstraint[] array and its contents.
137165*/
137166static void freeCursorConstraints(RtreeCursor *pCsr){
137167  if( pCsr->aConstraint ){
137168    int i;                        /* Used to iterate through constraint array */
137169    for(i=0; i<pCsr->nConstraint; i++){
137170      sqlite3_rtree_geometry *pGeom = pCsr->aConstraint[i].pGeom;
137171      if( pGeom ){
137172        if( pGeom->xDelUser ) pGeom->xDelUser(pGeom->pUser);
137173        sqlite3_free(pGeom);
137174      }
137175    }
137176    sqlite3_free(pCsr->aConstraint);
137177    pCsr->aConstraint = 0;
137178  }
137179}
137180
137181/*
137182** Rtree virtual table module xClose method.
137183*/
137184static int rtreeClose(sqlite3_vtab_cursor *cur){
137185  Rtree *pRtree = (Rtree *)(cur->pVtab);
137186  int rc;
137187  RtreeCursor *pCsr = (RtreeCursor *)cur;
137188  freeCursorConstraints(pCsr);
137189  rc = nodeRelease(pRtree, pCsr->pNode);
137190  sqlite3_free(pCsr);
137191  return rc;
137192}
137193
137194/*
137195** Rtree virtual table module xEof method.
137196**
137197** Return non-zero if the cursor does not currently point to a valid
137198** record (i.e if the scan has finished), or zero otherwise.
137199*/
137200static int rtreeEof(sqlite3_vtab_cursor *cur){
137201  RtreeCursor *pCsr = (RtreeCursor *)cur;
137202  return (pCsr->pNode==0);
137203}
137204
137205/*
137206** The r-tree constraint passed as the second argument to this function is
137207** guaranteed to be a MATCH constraint.
137208*/
137209static int testRtreeGeom(
137210  Rtree *pRtree,                  /* R-Tree object */
137211  RtreeConstraint *pConstraint,   /* MATCH constraint to test */
137212  RtreeCell *pCell,               /* Cell to test */
137213  int *pbRes                      /* OUT: Test result */
137214){
137215  int i;
137216  RtreeDValue aCoord[RTREE_MAX_DIMENSIONS*2];
137217  int nCoord = pRtree->nDim*2;
137218
137219  assert( pConstraint->op==RTREE_MATCH );
137220  assert( pConstraint->pGeom );
137221
137222  for(i=0; i<nCoord; i++){
137223    aCoord[i] = DCOORD(pCell->aCoord[i]);
137224  }
137225  return pConstraint->xGeom(pConstraint->pGeom, nCoord, aCoord, pbRes);
137226}
137227
137228/*
137229** Cursor pCursor currently points to a cell in a non-leaf page.
137230** Set *pbEof to true if the sub-tree headed by the cell is filtered
137231** (excluded) by the constraints in the pCursor->aConstraint[]
137232** array, or false otherwise.
137233**
137234** Return SQLITE_OK if successful or an SQLite error code if an error
137235** occurs within a geometry callback.
137236*/
137237static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
137238  RtreeCell cell;
137239  int ii;
137240  int bRes = 0;
137241  int rc = SQLITE_OK;
137242
137243  nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
137244  for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
137245    RtreeConstraint *p = &pCursor->aConstraint[ii];
137246    RtreeDValue cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
137247    RtreeDValue cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
137248
137249    assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
137250        || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
137251    );
137252
137253    switch( p->op ){
137254      case RTREE_LE: case RTREE_LT:
137255        bRes = p->rValue<cell_min;
137256        break;
137257
137258      case RTREE_GE: case RTREE_GT:
137259        bRes = p->rValue>cell_max;
137260        break;
137261
137262      case RTREE_EQ:
137263        bRes = (p->rValue>cell_max || p->rValue<cell_min);
137264        break;
137265
137266      default: {
137267        assert( p->op==RTREE_MATCH );
137268        rc = testRtreeGeom(pRtree, p, &cell, &bRes);
137269        bRes = !bRes;
137270        break;
137271      }
137272    }
137273  }
137274
137275  *pbEof = bRes;
137276  return rc;
137277}
137278
137279/*
137280** Test if the cell that cursor pCursor currently points to
137281** would be filtered (excluded) by the constraints in the
137282** pCursor->aConstraint[] array. If so, set *pbEof to true before
137283** returning. If the cell is not filtered (excluded) by the constraints,
137284** set pbEof to zero.
137285**
137286** Return SQLITE_OK if successful or an SQLite error code if an error
137287** occurs within a geometry callback.
137288**
137289** This function assumes that the cell is part of a leaf node.
137290*/
137291static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
137292  RtreeCell cell;
137293  int ii;
137294  *pbEof = 0;
137295
137296  nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
137297  for(ii=0; ii<pCursor->nConstraint; ii++){
137298    RtreeConstraint *p = &pCursor->aConstraint[ii];
137299    RtreeDValue coord = DCOORD(cell.aCoord[p->iCoord]);
137300    int res;
137301    assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
137302        || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
137303    );
137304    switch( p->op ){
137305      case RTREE_LE: res = (coord<=p->rValue); break;
137306      case RTREE_LT: res = (coord<p->rValue);  break;
137307      case RTREE_GE: res = (coord>=p->rValue); break;
137308      case RTREE_GT: res = (coord>p->rValue);  break;
137309      case RTREE_EQ: res = (coord==p->rValue); break;
137310      default: {
137311        int rc;
137312        assert( p->op==RTREE_MATCH );
137313        rc = testRtreeGeom(pRtree, p, &cell, &res);
137314        if( rc!=SQLITE_OK ){
137315          return rc;
137316        }
137317        break;
137318      }
137319    }
137320
137321    if( !res ){
137322      *pbEof = 1;
137323      return SQLITE_OK;
137324    }
137325  }
137326
137327  return SQLITE_OK;
137328}
137329
137330/*
137331** Cursor pCursor currently points at a node that heads a sub-tree of
137332** height iHeight (if iHeight==0, then the node is a leaf). Descend
137333** to point to the left-most cell of the sub-tree that matches the
137334** configured constraints.
137335*/
137336static int descendToCell(
137337  Rtree *pRtree,
137338  RtreeCursor *pCursor,
137339  int iHeight,
137340  int *pEof                 /* OUT: Set to true if cannot descend */
137341){
137342  int isEof;
137343  int rc;
137344  int ii;
137345  RtreeNode *pChild;
137346  sqlite3_int64 iRowid;
137347
137348  RtreeNode *pSavedNode = pCursor->pNode;
137349  int iSavedCell = pCursor->iCell;
137350
137351  assert( iHeight>=0 );
137352
137353  if( iHeight==0 ){
137354    rc = testRtreeEntry(pRtree, pCursor, &isEof);
137355  }else{
137356    rc = testRtreeCell(pRtree, pCursor, &isEof);
137357  }
137358  if( rc!=SQLITE_OK || isEof || iHeight==0 ){
137359    goto descend_to_cell_out;
137360  }
137361
137362  iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
137363  rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
137364  if( rc!=SQLITE_OK ){
137365    goto descend_to_cell_out;
137366  }
137367
137368  nodeRelease(pRtree, pCursor->pNode);
137369  pCursor->pNode = pChild;
137370  isEof = 1;
137371  for(ii=0; isEof && ii<NCELL(pChild); ii++){
137372    pCursor->iCell = ii;
137373    rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
137374    if( rc!=SQLITE_OK ){
137375      goto descend_to_cell_out;
137376    }
137377  }
137378
137379  if( isEof ){
137380    assert( pCursor->pNode==pChild );
137381    nodeReference(pSavedNode);
137382    nodeRelease(pRtree, pChild);
137383    pCursor->pNode = pSavedNode;
137384    pCursor->iCell = iSavedCell;
137385  }
137386
137387descend_to_cell_out:
137388  *pEof = isEof;
137389  return rc;
137390}
137391
137392/*
137393** One of the cells in node pNode is guaranteed to have a 64-bit
137394** integer value equal to iRowid. Return the index of this cell.
137395*/
137396static int nodeRowidIndex(
137397  Rtree *pRtree,
137398  RtreeNode *pNode,
137399  i64 iRowid,
137400  int *piIndex
137401){
137402  int ii;
137403  int nCell = NCELL(pNode);
137404  for(ii=0; ii<nCell; ii++){
137405    if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
137406      *piIndex = ii;
137407      return SQLITE_OK;
137408    }
137409  }
137410  return SQLITE_CORRUPT_VTAB;
137411}
137412
137413/*
137414** Return the index of the cell containing a pointer to node pNode
137415** in its parent. If pNode is the root node, return -1.
137416*/
137417static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
137418  RtreeNode *pParent = pNode->pParent;
137419  if( pParent ){
137420    return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
137421  }
137422  *piIndex = -1;
137423  return SQLITE_OK;
137424}
137425
137426/*
137427** Rtree virtual table module xNext method.
137428*/
137429static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
137430  Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
137431  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
137432  int rc = SQLITE_OK;
137433
137434  /* RtreeCursor.pNode must not be NULL. If is is NULL, then this cursor is
137435  ** already at EOF. It is against the rules to call the xNext() method of
137436  ** a cursor that has already reached EOF.
137437  */
137438  assert( pCsr->pNode );
137439
137440  if( pCsr->iStrategy==1 ){
137441    /* This "scan" is a direct lookup by rowid. There is no next entry. */
137442    nodeRelease(pRtree, pCsr->pNode);
137443    pCsr->pNode = 0;
137444  }else{
137445    /* Move to the next entry that matches the configured constraints. */
137446    int iHeight = 0;
137447    while( pCsr->pNode ){
137448      RtreeNode *pNode = pCsr->pNode;
137449      int nCell = NCELL(pNode);
137450      for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
137451        int isEof;
137452        rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
137453        if( rc!=SQLITE_OK || !isEof ){
137454          return rc;
137455        }
137456      }
137457      pCsr->pNode = pNode->pParent;
137458      rc = nodeParentIndex(pRtree, pNode, &pCsr->iCell);
137459      if( rc!=SQLITE_OK ){
137460        return rc;
137461      }
137462      nodeReference(pCsr->pNode);
137463      nodeRelease(pRtree, pNode);
137464      iHeight++;
137465    }
137466  }
137467
137468  return rc;
137469}
137470
137471/*
137472** Rtree virtual table module xRowid method.
137473*/
137474static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
137475  Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
137476  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
137477
137478  assert(pCsr->pNode);
137479  *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
137480
137481  return SQLITE_OK;
137482}
137483
137484/*
137485** Rtree virtual table module xColumn method.
137486*/
137487static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
137488  Rtree *pRtree = (Rtree *)cur->pVtab;
137489  RtreeCursor *pCsr = (RtreeCursor *)cur;
137490
137491  if( i==0 ){
137492    i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
137493    sqlite3_result_int64(ctx, iRowid);
137494  }else{
137495    RtreeCoord c;
137496    nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
137497#ifndef SQLITE_RTREE_INT_ONLY
137498    if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
137499      sqlite3_result_double(ctx, c.f);
137500    }else
137501#endif
137502    {
137503      assert( pRtree->eCoordType==RTREE_COORD_INT32 );
137504      sqlite3_result_int(ctx, c.i);
137505    }
137506  }
137507
137508  return SQLITE_OK;
137509}
137510
137511/*
137512** Use nodeAcquire() to obtain the leaf node containing the record with
137513** rowid iRowid. If successful, set *ppLeaf to point to the node and
137514** return SQLITE_OK. If there is no such record in the table, set
137515** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
137516** to zero and return an SQLite error code.
137517*/
137518static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
137519  int rc;
137520  *ppLeaf = 0;
137521  sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
137522  if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
137523    i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
137524    rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
137525    sqlite3_reset(pRtree->pReadRowid);
137526  }else{
137527    rc = sqlite3_reset(pRtree->pReadRowid);
137528  }
137529  return rc;
137530}
137531
137532/*
137533** This function is called to configure the RtreeConstraint object passed
137534** as the second argument for a MATCH constraint. The value passed as the
137535** first argument to this function is the right-hand operand to the MATCH
137536** operator.
137537*/
137538static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
137539  RtreeMatchArg *p;
137540  sqlite3_rtree_geometry *pGeom;
137541  int nBlob;
137542
137543  /* Check that value is actually a blob. */
137544  if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR;
137545
137546  /* Check that the blob is roughly the right size. */
137547  nBlob = sqlite3_value_bytes(pValue);
137548  if( nBlob<(int)sizeof(RtreeMatchArg)
137549   || ((nBlob-sizeof(RtreeMatchArg))%sizeof(RtreeDValue))!=0
137550  ){
137551    return SQLITE_ERROR;
137552  }
137553
137554  pGeom = (sqlite3_rtree_geometry *)sqlite3_malloc(
137555      sizeof(sqlite3_rtree_geometry) + nBlob
137556  );
137557  if( !pGeom ) return SQLITE_NOMEM;
137558  memset(pGeom, 0, sizeof(sqlite3_rtree_geometry));
137559  p = (RtreeMatchArg *)&pGeom[1];
137560
137561  memcpy(p, sqlite3_value_blob(pValue), nBlob);
137562  if( p->magic!=RTREE_GEOMETRY_MAGIC
137563   || nBlob!=(int)(sizeof(RtreeMatchArg) + (p->nParam-1)*sizeof(RtreeDValue))
137564  ){
137565    sqlite3_free(pGeom);
137566    return SQLITE_ERROR;
137567  }
137568
137569  pGeom->pContext = p->pContext;
137570  pGeom->nParam = p->nParam;
137571  pGeom->aParam = p->aParam;
137572
137573  pCons->xGeom = p->xGeom;
137574  pCons->pGeom = pGeom;
137575  return SQLITE_OK;
137576}
137577
137578/*
137579** Rtree virtual table module xFilter method.
137580*/
137581static int rtreeFilter(
137582  sqlite3_vtab_cursor *pVtabCursor,
137583  int idxNum, const char *idxStr,
137584  int argc, sqlite3_value **argv
137585){
137586  Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
137587  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
137588
137589  RtreeNode *pRoot = 0;
137590  int ii;
137591  int rc = SQLITE_OK;
137592
137593  rtreeReference(pRtree);
137594
137595  freeCursorConstraints(pCsr);
137596  pCsr->iStrategy = idxNum;
137597
137598  if( idxNum==1 ){
137599    /* Special case - lookup by rowid. */
137600    RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
137601    i64 iRowid = sqlite3_value_int64(argv[0]);
137602    rc = findLeafNode(pRtree, iRowid, &pLeaf);
137603    pCsr->pNode = pLeaf;
137604    if( pLeaf ){
137605      assert( rc==SQLITE_OK );
137606      rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &pCsr->iCell);
137607    }
137608  }else{
137609    /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
137610    ** with the configured constraints.
137611    */
137612    if( argc>0 ){
137613      pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
137614      pCsr->nConstraint = argc;
137615      if( !pCsr->aConstraint ){
137616        rc = SQLITE_NOMEM;
137617      }else{
137618        memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
137619        assert( (idxStr==0 && argc==0)
137620                || (idxStr && (int)strlen(idxStr)==argc*2) );
137621        for(ii=0; ii<argc; ii++){
137622          RtreeConstraint *p = &pCsr->aConstraint[ii];
137623          p->op = idxStr[ii*2];
137624          p->iCoord = idxStr[ii*2+1]-'a';
137625          if( p->op==RTREE_MATCH ){
137626            /* A MATCH operator. The right-hand-side must be a blob that
137627            ** can be cast into an RtreeMatchArg object. One created using
137628            ** an sqlite3_rtree_geometry_callback() SQL user function.
137629            */
137630            rc = deserializeGeometry(argv[ii], p);
137631            if( rc!=SQLITE_OK ){
137632              break;
137633            }
137634          }else{
137635#ifdef SQLITE_RTREE_INT_ONLY
137636            p->rValue = sqlite3_value_int64(argv[ii]);
137637#else
137638            p->rValue = sqlite3_value_double(argv[ii]);
137639#endif
137640          }
137641        }
137642      }
137643    }
137644
137645    if( rc==SQLITE_OK ){
137646      pCsr->pNode = 0;
137647      rc = nodeAcquire(pRtree, 1, 0, &pRoot);
137648    }
137649    if( rc==SQLITE_OK ){
137650      int isEof = 1;
137651      int nCell = NCELL(pRoot);
137652      pCsr->pNode = pRoot;
137653      for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
137654        assert( pCsr->pNode==pRoot );
137655        rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
137656        if( !isEof ){
137657          break;
137658        }
137659      }
137660      if( rc==SQLITE_OK && isEof ){
137661        assert( pCsr->pNode==pRoot );
137662        nodeRelease(pRtree, pRoot);
137663        pCsr->pNode = 0;
137664      }
137665      assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
137666    }
137667  }
137668
137669  rtreeRelease(pRtree);
137670  return rc;
137671}
137672
137673/*
137674** Rtree virtual table module xBestIndex method. There are three
137675** table scan strategies to choose from (in order from most to
137676** least desirable):
137677**
137678**   idxNum     idxStr        Strategy
137679**   ------------------------------------------------
137680**     1        Unused        Direct lookup by rowid.
137681**     2        See below     R-tree query or full-table scan.
137682**   ------------------------------------------------
137683**
137684** If strategy 1 is used, then idxStr is not meaningful. If strategy
137685** 2 is used, idxStr is formatted to contain 2 bytes for each
137686** constraint used. The first two bytes of idxStr correspond to
137687** the constraint in sqlite3_index_info.aConstraintUsage[] with
137688** (argvIndex==1) etc.
137689**
137690** The first of each pair of bytes in idxStr identifies the constraint
137691** operator as follows:
137692**
137693**   Operator    Byte Value
137694**   ----------------------
137695**      =        0x41 ('A')
137696**     <=        0x42 ('B')
137697**      <        0x43 ('C')
137698**     >=        0x44 ('D')
137699**      >        0x45 ('E')
137700**   MATCH       0x46 ('F')
137701**   ----------------------
137702**
137703** The second of each pair of bytes identifies the coordinate column
137704** to which the constraint applies. The leftmost coordinate column
137705** is 'a', the second from the left 'b' etc.
137706*/
137707static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
137708  int rc = SQLITE_OK;
137709  int ii;
137710
137711  int iIdx = 0;
137712  char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
137713  memset(zIdxStr, 0, sizeof(zIdxStr));
137714  UNUSED_PARAMETER(tab);
137715
137716  assert( pIdxInfo->idxStr==0 );
137717  for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
137718    struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
137719
137720    if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
137721      /* We have an equality constraint on the rowid. Use strategy 1. */
137722      int jj;
137723      for(jj=0; jj<ii; jj++){
137724        pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
137725        pIdxInfo->aConstraintUsage[jj].omit = 0;
137726      }
137727      pIdxInfo->idxNum = 1;
137728      pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
137729      pIdxInfo->aConstraintUsage[jj].omit = 1;
137730
137731      /* This strategy involves a two rowid lookups on an B-Tree structures
137732      ** and then a linear search of an R-Tree node. This should be
137733      ** considered almost as quick as a direct rowid lookup (for which
137734      ** sqlite uses an internal cost of 0.0).
137735      */
137736      pIdxInfo->estimatedCost = 10.0;
137737      return SQLITE_OK;
137738    }
137739
137740    if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
137741      u8 op;
137742      switch( p->op ){
137743        case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
137744        case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
137745        case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
137746        case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
137747        case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
137748        default:
137749          assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
137750          op = RTREE_MATCH;
137751          break;
137752      }
137753      zIdxStr[iIdx++] = op;
137754      zIdxStr[iIdx++] = p->iColumn - 1 + 'a';
137755      pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
137756      pIdxInfo->aConstraintUsage[ii].omit = 1;
137757    }
137758  }
137759
137760  pIdxInfo->idxNum = 2;
137761  pIdxInfo->needToFreeIdxStr = 1;
137762  if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
137763    return SQLITE_NOMEM;
137764  }
137765  assert( iIdx>=0 );
137766  pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
137767  return rc;
137768}
137769
137770/*
137771** Return the N-dimensional volumn of the cell stored in *p.
137772*/
137773static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
137774  RtreeDValue area = (RtreeDValue)1;
137775  int ii;
137776  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
137777    area = (area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])));
137778  }
137779  return area;
137780}
137781
137782/*
137783** Return the margin length of cell p. The margin length is the sum
137784** of the objects size in each dimension.
137785*/
137786static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
137787  RtreeDValue margin = (RtreeDValue)0;
137788  int ii;
137789  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
137790    margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
137791  }
137792  return margin;
137793}
137794
137795/*
137796** Store the union of cells p1 and p2 in p1.
137797*/
137798static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
137799  int ii;
137800  if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
137801    for(ii=0; ii<(pRtree->nDim*2); ii+=2){
137802      p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
137803      p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
137804    }
137805  }else{
137806    for(ii=0; ii<(pRtree->nDim*2); ii+=2){
137807      p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
137808      p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
137809    }
137810  }
137811}
137812
137813/*
137814** Return true if the area covered by p2 is a subset of the area covered
137815** by p1. False otherwise.
137816*/
137817static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
137818  int ii;
137819  int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
137820  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
137821    RtreeCoord *a1 = &p1->aCoord[ii];
137822    RtreeCoord *a2 = &p2->aCoord[ii];
137823    if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
137824     || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
137825    ){
137826      return 0;
137827    }
137828  }
137829  return 1;
137830}
137831
137832/*
137833** Return the amount cell p would grow by if it were unioned with pCell.
137834*/
137835static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
137836  RtreeDValue area;
137837  RtreeCell cell;
137838  memcpy(&cell, p, sizeof(RtreeCell));
137839  area = cellArea(pRtree, &cell);
137840  cellUnion(pRtree, &cell, pCell);
137841  return (cellArea(pRtree, &cell)-area);
137842}
137843
137844#if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
137845static RtreeDValue cellOverlap(
137846  Rtree *pRtree,
137847  RtreeCell *p,
137848  RtreeCell *aCell,
137849  int nCell,
137850  int iExclude
137851){
137852  int ii;
137853  RtreeDValue overlap = 0.0;
137854  for(ii=0; ii<nCell; ii++){
137855#if VARIANT_RSTARTREE_CHOOSESUBTREE
137856    if( ii!=iExclude )
137857#else
137858    assert( iExclude==-1 );
137859    UNUSED_PARAMETER(iExclude);
137860#endif
137861    {
137862      int jj;
137863      RtreeDValue o = (RtreeDValue)1;
137864      for(jj=0; jj<(pRtree->nDim*2); jj+=2){
137865        RtreeDValue x1, x2;
137866
137867        x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
137868        x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
137869
137870        if( x2<x1 ){
137871          o = 0.0;
137872          break;
137873        }else{
137874          o = o * (x2-x1);
137875        }
137876      }
137877      overlap += o;
137878    }
137879  }
137880  return overlap;
137881}
137882#endif
137883
137884#if VARIANT_RSTARTREE_CHOOSESUBTREE
137885static RtreeDValue cellOverlapEnlargement(
137886  Rtree *pRtree,
137887  RtreeCell *p,
137888  RtreeCell *pInsert,
137889  RtreeCell *aCell,
137890  int nCell,
137891  int iExclude
137892){
137893  RtreeDValue before, after;
137894  before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
137895  cellUnion(pRtree, p, pInsert);
137896  after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
137897  return (after-before);
137898}
137899#endif
137900
137901
137902/*
137903** This function implements the ChooseLeaf algorithm from Gutman[84].
137904** ChooseSubTree in r*tree terminology.
137905*/
137906static int ChooseLeaf(
137907  Rtree *pRtree,               /* Rtree table */
137908  RtreeCell *pCell,            /* Cell to insert into rtree */
137909  int iHeight,                 /* Height of sub-tree rooted at pCell */
137910  RtreeNode **ppLeaf           /* OUT: Selected leaf page */
137911){
137912  int rc;
137913  int ii;
137914  RtreeNode *pNode;
137915  rc = nodeAcquire(pRtree, 1, 0, &pNode);
137916
137917  for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
137918    int iCell;
137919    sqlite3_int64 iBest = 0;
137920
137921    RtreeDValue fMinGrowth = 0.0;
137922    RtreeDValue fMinArea = 0.0;
137923#if VARIANT_RSTARTREE_CHOOSESUBTREE
137924    RtreeDValue fMinOverlap = 0.0;
137925    RtreeDValue overlap;
137926#endif
137927
137928    int nCell = NCELL(pNode);
137929    RtreeCell cell;
137930    RtreeNode *pChild;
137931
137932    RtreeCell *aCell = 0;
137933
137934#if VARIANT_RSTARTREE_CHOOSESUBTREE
137935    if( ii==(pRtree->iDepth-1) ){
137936      int jj;
137937      aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
137938      if( !aCell ){
137939        rc = SQLITE_NOMEM;
137940        nodeRelease(pRtree, pNode);
137941        pNode = 0;
137942        continue;
137943      }
137944      for(jj=0; jj<nCell; jj++){
137945        nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
137946      }
137947    }
137948#endif
137949
137950    /* Select the child node which will be enlarged the least if pCell
137951    ** is inserted into it. Resolve ties by choosing the entry with
137952    ** the smallest area.
137953    */
137954    for(iCell=0; iCell<nCell; iCell++){
137955      int bBest = 0;
137956      RtreeDValue growth;
137957      RtreeDValue area;
137958      nodeGetCell(pRtree, pNode, iCell, &cell);
137959      growth = cellGrowth(pRtree, &cell, pCell);
137960      area = cellArea(pRtree, &cell);
137961
137962#if VARIANT_RSTARTREE_CHOOSESUBTREE
137963      if( ii==(pRtree->iDepth-1) ){
137964        overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
137965      }else{
137966        overlap = 0.0;
137967      }
137968      if( (iCell==0)
137969       || (overlap<fMinOverlap)
137970       || (overlap==fMinOverlap && growth<fMinGrowth)
137971       || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
137972      ){
137973        bBest = 1;
137974        fMinOverlap = overlap;
137975      }
137976#else
137977      if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
137978        bBest = 1;
137979      }
137980#endif
137981      if( bBest ){
137982        fMinGrowth = growth;
137983        fMinArea = area;
137984        iBest = cell.iRowid;
137985      }
137986    }
137987
137988    sqlite3_free(aCell);
137989    rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
137990    nodeRelease(pRtree, pNode);
137991    pNode = pChild;
137992  }
137993
137994  *ppLeaf = pNode;
137995  return rc;
137996}
137997
137998/*
137999** A cell with the same content as pCell has just been inserted into
138000** the node pNode. This function updates the bounding box cells in
138001** all ancestor elements.
138002*/
138003static int AdjustTree(
138004  Rtree *pRtree,                    /* Rtree table */
138005  RtreeNode *pNode,                 /* Adjust ancestry of this node. */
138006  RtreeCell *pCell                  /* This cell was just inserted */
138007){
138008  RtreeNode *p = pNode;
138009  while( p->pParent ){
138010    RtreeNode *pParent = p->pParent;
138011    RtreeCell cell;
138012    int iCell;
138013
138014    if( nodeParentIndex(pRtree, p, &iCell) ){
138015      return SQLITE_CORRUPT_VTAB;
138016    }
138017
138018    nodeGetCell(pRtree, pParent, iCell, &cell);
138019    if( !cellContains(pRtree, &cell, pCell) ){
138020      cellUnion(pRtree, &cell, pCell);
138021      nodeOverwriteCell(pRtree, pParent, &cell, iCell);
138022    }
138023
138024    p = pParent;
138025  }
138026  return SQLITE_OK;
138027}
138028
138029/*
138030** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
138031*/
138032static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
138033  sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
138034  sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
138035  sqlite3_step(pRtree->pWriteRowid);
138036  return sqlite3_reset(pRtree->pWriteRowid);
138037}
138038
138039/*
138040** Write mapping (iNode->iPar) to the <rtree>_parent table.
138041*/
138042static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
138043  sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
138044  sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
138045  sqlite3_step(pRtree->pWriteParent);
138046  return sqlite3_reset(pRtree->pWriteParent);
138047}
138048
138049static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
138050
138051#if VARIANT_GUTTMAN_LINEAR_SPLIT
138052/*
138053** Implementation of the linear variant of the PickNext() function from
138054** Guttman[84].
138055*/
138056static RtreeCell *LinearPickNext(
138057  Rtree *pRtree,
138058  RtreeCell *aCell,
138059  int nCell,
138060  RtreeCell *pLeftBox,
138061  RtreeCell *pRightBox,
138062  int *aiUsed
138063){
138064  int ii;
138065  for(ii=0; aiUsed[ii]; ii++);
138066  aiUsed[ii] = 1;
138067  return &aCell[ii];
138068}
138069
138070/*
138071** Implementation of the linear variant of the PickSeeds() function from
138072** Guttman[84].
138073*/
138074static void LinearPickSeeds(
138075  Rtree *pRtree,
138076  RtreeCell *aCell,
138077  int nCell,
138078  int *piLeftSeed,
138079  int *piRightSeed
138080){
138081  int i;
138082  int iLeftSeed = 0;
138083  int iRightSeed = 1;
138084  RtreeDValue maxNormalInnerWidth = (RtreeDValue)0;
138085
138086  /* Pick two "seed" cells from the array of cells. The algorithm used
138087  ** here is the LinearPickSeeds algorithm from Gutman[1984]. The
138088  ** indices of the two seed cells in the array are stored in local
138089  ** variables iLeftSeek and iRightSeed.
138090  */
138091  for(i=0; i<pRtree->nDim; i++){
138092    RtreeDValue x1 = DCOORD(aCell[0].aCoord[i*2]);
138093    RtreeDValue x2 = DCOORD(aCell[0].aCoord[i*2+1]);
138094    RtreeDValue x3 = x1;
138095    RtreeDValue x4 = x2;
138096    int jj;
138097
138098    int iCellLeft = 0;
138099    int iCellRight = 0;
138100
138101    for(jj=1; jj<nCell; jj++){
138102      RtreeDValue left = DCOORD(aCell[jj].aCoord[i*2]);
138103      RtreeDValue right = DCOORD(aCell[jj].aCoord[i*2+1]);
138104
138105      if( left<x1 ) x1 = left;
138106      if( right>x4 ) x4 = right;
138107      if( left>x3 ){
138108        x3 = left;
138109        iCellRight = jj;
138110      }
138111      if( right<x2 ){
138112        x2 = right;
138113        iCellLeft = jj;
138114      }
138115    }
138116
138117    if( x4!=x1 ){
138118      RtreeDValue normalwidth = (x3 - x2) / (x4 - x1);
138119      if( normalwidth>maxNormalInnerWidth ){
138120        iLeftSeed = iCellLeft;
138121        iRightSeed = iCellRight;
138122      }
138123    }
138124  }
138125
138126  *piLeftSeed = iLeftSeed;
138127  *piRightSeed = iRightSeed;
138128}
138129#endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
138130
138131#if VARIANT_GUTTMAN_QUADRATIC_SPLIT
138132/*
138133** Implementation of the quadratic variant of the PickNext() function from
138134** Guttman[84].
138135*/
138136static RtreeCell *QuadraticPickNext(
138137  Rtree *pRtree,
138138  RtreeCell *aCell,
138139  int nCell,
138140  RtreeCell *pLeftBox,
138141  RtreeCell *pRightBox,
138142  int *aiUsed
138143){
138144  #define FABS(a) ((a)<0.0?-1.0*(a):(a))
138145
138146  int iSelect = -1;
138147  RtreeDValue fDiff;
138148  int ii;
138149  for(ii=0; ii<nCell; ii++){
138150    if( aiUsed[ii]==0 ){
138151      RtreeDValue left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
138152      RtreeDValue right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
138153      RtreeDValue diff = FABS(right-left);
138154      if( iSelect<0 || diff>fDiff ){
138155        fDiff = diff;
138156        iSelect = ii;
138157      }
138158    }
138159  }
138160  aiUsed[iSelect] = 1;
138161  return &aCell[iSelect];
138162}
138163
138164/*
138165** Implementation of the quadratic variant of the PickSeeds() function from
138166** Guttman[84].
138167*/
138168static void QuadraticPickSeeds(
138169  Rtree *pRtree,
138170  RtreeCell *aCell,
138171  int nCell,
138172  int *piLeftSeed,
138173  int *piRightSeed
138174){
138175  int ii;
138176  int jj;
138177
138178  int iLeftSeed = 0;
138179  int iRightSeed = 1;
138180  RtreeDValue fWaste = 0.0;
138181
138182  for(ii=0; ii<nCell; ii++){
138183    for(jj=ii+1; jj<nCell; jj++){
138184      RtreeDValue right = cellArea(pRtree, &aCell[jj]);
138185      RtreeDValue growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
138186      RtreeDValue waste = growth - right;
138187
138188      if( waste>fWaste ){
138189        iLeftSeed = ii;
138190        iRightSeed = jj;
138191        fWaste = waste;
138192      }
138193    }
138194  }
138195
138196  *piLeftSeed = iLeftSeed;
138197  *piRightSeed = iRightSeed;
138198}
138199#endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
138200
138201/*
138202** Arguments aIdx, aDistance and aSpare all point to arrays of size
138203** nIdx. The aIdx array contains the set of integers from 0 to
138204** (nIdx-1) in no particular order. This function sorts the values
138205** in aIdx according to the indexed values in aDistance. For
138206** example, assuming the inputs:
138207**
138208**   aIdx      = { 0,   1,   2,   3 }
138209**   aDistance = { 5.0, 2.0, 7.0, 6.0 }
138210**
138211** this function sets the aIdx array to contain:
138212**
138213**   aIdx      = { 0,   1,   2,   3 }
138214**
138215** The aSpare array is used as temporary working space by the
138216** sorting algorithm.
138217*/
138218static void SortByDistance(
138219  int *aIdx,
138220  int nIdx,
138221  RtreeDValue *aDistance,
138222  int *aSpare
138223){
138224  if( nIdx>1 ){
138225    int iLeft = 0;
138226    int iRight = 0;
138227
138228    int nLeft = nIdx/2;
138229    int nRight = nIdx-nLeft;
138230    int *aLeft = aIdx;
138231    int *aRight = &aIdx[nLeft];
138232
138233    SortByDistance(aLeft, nLeft, aDistance, aSpare);
138234    SortByDistance(aRight, nRight, aDistance, aSpare);
138235
138236    memcpy(aSpare, aLeft, sizeof(int)*nLeft);
138237    aLeft = aSpare;
138238
138239    while( iLeft<nLeft || iRight<nRight ){
138240      if( iLeft==nLeft ){
138241        aIdx[iLeft+iRight] = aRight[iRight];
138242        iRight++;
138243      }else if( iRight==nRight ){
138244        aIdx[iLeft+iRight] = aLeft[iLeft];
138245        iLeft++;
138246      }else{
138247        RtreeDValue fLeft = aDistance[aLeft[iLeft]];
138248        RtreeDValue fRight = aDistance[aRight[iRight]];
138249        if( fLeft<fRight ){
138250          aIdx[iLeft+iRight] = aLeft[iLeft];
138251          iLeft++;
138252        }else{
138253          aIdx[iLeft+iRight] = aRight[iRight];
138254          iRight++;
138255        }
138256      }
138257    }
138258
138259#if 0
138260    /* Check that the sort worked */
138261    {
138262      int jj;
138263      for(jj=1; jj<nIdx; jj++){
138264        RtreeDValue left = aDistance[aIdx[jj-1]];
138265        RtreeDValue right = aDistance[aIdx[jj]];
138266        assert( left<=right );
138267      }
138268    }
138269#endif
138270  }
138271}
138272
138273/*
138274** Arguments aIdx, aCell and aSpare all point to arrays of size
138275** nIdx. The aIdx array contains the set of integers from 0 to
138276** (nIdx-1) in no particular order. This function sorts the values
138277** in aIdx according to dimension iDim of the cells in aCell. The
138278** minimum value of dimension iDim is considered first, the
138279** maximum used to break ties.
138280**
138281** The aSpare array is used as temporary working space by the
138282** sorting algorithm.
138283*/
138284static void SortByDimension(
138285  Rtree *pRtree,
138286  int *aIdx,
138287  int nIdx,
138288  int iDim,
138289  RtreeCell *aCell,
138290  int *aSpare
138291){
138292  if( nIdx>1 ){
138293
138294    int iLeft = 0;
138295    int iRight = 0;
138296
138297    int nLeft = nIdx/2;
138298    int nRight = nIdx-nLeft;
138299    int *aLeft = aIdx;
138300    int *aRight = &aIdx[nLeft];
138301
138302    SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
138303    SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
138304
138305    memcpy(aSpare, aLeft, sizeof(int)*nLeft);
138306    aLeft = aSpare;
138307    while( iLeft<nLeft || iRight<nRight ){
138308      RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
138309      RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
138310      RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
138311      RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
138312      if( (iLeft!=nLeft) && ((iRight==nRight)
138313       || (xleft1<xright1)
138314       || (xleft1==xright1 && xleft2<xright2)
138315      )){
138316        aIdx[iLeft+iRight] = aLeft[iLeft];
138317        iLeft++;
138318      }else{
138319        aIdx[iLeft+iRight] = aRight[iRight];
138320        iRight++;
138321      }
138322    }
138323
138324#if 0
138325    /* Check that the sort worked */
138326    {
138327      int jj;
138328      for(jj=1; jj<nIdx; jj++){
138329        RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
138330        RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
138331        RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
138332        RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
138333        assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
138334      }
138335    }
138336#endif
138337  }
138338}
138339
138340#if VARIANT_RSTARTREE_SPLIT
138341/*
138342** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
138343*/
138344static int splitNodeStartree(
138345  Rtree *pRtree,
138346  RtreeCell *aCell,
138347  int nCell,
138348  RtreeNode *pLeft,
138349  RtreeNode *pRight,
138350  RtreeCell *pBboxLeft,
138351  RtreeCell *pBboxRight
138352){
138353  int **aaSorted;
138354  int *aSpare;
138355  int ii;
138356
138357  int iBestDim = 0;
138358  int iBestSplit = 0;
138359  RtreeDValue fBestMargin = 0.0;
138360
138361  int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
138362
138363  aaSorted = (int **)sqlite3_malloc(nByte);
138364  if( !aaSorted ){
138365    return SQLITE_NOMEM;
138366  }
138367
138368  aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
138369  memset(aaSorted, 0, nByte);
138370  for(ii=0; ii<pRtree->nDim; ii++){
138371    int jj;
138372    aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
138373    for(jj=0; jj<nCell; jj++){
138374      aaSorted[ii][jj] = jj;
138375    }
138376    SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
138377  }
138378
138379  for(ii=0; ii<pRtree->nDim; ii++){
138380    RtreeDValue margin = 0.0;
138381    RtreeDValue fBestOverlap = 0.0;
138382    RtreeDValue fBestArea = 0.0;
138383    int iBestLeft = 0;
138384    int nLeft;
138385
138386    for(
138387      nLeft=RTREE_MINCELLS(pRtree);
138388      nLeft<=(nCell-RTREE_MINCELLS(pRtree));
138389      nLeft++
138390    ){
138391      RtreeCell left;
138392      RtreeCell right;
138393      int kk;
138394      RtreeDValue overlap;
138395      RtreeDValue area;
138396
138397      memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
138398      memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
138399      for(kk=1; kk<(nCell-1); kk++){
138400        if( kk<nLeft ){
138401          cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
138402        }else{
138403          cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
138404        }
138405      }
138406      margin += cellMargin(pRtree, &left);
138407      margin += cellMargin(pRtree, &right);
138408      overlap = cellOverlap(pRtree, &left, &right, 1, -1);
138409      area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
138410      if( (nLeft==RTREE_MINCELLS(pRtree))
138411       || (overlap<fBestOverlap)
138412       || (overlap==fBestOverlap && area<fBestArea)
138413      ){
138414        iBestLeft = nLeft;
138415        fBestOverlap = overlap;
138416        fBestArea = area;
138417      }
138418    }
138419
138420    if( ii==0 || margin<fBestMargin ){
138421      iBestDim = ii;
138422      fBestMargin = margin;
138423      iBestSplit = iBestLeft;
138424    }
138425  }
138426
138427  memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
138428  memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
138429  for(ii=0; ii<nCell; ii++){
138430    RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
138431    RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
138432    RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
138433    nodeInsertCell(pRtree, pTarget, pCell);
138434    cellUnion(pRtree, pBbox, pCell);
138435  }
138436
138437  sqlite3_free(aaSorted);
138438  return SQLITE_OK;
138439}
138440#endif
138441
138442#if VARIANT_GUTTMAN_SPLIT
138443/*
138444** Implementation of the regular R-tree SplitNode from Guttman[1984].
138445*/
138446static int splitNodeGuttman(
138447  Rtree *pRtree,
138448  RtreeCell *aCell,
138449  int nCell,
138450  RtreeNode *pLeft,
138451  RtreeNode *pRight,
138452  RtreeCell *pBboxLeft,
138453  RtreeCell *pBboxRight
138454){
138455  int iLeftSeed = 0;
138456  int iRightSeed = 1;
138457  int *aiUsed;
138458  int i;
138459
138460  aiUsed = sqlite3_malloc(sizeof(int)*nCell);
138461  if( !aiUsed ){
138462    return SQLITE_NOMEM;
138463  }
138464  memset(aiUsed, 0, sizeof(int)*nCell);
138465
138466  PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
138467
138468  memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
138469  memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
138470  nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
138471  nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
138472  aiUsed[iLeftSeed] = 1;
138473  aiUsed[iRightSeed] = 1;
138474
138475  for(i=nCell-2; i>0; i--){
138476    RtreeCell *pNext;
138477    pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
138478    RtreeDValue diff =
138479      cellGrowth(pRtree, pBboxLeft, pNext) -
138480      cellGrowth(pRtree, pBboxRight, pNext)
138481    ;
138482    if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
138483     || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
138484    ){
138485      nodeInsertCell(pRtree, pRight, pNext);
138486      cellUnion(pRtree, pBboxRight, pNext);
138487    }else{
138488      nodeInsertCell(pRtree, pLeft, pNext);
138489      cellUnion(pRtree, pBboxLeft, pNext);
138490    }
138491  }
138492
138493  sqlite3_free(aiUsed);
138494  return SQLITE_OK;
138495}
138496#endif
138497
138498static int updateMapping(
138499  Rtree *pRtree,
138500  i64 iRowid,
138501  RtreeNode *pNode,
138502  int iHeight
138503){
138504  int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
138505  xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
138506  if( iHeight>0 ){
138507    RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
138508    if( pChild ){
138509      nodeRelease(pRtree, pChild->pParent);
138510      nodeReference(pNode);
138511      pChild->pParent = pNode;
138512    }
138513  }
138514  return xSetMapping(pRtree, iRowid, pNode->iNode);
138515}
138516
138517static int SplitNode(
138518  Rtree *pRtree,
138519  RtreeNode *pNode,
138520  RtreeCell *pCell,
138521  int iHeight
138522){
138523  int i;
138524  int newCellIsRight = 0;
138525
138526  int rc = SQLITE_OK;
138527  int nCell = NCELL(pNode);
138528  RtreeCell *aCell;
138529  int *aiUsed;
138530
138531  RtreeNode *pLeft = 0;
138532  RtreeNode *pRight = 0;
138533
138534  RtreeCell leftbbox;
138535  RtreeCell rightbbox;
138536
138537  /* Allocate an array and populate it with a copy of pCell and
138538  ** all cells from node pLeft. Then zero the original node.
138539  */
138540  aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
138541  if( !aCell ){
138542    rc = SQLITE_NOMEM;
138543    goto splitnode_out;
138544  }
138545  aiUsed = (int *)&aCell[nCell+1];
138546  memset(aiUsed, 0, sizeof(int)*(nCell+1));
138547  for(i=0; i<nCell; i++){
138548    nodeGetCell(pRtree, pNode, i, &aCell[i]);
138549  }
138550  nodeZero(pRtree, pNode);
138551  memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
138552  nCell++;
138553
138554  if( pNode->iNode==1 ){
138555    pRight = nodeNew(pRtree, pNode);
138556    pLeft = nodeNew(pRtree, pNode);
138557    pRtree->iDepth++;
138558    pNode->isDirty = 1;
138559    writeInt16(pNode->zData, pRtree->iDepth);
138560  }else{
138561    pLeft = pNode;
138562    pRight = nodeNew(pRtree, pLeft->pParent);
138563    nodeReference(pLeft);
138564  }
138565
138566  if( !pLeft || !pRight ){
138567    rc = SQLITE_NOMEM;
138568    goto splitnode_out;
138569  }
138570
138571  memset(pLeft->zData, 0, pRtree->iNodeSize);
138572  memset(pRight->zData, 0, pRtree->iNodeSize);
138573
138574  rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
138575  if( rc!=SQLITE_OK ){
138576    goto splitnode_out;
138577  }
138578
138579  /* Ensure both child nodes have node numbers assigned to them by calling
138580  ** nodeWrite(). Node pRight always needs a node number, as it was created
138581  ** by nodeNew() above. But node pLeft sometimes already has a node number.
138582  ** In this case avoid the all to nodeWrite().
138583  */
138584  if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
138585   || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
138586  ){
138587    goto splitnode_out;
138588  }
138589
138590  rightbbox.iRowid = pRight->iNode;
138591  leftbbox.iRowid = pLeft->iNode;
138592
138593  if( pNode->iNode==1 ){
138594    rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
138595    if( rc!=SQLITE_OK ){
138596      goto splitnode_out;
138597    }
138598  }else{
138599    RtreeNode *pParent = pLeft->pParent;
138600    int iCell;
138601    rc = nodeParentIndex(pRtree, pLeft, &iCell);
138602    if( rc==SQLITE_OK ){
138603      nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
138604      rc = AdjustTree(pRtree, pParent, &leftbbox);
138605    }
138606    if( rc!=SQLITE_OK ){
138607      goto splitnode_out;
138608    }
138609  }
138610  if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
138611    goto splitnode_out;
138612  }
138613
138614  for(i=0; i<NCELL(pRight); i++){
138615    i64 iRowid = nodeGetRowid(pRtree, pRight, i);
138616    rc = updateMapping(pRtree, iRowid, pRight, iHeight);
138617    if( iRowid==pCell->iRowid ){
138618      newCellIsRight = 1;
138619    }
138620    if( rc!=SQLITE_OK ){
138621      goto splitnode_out;
138622    }
138623  }
138624  if( pNode->iNode==1 ){
138625    for(i=0; i<NCELL(pLeft); i++){
138626      i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
138627      rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
138628      if( rc!=SQLITE_OK ){
138629        goto splitnode_out;
138630      }
138631    }
138632  }else if( newCellIsRight==0 ){
138633    rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
138634  }
138635
138636  if( rc==SQLITE_OK ){
138637    rc = nodeRelease(pRtree, pRight);
138638    pRight = 0;
138639  }
138640  if( rc==SQLITE_OK ){
138641    rc = nodeRelease(pRtree, pLeft);
138642    pLeft = 0;
138643  }
138644
138645splitnode_out:
138646  nodeRelease(pRtree, pRight);
138647  nodeRelease(pRtree, pLeft);
138648  sqlite3_free(aCell);
138649  return rc;
138650}
138651
138652/*
138653** If node pLeaf is not the root of the r-tree and its pParent pointer is
138654** still NULL, load all ancestor nodes of pLeaf into memory and populate
138655** the pLeaf->pParent chain all the way up to the root node.
138656**
138657** This operation is required when a row is deleted (or updated - an update
138658** is implemented as a delete followed by an insert). SQLite provides the
138659** rowid of the row to delete, which can be used to find the leaf on which
138660** the entry resides (argument pLeaf). Once the leaf is located, this
138661** function is called to determine its ancestry.
138662*/
138663static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
138664  int rc = SQLITE_OK;
138665  RtreeNode *pChild = pLeaf;
138666  while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
138667    int rc2 = SQLITE_OK;          /* sqlite3_reset() return code */
138668    sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
138669    rc = sqlite3_step(pRtree->pReadParent);
138670    if( rc==SQLITE_ROW ){
138671      RtreeNode *pTest;           /* Used to test for reference loops */
138672      i64 iNode;                  /* Node number of parent node */
138673
138674      /* Before setting pChild->pParent, test that we are not creating a
138675      ** loop of references (as we would if, say, pChild==pParent). We don't
138676      ** want to do this as it leads to a memory leak when trying to delete
138677      ** the referenced counted node structures.
138678      */
138679      iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
138680      for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
138681      if( !pTest ){
138682        rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
138683      }
138684    }
138685    rc = sqlite3_reset(pRtree->pReadParent);
138686    if( rc==SQLITE_OK ) rc = rc2;
138687    if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
138688    pChild = pChild->pParent;
138689  }
138690  return rc;
138691}
138692
138693static int deleteCell(Rtree *, RtreeNode *, int, int);
138694
138695static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
138696  int rc;
138697  int rc2;
138698  RtreeNode *pParent = 0;
138699  int iCell;
138700
138701  assert( pNode->nRef==1 );
138702
138703  /* Remove the entry in the parent cell. */
138704  rc = nodeParentIndex(pRtree, pNode, &iCell);
138705  if( rc==SQLITE_OK ){
138706    pParent = pNode->pParent;
138707    pNode->pParent = 0;
138708    rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
138709  }
138710  rc2 = nodeRelease(pRtree, pParent);
138711  if( rc==SQLITE_OK ){
138712    rc = rc2;
138713  }
138714  if( rc!=SQLITE_OK ){
138715    return rc;
138716  }
138717
138718  /* Remove the xxx_node entry. */
138719  sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
138720  sqlite3_step(pRtree->pDeleteNode);
138721  if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
138722    return rc;
138723  }
138724
138725  /* Remove the xxx_parent entry. */
138726  sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
138727  sqlite3_step(pRtree->pDeleteParent);
138728  if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
138729    return rc;
138730  }
138731
138732  /* Remove the node from the in-memory hash table and link it into
138733  ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
138734  */
138735  nodeHashDelete(pRtree, pNode);
138736  pNode->iNode = iHeight;
138737  pNode->pNext = pRtree->pDeleted;
138738  pNode->nRef++;
138739  pRtree->pDeleted = pNode;
138740
138741  return SQLITE_OK;
138742}
138743
138744static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
138745  RtreeNode *pParent = pNode->pParent;
138746  int rc = SQLITE_OK;
138747  if( pParent ){
138748    int ii;
138749    int nCell = NCELL(pNode);
138750    RtreeCell box;                            /* Bounding box for pNode */
138751    nodeGetCell(pRtree, pNode, 0, &box);
138752    for(ii=1; ii<nCell; ii++){
138753      RtreeCell cell;
138754      nodeGetCell(pRtree, pNode, ii, &cell);
138755      cellUnion(pRtree, &box, &cell);
138756    }
138757    box.iRowid = pNode->iNode;
138758    rc = nodeParentIndex(pRtree, pNode, &ii);
138759    if( rc==SQLITE_OK ){
138760      nodeOverwriteCell(pRtree, pParent, &box, ii);
138761      rc = fixBoundingBox(pRtree, pParent);
138762    }
138763  }
138764  return rc;
138765}
138766
138767/*
138768** Delete the cell at index iCell of node pNode. After removing the
138769** cell, adjust the r-tree data structure if required.
138770*/
138771static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
138772  RtreeNode *pParent;
138773  int rc;
138774
138775  if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
138776    return rc;
138777  }
138778
138779  /* Remove the cell from the node. This call just moves bytes around
138780  ** the in-memory node image, so it cannot fail.
138781  */
138782  nodeDeleteCell(pRtree, pNode, iCell);
138783
138784  /* If the node is not the tree root and now has less than the minimum
138785  ** number of cells, remove it from the tree. Otherwise, update the
138786  ** cell in the parent node so that it tightly contains the updated
138787  ** node.
138788  */
138789  pParent = pNode->pParent;
138790  assert( pParent || pNode->iNode==1 );
138791  if( pParent ){
138792    if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
138793      rc = removeNode(pRtree, pNode, iHeight);
138794    }else{
138795      rc = fixBoundingBox(pRtree, pNode);
138796    }
138797  }
138798
138799  return rc;
138800}
138801
138802static int Reinsert(
138803  Rtree *pRtree,
138804  RtreeNode *pNode,
138805  RtreeCell *pCell,
138806  int iHeight
138807){
138808  int *aOrder;
138809  int *aSpare;
138810  RtreeCell *aCell;
138811  RtreeDValue *aDistance;
138812  int nCell;
138813  RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
138814  int iDim;
138815  int ii;
138816  int rc = SQLITE_OK;
138817  int n;
138818
138819  memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
138820
138821  nCell = NCELL(pNode)+1;
138822  n = (nCell+1)&(~1);
138823
138824  /* Allocate the buffers used by this operation. The allocation is
138825  ** relinquished before this function returns.
138826  */
138827  aCell = (RtreeCell *)sqlite3_malloc(n * (
138828    sizeof(RtreeCell)     +         /* aCell array */
138829    sizeof(int)           +         /* aOrder array */
138830    sizeof(int)           +         /* aSpare array */
138831    sizeof(RtreeDValue)             /* aDistance array */
138832  ));
138833  if( !aCell ){
138834    return SQLITE_NOMEM;
138835  }
138836  aOrder    = (int *)&aCell[n];
138837  aSpare    = (int *)&aOrder[n];
138838  aDistance = (RtreeDValue *)&aSpare[n];
138839
138840  for(ii=0; ii<nCell; ii++){
138841    if( ii==(nCell-1) ){
138842      memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
138843    }else{
138844      nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
138845    }
138846    aOrder[ii] = ii;
138847    for(iDim=0; iDim<pRtree->nDim; iDim++){
138848      aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
138849      aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
138850    }
138851  }
138852  for(iDim=0; iDim<pRtree->nDim; iDim++){
138853    aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
138854  }
138855
138856  for(ii=0; ii<nCell; ii++){
138857    aDistance[ii] = 0.0;
138858    for(iDim=0; iDim<pRtree->nDim; iDim++){
138859      RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) -
138860                               DCOORD(aCell[ii].aCoord[iDim*2]));
138861      aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
138862    }
138863  }
138864
138865  SortByDistance(aOrder, nCell, aDistance, aSpare);
138866  nodeZero(pRtree, pNode);
138867
138868  for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
138869    RtreeCell *p = &aCell[aOrder[ii]];
138870    nodeInsertCell(pRtree, pNode, p);
138871    if( p->iRowid==pCell->iRowid ){
138872      if( iHeight==0 ){
138873        rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
138874      }else{
138875        rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
138876      }
138877    }
138878  }
138879  if( rc==SQLITE_OK ){
138880    rc = fixBoundingBox(pRtree, pNode);
138881  }
138882  for(; rc==SQLITE_OK && ii<nCell; ii++){
138883    /* Find a node to store this cell in. pNode->iNode currently contains
138884    ** the height of the sub-tree headed by the cell.
138885    */
138886    RtreeNode *pInsert;
138887    RtreeCell *p = &aCell[aOrder[ii]];
138888    rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
138889    if( rc==SQLITE_OK ){
138890      int rc2;
138891      rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
138892      rc2 = nodeRelease(pRtree, pInsert);
138893      if( rc==SQLITE_OK ){
138894        rc = rc2;
138895      }
138896    }
138897  }
138898
138899  sqlite3_free(aCell);
138900  return rc;
138901}
138902
138903/*
138904** Insert cell pCell into node pNode. Node pNode is the head of a
138905** subtree iHeight high (leaf nodes have iHeight==0).
138906*/
138907static int rtreeInsertCell(
138908  Rtree *pRtree,
138909  RtreeNode *pNode,
138910  RtreeCell *pCell,
138911  int iHeight
138912){
138913  int rc = SQLITE_OK;
138914  if( iHeight>0 ){
138915    RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
138916    if( pChild ){
138917      nodeRelease(pRtree, pChild->pParent);
138918      nodeReference(pNode);
138919      pChild->pParent = pNode;
138920    }
138921  }
138922  if( nodeInsertCell(pRtree, pNode, pCell) ){
138923#if VARIANT_RSTARTREE_REINSERT
138924    if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
138925      rc = SplitNode(pRtree, pNode, pCell, iHeight);
138926    }else{
138927      pRtree->iReinsertHeight = iHeight;
138928      rc = Reinsert(pRtree, pNode, pCell, iHeight);
138929    }
138930#else
138931    rc = SplitNode(pRtree, pNode, pCell, iHeight);
138932#endif
138933  }else{
138934    rc = AdjustTree(pRtree, pNode, pCell);
138935    if( rc==SQLITE_OK ){
138936      if( iHeight==0 ){
138937        rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
138938      }else{
138939        rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
138940      }
138941    }
138942  }
138943  return rc;
138944}
138945
138946static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
138947  int ii;
138948  int rc = SQLITE_OK;
138949  int nCell = NCELL(pNode);
138950
138951  for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
138952    RtreeNode *pInsert;
138953    RtreeCell cell;
138954    nodeGetCell(pRtree, pNode, ii, &cell);
138955
138956    /* Find a node to store this cell in. pNode->iNode currently contains
138957    ** the height of the sub-tree headed by the cell.
138958    */
138959    rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
138960    if( rc==SQLITE_OK ){
138961      int rc2;
138962      rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
138963      rc2 = nodeRelease(pRtree, pInsert);
138964      if( rc==SQLITE_OK ){
138965        rc = rc2;
138966      }
138967    }
138968  }
138969  return rc;
138970}
138971
138972/*
138973** Select a currently unused rowid for a new r-tree record.
138974*/
138975static int newRowid(Rtree *pRtree, i64 *piRowid){
138976  int rc;
138977  sqlite3_bind_null(pRtree->pWriteRowid, 1);
138978  sqlite3_bind_null(pRtree->pWriteRowid, 2);
138979  sqlite3_step(pRtree->pWriteRowid);
138980  rc = sqlite3_reset(pRtree->pWriteRowid);
138981  *piRowid = sqlite3_last_insert_rowid(pRtree->db);
138982  return rc;
138983}
138984
138985/*
138986** Remove the entry with rowid=iDelete from the r-tree structure.
138987*/
138988static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
138989  int rc;                         /* Return code */
138990  RtreeNode *pLeaf = 0;           /* Leaf node containing record iDelete */
138991  int iCell;                      /* Index of iDelete cell in pLeaf */
138992  RtreeNode *pRoot;               /* Root node of rtree structure */
138993
138994
138995  /* Obtain a reference to the root node to initialize Rtree.iDepth */
138996  rc = nodeAcquire(pRtree, 1, 0, &pRoot);
138997
138998  /* Obtain a reference to the leaf node that contains the entry
138999  ** about to be deleted.
139000  */
139001  if( rc==SQLITE_OK ){
139002    rc = findLeafNode(pRtree, iDelete, &pLeaf);
139003  }
139004
139005  /* Delete the cell in question from the leaf node. */
139006  if( rc==SQLITE_OK ){
139007    int rc2;
139008    rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
139009    if( rc==SQLITE_OK ){
139010      rc = deleteCell(pRtree, pLeaf, iCell, 0);
139011    }
139012    rc2 = nodeRelease(pRtree, pLeaf);
139013    if( rc==SQLITE_OK ){
139014      rc = rc2;
139015    }
139016  }
139017
139018  /* Delete the corresponding entry in the <rtree>_rowid table. */
139019  if( rc==SQLITE_OK ){
139020    sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
139021    sqlite3_step(pRtree->pDeleteRowid);
139022    rc = sqlite3_reset(pRtree->pDeleteRowid);
139023  }
139024
139025  /* Check if the root node now has exactly one child. If so, remove
139026  ** it, schedule the contents of the child for reinsertion and
139027  ** reduce the tree height by one.
139028  **
139029  ** This is equivalent to copying the contents of the child into
139030  ** the root node (the operation that Gutman's paper says to perform
139031  ** in this scenario).
139032  */
139033  if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
139034    int rc2;
139035    RtreeNode *pChild;
139036    i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
139037    rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
139038    if( rc==SQLITE_OK ){
139039      rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
139040    }
139041    rc2 = nodeRelease(pRtree, pChild);
139042    if( rc==SQLITE_OK ) rc = rc2;
139043    if( rc==SQLITE_OK ){
139044      pRtree->iDepth--;
139045      writeInt16(pRoot->zData, pRtree->iDepth);
139046      pRoot->isDirty = 1;
139047    }
139048  }
139049
139050  /* Re-insert the contents of any underfull nodes removed from the tree. */
139051  for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
139052    if( rc==SQLITE_OK ){
139053      rc = reinsertNodeContent(pRtree, pLeaf);
139054    }
139055    pRtree->pDeleted = pLeaf->pNext;
139056    sqlite3_free(pLeaf);
139057  }
139058
139059  /* Release the reference to the root node. */
139060  if( rc==SQLITE_OK ){
139061    rc = nodeRelease(pRtree, pRoot);
139062  }else{
139063    nodeRelease(pRtree, pRoot);
139064  }
139065
139066  return rc;
139067}
139068
139069/*
139070** Rounding constants for float->double conversion.
139071*/
139072#define RNDTOWARDS  (1.0 - 1.0/8388608.0)  /* Round towards zero */
139073#define RNDAWAY     (1.0 + 1.0/8388608.0)  /* Round away from zero */
139074
139075#if !defined(SQLITE_RTREE_INT_ONLY)
139076/*
139077** Convert an sqlite3_value into an RtreeValue (presumably a float)
139078** while taking care to round toward negative or positive, respectively.
139079*/
139080static RtreeValue rtreeValueDown(sqlite3_value *v){
139081  double d = sqlite3_value_double(v);
139082  float f = (float)d;
139083  if( f>d ){
139084    f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
139085  }
139086  return f;
139087}
139088static RtreeValue rtreeValueUp(sqlite3_value *v){
139089  double d = sqlite3_value_double(v);
139090  float f = (float)d;
139091  if( f<d ){
139092    f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
139093  }
139094  return f;
139095}
139096#endif /* !defined(SQLITE_RTREE_INT_ONLY) */
139097
139098
139099/*
139100** The xUpdate method for rtree module virtual tables.
139101*/
139102static int rtreeUpdate(
139103  sqlite3_vtab *pVtab,
139104  int nData,
139105  sqlite3_value **azData,
139106  sqlite_int64 *pRowid
139107){
139108  Rtree *pRtree = (Rtree *)pVtab;
139109  int rc = SQLITE_OK;
139110  RtreeCell cell;                 /* New cell to insert if nData>1 */
139111  int bHaveRowid = 0;             /* Set to 1 after new rowid is determined */
139112
139113  rtreeReference(pRtree);
139114  assert(nData>=1);
139115
139116  /* Constraint handling. A write operation on an r-tree table may return
139117  ** SQLITE_CONSTRAINT for two reasons:
139118  **
139119  **   1. A duplicate rowid value, or
139120  **   2. The supplied data violates the "x2>=x1" constraint.
139121  **
139122  ** In the first case, if the conflict-handling mode is REPLACE, then
139123  ** the conflicting row can be removed before proceeding. In the second
139124  ** case, SQLITE_CONSTRAINT must be returned regardless of the
139125  ** conflict-handling mode specified by the user.
139126  */
139127  if( nData>1 ){
139128    int ii;
139129
139130    /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
139131    assert( nData==(pRtree->nDim*2 + 3) );
139132#ifndef SQLITE_RTREE_INT_ONLY
139133    if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
139134      for(ii=0; ii<(pRtree->nDim*2); ii+=2){
139135        cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]);
139136        cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]);
139137        if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
139138          rc = SQLITE_CONSTRAINT;
139139          goto constraint;
139140        }
139141      }
139142    }else
139143#endif
139144    {
139145      for(ii=0; ii<(pRtree->nDim*2); ii+=2){
139146        cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
139147        cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
139148        if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
139149          rc = SQLITE_CONSTRAINT;
139150          goto constraint;
139151        }
139152      }
139153    }
139154
139155    /* If a rowid value was supplied, check if it is already present in
139156    ** the table. If so, the constraint has failed. */
139157    if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
139158      cell.iRowid = sqlite3_value_int64(azData[2]);
139159      if( sqlite3_value_type(azData[0])==SQLITE_NULL
139160       || sqlite3_value_int64(azData[0])!=cell.iRowid
139161      ){
139162        int steprc;
139163        sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
139164        steprc = sqlite3_step(pRtree->pReadRowid);
139165        rc = sqlite3_reset(pRtree->pReadRowid);
139166        if( SQLITE_ROW==steprc ){
139167          if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
139168            rc = rtreeDeleteRowid(pRtree, cell.iRowid);
139169          }else{
139170            rc = SQLITE_CONSTRAINT;
139171            goto constraint;
139172          }
139173        }
139174      }
139175      bHaveRowid = 1;
139176    }
139177  }
139178
139179  /* If azData[0] is not an SQL NULL value, it is the rowid of a
139180  ** record to delete from the r-tree table. The following block does
139181  ** just that.
139182  */
139183  if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
139184    rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
139185  }
139186
139187  /* If the azData[] array contains more than one element, elements
139188  ** (azData[2]..azData[argc-1]) contain a new record to insert into
139189  ** the r-tree structure.
139190  */
139191  if( rc==SQLITE_OK && nData>1 ){
139192    /* Insert the new record into the r-tree */
139193    RtreeNode *pLeaf = 0;
139194
139195    /* Figure out the rowid of the new row. */
139196    if( bHaveRowid==0 ){
139197      rc = newRowid(pRtree, &cell.iRowid);
139198    }
139199    *pRowid = cell.iRowid;
139200
139201    if( rc==SQLITE_OK ){
139202      rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
139203    }
139204    if( rc==SQLITE_OK ){
139205      int rc2;
139206      pRtree->iReinsertHeight = -1;
139207      rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
139208      rc2 = nodeRelease(pRtree, pLeaf);
139209      if( rc==SQLITE_OK ){
139210        rc = rc2;
139211      }
139212    }
139213  }
139214
139215constraint:
139216  rtreeRelease(pRtree);
139217  return rc;
139218}
139219
139220/*
139221** The xRename method for rtree module virtual tables.
139222*/
139223static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
139224  Rtree *pRtree = (Rtree *)pVtab;
139225  int rc = SQLITE_NOMEM;
139226  char *zSql = sqlite3_mprintf(
139227    "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
139228    "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
139229    "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
139230    , pRtree->zDb, pRtree->zName, zNewName
139231    , pRtree->zDb, pRtree->zName, zNewName
139232    , pRtree->zDb, pRtree->zName, zNewName
139233  );
139234  if( zSql ){
139235    rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
139236    sqlite3_free(zSql);
139237  }
139238  return rc;
139239}
139240
139241static sqlite3_module rtreeModule = {
139242  0,                          /* iVersion */
139243  rtreeCreate,                /* xCreate - create a table */
139244  rtreeConnect,               /* xConnect - connect to an existing table */
139245  rtreeBestIndex,             /* xBestIndex - Determine search strategy */
139246  rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
139247  rtreeDestroy,               /* xDestroy - Drop a table */
139248  rtreeOpen,                  /* xOpen - open a cursor */
139249  rtreeClose,                 /* xClose - close a cursor */
139250  rtreeFilter,                /* xFilter - configure scan constraints */
139251  rtreeNext,                  /* xNext - advance a cursor */
139252  rtreeEof,                   /* xEof */
139253  rtreeColumn,                /* xColumn - read data */
139254  rtreeRowid,                 /* xRowid - read data */
139255  rtreeUpdate,                /* xUpdate - write data */
139256  0,                          /* xBegin - begin transaction */
139257  0,                          /* xSync - sync transaction */
139258  0,                          /* xCommit - commit transaction */
139259  0,                          /* xRollback - rollback transaction */
139260  0,                          /* xFindFunction - function overloading */
139261  rtreeRename,                /* xRename - rename the table */
139262  0,                          /* xSavepoint */
139263  0,                          /* xRelease */
139264  0                           /* xRollbackTo */
139265};
139266
139267static int rtreeSqlInit(
139268  Rtree *pRtree,
139269  sqlite3 *db,
139270  const char *zDb,
139271  const char *zPrefix,
139272  int isCreate
139273){
139274  int rc = SQLITE_OK;
139275
139276  #define N_STATEMENT 9
139277  static const char *azSql[N_STATEMENT] = {
139278    /* Read and write the xxx_node table */
139279    "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
139280    "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
139281    "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
139282
139283    /* Read and write the xxx_rowid table */
139284    "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
139285    "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
139286    "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
139287
139288    /* Read and write the xxx_parent table */
139289    "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
139290    "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
139291    "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
139292  };
139293  sqlite3_stmt **appStmt[N_STATEMENT];
139294  int i;
139295
139296  pRtree->db = db;
139297
139298  if( isCreate ){
139299    char *zCreate = sqlite3_mprintf(
139300"CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
139301"CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
139302"CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
139303"INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
139304      zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
139305    );
139306    if( !zCreate ){
139307      return SQLITE_NOMEM;
139308    }
139309    rc = sqlite3_exec(db, zCreate, 0, 0, 0);
139310    sqlite3_free(zCreate);
139311    if( rc!=SQLITE_OK ){
139312      return rc;
139313    }
139314  }
139315
139316  appStmt[0] = &pRtree->pReadNode;
139317  appStmt[1] = &pRtree->pWriteNode;
139318  appStmt[2] = &pRtree->pDeleteNode;
139319  appStmt[3] = &pRtree->pReadRowid;
139320  appStmt[4] = &pRtree->pWriteRowid;
139321  appStmt[5] = &pRtree->pDeleteRowid;
139322  appStmt[6] = &pRtree->pReadParent;
139323  appStmt[7] = &pRtree->pWriteParent;
139324  appStmt[8] = &pRtree->pDeleteParent;
139325
139326  for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
139327    char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
139328    if( zSql ){
139329      rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
139330    }else{
139331      rc = SQLITE_NOMEM;
139332    }
139333    sqlite3_free(zSql);
139334  }
139335
139336  return rc;
139337}
139338
139339/*
139340** The second argument to this function contains the text of an SQL statement
139341** that returns a single integer value. The statement is compiled and executed
139342** using database connection db. If successful, the integer value returned
139343** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
139344** code is returned and the value of *piVal after returning is not defined.
139345*/
139346static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
139347  int rc = SQLITE_NOMEM;
139348  if( zSql ){
139349    sqlite3_stmt *pStmt = 0;
139350    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
139351    if( rc==SQLITE_OK ){
139352      if( SQLITE_ROW==sqlite3_step(pStmt) ){
139353        *piVal = sqlite3_column_int(pStmt, 0);
139354      }
139355      rc = sqlite3_finalize(pStmt);
139356    }
139357  }
139358  return rc;
139359}
139360
139361/*
139362** This function is called from within the xConnect() or xCreate() method to
139363** determine the node-size used by the rtree table being created or connected
139364** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
139365** Otherwise, an SQLite error code is returned.
139366**
139367** If this function is being called as part of an xConnect(), then the rtree
139368** table already exists. In this case the node-size is determined by inspecting
139369** the root node of the tree.
139370**
139371** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
139372** This ensures that each node is stored on a single database page. If the
139373** database page-size is so large that more than RTREE_MAXCELLS entries
139374** would fit in a single node, use a smaller node-size.
139375*/
139376static int getNodeSize(
139377  sqlite3 *db,                    /* Database handle */
139378  Rtree *pRtree,                  /* Rtree handle */
139379  int isCreate,                   /* True for xCreate, false for xConnect */
139380  char **pzErr                    /* OUT: Error message, if any */
139381){
139382  int rc;
139383  char *zSql;
139384  if( isCreate ){
139385    int iPageSize = 0;
139386    zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
139387    rc = getIntFromStmt(db, zSql, &iPageSize);
139388    if( rc==SQLITE_OK ){
139389      pRtree->iNodeSize = iPageSize-64;
139390      if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
139391        pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
139392      }
139393    }else{
139394      *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
139395    }
139396  }else{
139397    zSql = sqlite3_mprintf(
139398        "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
139399        pRtree->zDb, pRtree->zName
139400    );
139401    rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
139402    if( rc!=SQLITE_OK ){
139403      *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
139404    }
139405  }
139406
139407  sqlite3_free(zSql);
139408  return rc;
139409}
139410
139411/*
139412** This function is the implementation of both the xConnect and xCreate
139413** methods of the r-tree virtual table.
139414**
139415**   argv[0]   -> module name
139416**   argv[1]   -> database name
139417**   argv[2]   -> table name
139418**   argv[...] -> column names...
139419*/
139420static int rtreeInit(
139421  sqlite3 *db,                        /* Database connection */
139422  void *pAux,                         /* One of the RTREE_COORD_* constants */
139423  int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
139424  sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
139425  char **pzErr,                       /* OUT: Error message, if any */
139426  int isCreate                        /* True for xCreate, false for xConnect */
139427){
139428  int rc = SQLITE_OK;
139429  Rtree *pRtree;
139430  int nDb;              /* Length of string argv[1] */
139431  int nName;            /* Length of string argv[2] */
139432  int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
139433
139434  const char *aErrMsg[] = {
139435    0,                                                    /* 0 */
139436    "Wrong number of columns for an rtree table",         /* 1 */
139437    "Too few columns for an rtree table",                 /* 2 */
139438    "Too many columns for an rtree table"                 /* 3 */
139439  };
139440
139441  int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
139442  if( aErrMsg[iErr] ){
139443    *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
139444    return SQLITE_ERROR;
139445  }
139446
139447  sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
139448
139449  /* Allocate the sqlite3_vtab structure */
139450  nDb = (int)strlen(argv[1]);
139451  nName = (int)strlen(argv[2]);
139452  pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
139453  if( !pRtree ){
139454    return SQLITE_NOMEM;
139455  }
139456  memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
139457  pRtree->nBusy = 1;
139458  pRtree->base.pModule = &rtreeModule;
139459  pRtree->zDb = (char *)&pRtree[1];
139460  pRtree->zName = &pRtree->zDb[nDb+1];
139461  pRtree->nDim = (argc-4)/2;
139462  pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
139463  pRtree->eCoordType = eCoordType;
139464  memcpy(pRtree->zDb, argv[1], nDb);
139465  memcpy(pRtree->zName, argv[2], nName);
139466
139467  /* Figure out the node size to use. */
139468  rc = getNodeSize(db, pRtree, isCreate, pzErr);
139469
139470  /* Create/Connect to the underlying relational database schema. If
139471  ** that is successful, call sqlite3_declare_vtab() to configure
139472  ** the r-tree table schema.
139473  */
139474  if( rc==SQLITE_OK ){
139475    if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
139476      *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
139477    }else{
139478      char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
139479      char *zTmp;
139480      int ii;
139481      for(ii=4; zSql && ii<argc; ii++){
139482        zTmp = zSql;
139483        zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
139484        sqlite3_free(zTmp);
139485      }
139486      if( zSql ){
139487        zTmp = zSql;
139488        zSql = sqlite3_mprintf("%s);", zTmp);
139489        sqlite3_free(zTmp);
139490      }
139491      if( !zSql ){
139492        rc = SQLITE_NOMEM;
139493      }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
139494        *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
139495      }
139496      sqlite3_free(zSql);
139497    }
139498  }
139499
139500  if( rc==SQLITE_OK ){
139501    *ppVtab = (sqlite3_vtab *)pRtree;
139502  }else{
139503    rtreeRelease(pRtree);
139504  }
139505  return rc;
139506}
139507
139508
139509/*
139510** Implementation of a scalar function that decodes r-tree nodes to
139511** human readable strings. This can be used for debugging and analysis.
139512**
139513** The scalar function takes two arguments, a blob of data containing
139514** an r-tree node, and the number of dimensions the r-tree indexes.
139515** For a two-dimensional r-tree structure called "rt", to deserialize
139516** all nodes, a statement like:
139517**
139518**   SELECT rtreenode(2, data) FROM rt_node;
139519**
139520** The human readable string takes the form of a Tcl list with one
139521** entry for each cell in the r-tree node. Each entry is itself a
139522** list, containing the 8-byte rowid/pageno followed by the
139523** <num-dimension>*2 coordinates.
139524*/
139525static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
139526  char *zText = 0;
139527  RtreeNode node;
139528  Rtree tree;
139529  int ii;
139530
139531  UNUSED_PARAMETER(nArg);
139532  memset(&node, 0, sizeof(RtreeNode));
139533  memset(&tree, 0, sizeof(Rtree));
139534  tree.nDim = sqlite3_value_int(apArg[0]);
139535  tree.nBytesPerCell = 8 + 8 * tree.nDim;
139536  node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
139537
139538  for(ii=0; ii<NCELL(&node); ii++){
139539    char zCell[512];
139540    int nCell = 0;
139541    RtreeCell cell;
139542    int jj;
139543
139544    nodeGetCell(&tree, &node, ii, &cell);
139545    sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
139546    nCell = (int)strlen(zCell);
139547    for(jj=0; jj<tree.nDim*2; jj++){
139548#ifndef SQLITE_RTREE_INT_ONLY
139549      sqlite3_snprintf(512-nCell,&zCell[nCell], " %f",
139550                       (double)cell.aCoord[jj].f);
139551#else
139552      sqlite3_snprintf(512-nCell,&zCell[nCell], " %d",
139553                       cell.aCoord[jj].i);
139554#endif
139555      nCell = (int)strlen(zCell);
139556    }
139557
139558    if( zText ){
139559      char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
139560      sqlite3_free(zText);
139561      zText = zTextNew;
139562    }else{
139563      zText = sqlite3_mprintf("{%s}", zCell);
139564    }
139565  }
139566
139567  sqlite3_result_text(ctx, zText, -1, sqlite3_free);
139568}
139569
139570static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
139571  UNUSED_PARAMETER(nArg);
139572  if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
139573   || sqlite3_value_bytes(apArg[0])<2
139574  ){
139575    sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
139576  }else{
139577    u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
139578    sqlite3_result_int(ctx, readInt16(zBlob));
139579  }
139580}
139581
139582/*
139583** Register the r-tree module with database handle db. This creates the
139584** virtual table module "rtree" and the debugging/analysis scalar
139585** function "rtreenode".
139586*/
139587SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
139588  const int utf8 = SQLITE_UTF8;
139589  int rc;
139590
139591  rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
139592  if( rc==SQLITE_OK ){
139593    rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
139594  }
139595  if( rc==SQLITE_OK ){
139596#ifdef SQLITE_RTREE_INT_ONLY
139597    void *c = (void *)RTREE_COORD_INT32;
139598#else
139599    void *c = (void *)RTREE_COORD_REAL32;
139600#endif
139601    rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
139602  }
139603  if( rc==SQLITE_OK ){
139604    void *c = (void *)RTREE_COORD_INT32;
139605    rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
139606  }
139607
139608  return rc;
139609}
139610
139611/*
139612** A version of sqlite3_free() that can be used as a callback. This is used
139613** in two places - as the destructor for the blob value returned by the
139614** invocation of a geometry function, and as the destructor for the geometry
139615** functions themselves.
139616*/
139617static void doSqlite3Free(void *p){
139618  sqlite3_free(p);
139619}
139620
139621/*
139622** Each call to sqlite3_rtree_geometry_callback() creates an ordinary SQLite
139623** scalar user function. This C function is the callback used for all such
139624** registered SQL functions.
139625**
139626** The scalar user functions return a blob that is interpreted by r-tree
139627** table MATCH operators.
139628*/
139629static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
139630  RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
139631  RtreeMatchArg *pBlob;
139632  int nBlob;
139633
139634  nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue);
139635  pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
139636  if( !pBlob ){
139637    sqlite3_result_error_nomem(ctx);
139638  }else{
139639    int i;
139640    pBlob->magic = RTREE_GEOMETRY_MAGIC;
139641    pBlob->xGeom = pGeomCtx->xGeom;
139642    pBlob->pContext = pGeomCtx->pContext;
139643    pBlob->nParam = nArg;
139644    for(i=0; i<nArg; i++){
139645#ifdef SQLITE_RTREE_INT_ONLY
139646      pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
139647#else
139648      pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
139649#endif
139650    }
139651    sqlite3_result_blob(ctx, pBlob, nBlob, doSqlite3Free);
139652  }
139653}
139654
139655/*
139656** Register a new geometry function for use with the r-tree MATCH operator.
139657*/
139658SQLITE_API int sqlite3_rtree_geometry_callback(
139659  sqlite3 *db,
139660  const char *zGeom,
139661  int (*xGeom)(sqlite3_rtree_geometry *, int, RtreeDValue *, int *),
139662  void *pContext
139663){
139664  RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
139665
139666  /* Allocate and populate the context object. */
139667  pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
139668  if( !pGeomCtx ) return SQLITE_NOMEM;
139669  pGeomCtx->xGeom = xGeom;
139670  pGeomCtx->pContext = pContext;
139671
139672  /* Create the new user-function. Register a destructor function to delete
139673  ** the context object when it is no longer required.  */
139674  return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
139675      (void *)pGeomCtx, geomCallback, 0, 0, doSqlite3Free
139676  );
139677}
139678
139679#if !SQLITE_CORE
139680SQLITE_API int sqlite3_extension_init(
139681  sqlite3 *db,
139682  char **pzErrMsg,
139683  const sqlite3_api_routines *pApi
139684){
139685  SQLITE_EXTENSION_INIT2(pApi)
139686  return sqlite3RtreeInit(db);
139687}
139688#endif
139689
139690#endif
139691
139692/************** End of rtree.c ***********************************************/
139693/************** Begin file icu.c *********************************************/
139694/*
139695** 2007 May 6
139696**
139697** The author disclaims copyright to this source code.  In place of
139698** a legal notice, here is a blessing:
139699**
139700**    May you do good and not evil.
139701**    May you find forgiveness for yourself and forgive others.
139702**    May you share freely, never taking more than you give.
139703**
139704*************************************************************************
139705** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
139706**
139707** This file implements an integration between the ICU library
139708** ("International Components for Unicode", an open-source library
139709** for handling unicode data) and SQLite. The integration uses
139710** ICU to provide the following to SQLite:
139711**
139712**   * An implementation of the SQL regexp() function (and hence REGEXP
139713**     operator) using the ICU uregex_XX() APIs.
139714**
139715**   * Implementations of the SQL scalar upper() and lower() functions
139716**     for case mapping.
139717**
139718**   * Integration of ICU and SQLite collation seqences.
139719**
139720**   * An implementation of the LIKE operator that uses ICU to
139721**     provide case-independent matching.
139722*/
139723
139724#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
139725
139726/* Include ICU headers */
139727#include <unicode/utypes.h>
139728#include <unicode/uregex.h>
139729#include <unicode/ustring.h>
139730#include <unicode/ucol.h>
139731
139732/* #include <assert.h> */
139733
139734#ifndef SQLITE_CORE
139735  SQLITE_EXTENSION_INIT1
139736#else
139737#endif
139738
139739/*
139740** Maximum length (in bytes) of the pattern in a LIKE or GLOB
139741** operator.
139742*/
139743#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
139744# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
139745#endif
139746
139747/*
139748** Version of sqlite3_free() that is always a function, never a macro.
139749*/
139750static void xFree(void *p){
139751  sqlite3_free(p);
139752}
139753
139754/*
139755** Compare two UTF-8 strings for equality where the first string is
139756** a "LIKE" expression. Return true (1) if they are the same and
139757** false (0) if they are different.
139758*/
139759static int icuLikeCompare(
139760  const uint8_t *zPattern,   /* LIKE pattern */
139761  const uint8_t *zString,    /* The UTF-8 string to compare against */
139762  const UChar32 uEsc         /* The escape character */
139763){
139764  static const int MATCH_ONE = (UChar32)'_';
139765  static const int MATCH_ALL = (UChar32)'%';
139766
139767  int iPattern = 0;       /* Current byte index in zPattern */
139768  int iString = 0;        /* Current byte index in zString */
139769
139770  int prevEscape = 0;     /* True if the previous character was uEsc */
139771
139772  while( zPattern[iPattern]!=0 ){
139773
139774    /* Read (and consume) the next character from the input pattern. */
139775    UChar32 uPattern;
139776    U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
139777    assert(uPattern!=0);
139778
139779    /* There are now 4 possibilities:
139780    **
139781    **     1. uPattern is an unescaped match-all character "%",
139782    **     2. uPattern is an unescaped match-one character "_",
139783    **     3. uPattern is an unescaped escape character, or
139784    **     4. uPattern is to be handled as an ordinary character
139785    */
139786    if( !prevEscape && uPattern==MATCH_ALL ){
139787      /* Case 1. */
139788      uint8_t c;
139789
139790      /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
139791      ** MATCH_ALL. For each MATCH_ONE, skip one character in the
139792      ** test string.
139793      */
139794      while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
139795        if( c==MATCH_ONE ){
139796          if( zString[iString]==0 ) return 0;
139797          U8_FWD_1_UNSAFE(zString, iString);
139798        }
139799        iPattern++;
139800      }
139801
139802      if( zPattern[iPattern]==0 ) return 1;
139803
139804      while( zString[iString] ){
139805        if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
139806          return 1;
139807        }
139808        U8_FWD_1_UNSAFE(zString, iString);
139809      }
139810      return 0;
139811
139812    }else if( !prevEscape && uPattern==MATCH_ONE ){
139813      /* Case 2. */
139814      if( zString[iString]==0 ) return 0;
139815      U8_FWD_1_UNSAFE(zString, iString);
139816
139817    }else if( !prevEscape && uPattern==uEsc){
139818      /* Case 3. */
139819      prevEscape = 1;
139820
139821    }else{
139822      /* Case 4. */
139823      UChar32 uString;
139824      U8_NEXT_UNSAFE(zString, iString, uString);
139825      uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
139826      uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
139827      if( uString!=uPattern ){
139828        return 0;
139829      }
139830      prevEscape = 0;
139831    }
139832  }
139833
139834  return zString[iString]==0;
139835}
139836
139837/*
139838** Implementation of the like() SQL function.  This function implements
139839** the build-in LIKE operator.  The first argument to the function is the
139840** pattern and the second argument is the string.  So, the SQL statements:
139841**
139842**       A LIKE B
139843**
139844** is implemented as like(B, A). If there is an escape character E,
139845**
139846**       A LIKE B ESCAPE E
139847**
139848** is mapped to like(B, A, E).
139849*/
139850static void icuLikeFunc(
139851  sqlite3_context *context,
139852  int argc,
139853  sqlite3_value **argv
139854){
139855  const unsigned char *zA = sqlite3_value_text(argv[0]);
139856  const unsigned char *zB = sqlite3_value_text(argv[1]);
139857  UChar32 uEsc = 0;
139858
139859  /* Limit the length of the LIKE or GLOB pattern to avoid problems
139860  ** of deep recursion and N*N behavior in patternCompare().
139861  */
139862  if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
139863    sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
139864    return;
139865  }
139866
139867
139868  if( argc==3 ){
139869    /* The escape character string must consist of a single UTF-8 character.
139870    ** Otherwise, return an error.
139871    */
139872    int nE= sqlite3_value_bytes(argv[2]);
139873    const unsigned char *zE = sqlite3_value_text(argv[2]);
139874    int i = 0;
139875    if( zE==0 ) return;
139876    U8_NEXT(zE, i, nE, uEsc);
139877    if( i!=nE){
139878      sqlite3_result_error(context,
139879          "ESCAPE expression must be a single character", -1);
139880      return;
139881    }
139882  }
139883
139884  if( zA && zB ){
139885    sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
139886  }
139887}
139888
139889/*
139890** This function is called when an ICU function called from within
139891** the implementation of an SQL scalar function returns an error.
139892**
139893** The scalar function context passed as the first argument is
139894** loaded with an error message based on the following two args.
139895*/
139896static void icuFunctionError(
139897  sqlite3_context *pCtx,       /* SQLite scalar function context */
139898  const char *zName,           /* Name of ICU function that failed */
139899  UErrorCode e                 /* Error code returned by ICU function */
139900){
139901  char zBuf[128];
139902  sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
139903  zBuf[127] = '\0';
139904  sqlite3_result_error(pCtx, zBuf, -1);
139905}
139906
139907/*
139908** Function to delete compiled regexp objects. Registered as
139909** a destructor function with sqlite3_set_auxdata().
139910*/
139911static void icuRegexpDelete(void *p){
139912  URegularExpression *pExpr = (URegularExpression *)p;
139913  uregex_close(pExpr);
139914}
139915
139916/*
139917** Implementation of SQLite REGEXP operator. This scalar function takes
139918** two arguments. The first is a regular expression pattern to compile
139919** the second is a string to match against that pattern. If either
139920** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
139921** is 1 if the string matches the pattern, or 0 otherwise.
139922**
139923** SQLite maps the regexp() function to the regexp() operator such
139924** that the following two are equivalent:
139925**
139926**     zString REGEXP zPattern
139927**     regexp(zPattern, zString)
139928**
139929** Uses the following ICU regexp APIs:
139930**
139931**     uregex_open()
139932**     uregex_matches()
139933**     uregex_close()
139934*/
139935static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
139936  UErrorCode status = U_ZERO_ERROR;
139937  URegularExpression *pExpr;
139938  UBool res;
139939  const UChar *zString = sqlite3_value_text16(apArg[1]);
139940
139941  (void)nArg;  /* Unused parameter */
139942
139943  /* If the left hand side of the regexp operator is NULL,
139944  ** then the result is also NULL.
139945  */
139946  if( !zString ){
139947    return;
139948  }
139949
139950  pExpr = sqlite3_get_auxdata(p, 0);
139951  if( !pExpr ){
139952    const UChar *zPattern = sqlite3_value_text16(apArg[0]);
139953    if( !zPattern ){
139954      return;
139955    }
139956    pExpr = uregex_open(zPattern, -1, 0, 0, &status);
139957
139958    if( U_SUCCESS(status) ){
139959      sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
139960    }else{
139961      assert(!pExpr);
139962      icuFunctionError(p, "uregex_open", status);
139963      return;
139964    }
139965  }
139966
139967  /* Configure the text that the regular expression operates on. */
139968  uregex_setText(pExpr, zString, -1, &status);
139969  if( !U_SUCCESS(status) ){
139970    icuFunctionError(p, "uregex_setText", status);
139971    return;
139972  }
139973
139974  /* Attempt the match */
139975  res = uregex_matches(pExpr, 0, &status);
139976  if( !U_SUCCESS(status) ){
139977    icuFunctionError(p, "uregex_matches", status);
139978    return;
139979  }
139980
139981  /* Set the text that the regular expression operates on to a NULL
139982  ** pointer. This is not really necessary, but it is tidier than
139983  ** leaving the regular expression object configured with an invalid
139984  ** pointer after this function returns.
139985  */
139986  uregex_setText(pExpr, 0, 0, &status);
139987
139988  /* Return 1 or 0. */
139989  sqlite3_result_int(p, res ? 1 : 0);
139990}
139991
139992/*
139993** Implementations of scalar functions for case mapping - upper() and
139994** lower(). Function upper() converts its input to upper-case (ABC).
139995** Function lower() converts to lower-case (abc).
139996**
139997** ICU provides two types of case mapping, "general" case mapping and
139998** "language specific". Refer to ICU documentation for the differences
139999** between the two.
140000**
140001** To utilise "general" case mapping, the upper() or lower() scalar
140002** functions are invoked with one argument:
140003**
140004**     upper('ABC') -> 'abc'
140005**     lower('abc') -> 'ABC'
140006**
140007** To access ICU "language specific" case mapping, upper() or lower()
140008** should be invoked with two arguments. The second argument is the name
140009** of the locale to use. Passing an empty string ("") or SQL NULL value
140010** as the second argument is the same as invoking the 1 argument version
140011** of upper() or lower().
140012**
140013**     lower('I', 'en_us') -> 'i'
140014**     lower('I', 'tr_tr') -> '��' (small dotless i)
140015**
140016** http://www.icu-project.org/userguide/posix.html#case_mappings
140017*/
140018static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
140019  const UChar *zInput;
140020  UChar *zOutput;
140021  int nInput;
140022  int nOutput;
140023
140024  UErrorCode status = U_ZERO_ERROR;
140025  const char *zLocale = 0;
140026
140027  assert(nArg==1 || nArg==2);
140028  if( nArg==2 ){
140029    zLocale = (const char *)sqlite3_value_text(apArg[1]);
140030  }
140031
140032  zInput = sqlite3_value_text16(apArg[0]);
140033  if( !zInput ){
140034    return;
140035  }
140036  nInput = sqlite3_value_bytes16(apArg[0]);
140037
140038  nOutput = nInput * 2 + 2;
140039  zOutput = sqlite3_malloc(nOutput);
140040  if( !zOutput ){
140041    return;
140042  }
140043
140044  if( sqlite3_user_data(p) ){
140045    u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
140046  }else{
140047    u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
140048  }
140049
140050  if( !U_SUCCESS(status) ){
140051    icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
140052    return;
140053  }
140054
140055  sqlite3_result_text16(p, zOutput, -1, xFree);
140056}
140057
140058/*
140059** Collation sequence destructor function. The pCtx argument points to
140060** a UCollator structure previously allocated using ucol_open().
140061*/
140062static void icuCollationDel(void *pCtx){
140063  UCollator *p = (UCollator *)pCtx;
140064  ucol_close(p);
140065}
140066
140067/*
140068** Collation sequence comparison function. The pCtx argument points to
140069** a UCollator structure previously allocated using ucol_open().
140070*/
140071static int icuCollationColl(
140072  void *pCtx,
140073  int nLeft,
140074  const void *zLeft,
140075  int nRight,
140076  const void *zRight
140077){
140078  UCollationResult res;
140079  UCollator *p = (UCollator *)pCtx;
140080  res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
140081  switch( res ){
140082    case UCOL_LESS:    return -1;
140083    case UCOL_GREATER: return +1;
140084    case UCOL_EQUAL:   return 0;
140085  }
140086  assert(!"Unexpected return value from ucol_strcoll()");
140087  return 0;
140088}
140089
140090/*
140091** Implementation of the scalar function icu_load_collation().
140092**
140093** This scalar function is used to add ICU collation based collation
140094** types to an SQLite database connection. It is intended to be called
140095** as follows:
140096**
140097**     SELECT icu_load_collation(<locale>, <collation-name>);
140098**
140099** Where <locale> is a string containing an ICU locale identifier (i.e.
140100** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
140101** collation sequence to create.
140102*/
140103static void icuLoadCollation(
140104  sqlite3_context *p,
140105  int nArg,
140106  sqlite3_value **apArg
140107){
140108  sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
140109  UErrorCode status = U_ZERO_ERROR;
140110  const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
140111  const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
140112  UCollator *pUCollator;    /* ICU library collation object */
140113  int rc;                   /* Return code from sqlite3_create_collation_x() */
140114
140115  assert(nArg==2);
140116  zLocale = (const char *)sqlite3_value_text(apArg[0]);
140117  zName = (const char *)sqlite3_value_text(apArg[1]);
140118
140119  if( !zLocale || !zName ){
140120    return;
140121  }
140122
140123  pUCollator = ucol_open(zLocale, &status);
140124  if( !U_SUCCESS(status) ){
140125    icuFunctionError(p, "ucol_open", status);
140126    return;
140127  }
140128  assert(p);
140129
140130  rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
140131      icuCollationColl, icuCollationDel
140132  );
140133  if( rc!=SQLITE_OK ){
140134    ucol_close(pUCollator);
140135    sqlite3_result_error(p, "Error registering collation function", -1);
140136  }
140137}
140138
140139/*
140140** Register the ICU extension functions with database db.
140141*/
140142SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
140143  struct IcuScalar {
140144    const char *zName;                        /* Function name */
140145    int nArg;                                 /* Number of arguments */
140146    int enc;                                  /* Optimal text encoding */
140147    void *pContext;                           /* sqlite3_user_data() context */
140148    void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
140149  } scalars[] = {
140150    {"regexp", 2, SQLITE_ANY,          0, icuRegexpFunc},
140151
140152    {"lower",  1, SQLITE_UTF16,        0, icuCaseFunc16},
140153    {"lower",  2, SQLITE_UTF16,        0, icuCaseFunc16},
140154    {"upper",  1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
140155    {"upper",  2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
140156
140157    {"lower",  1, SQLITE_UTF8,         0, icuCaseFunc16},
140158    {"lower",  2, SQLITE_UTF8,         0, icuCaseFunc16},
140159    {"upper",  1, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
140160    {"upper",  2, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
140161
140162    {"like",   2, SQLITE_UTF8,         0, icuLikeFunc},
140163    {"like",   3, SQLITE_UTF8,         0, icuLikeFunc},
140164
140165    {"icu_load_collation",  2, SQLITE_UTF8, (void*)db, icuLoadCollation},
140166  };
140167
140168  int rc = SQLITE_OK;
140169  int i;
140170
140171  for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
140172    struct IcuScalar *p = &scalars[i];
140173    rc = sqlite3_create_function(
140174        db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
140175    );
140176  }
140177
140178  return rc;
140179}
140180
140181#if !SQLITE_CORE
140182SQLITE_API int sqlite3_extension_init(
140183  sqlite3 *db,
140184  char **pzErrMsg,
140185  const sqlite3_api_routines *pApi
140186){
140187  SQLITE_EXTENSION_INIT2(pApi)
140188  return sqlite3IcuInit(db);
140189}
140190#endif
140191
140192#endif
140193
140194/************** End of icu.c *************************************************/
140195/************** Begin file fts3_icu.c ****************************************/
140196/*
140197** 2007 June 22
140198**
140199** The author disclaims copyright to this source code.  In place of
140200** a legal notice, here is a blessing:
140201**
140202**    May you do good and not evil.
140203**    May you find forgiveness for yourself and forgive others.
140204**    May you share freely, never taking more than you give.
140205**
140206*************************************************************************
140207** This file implements a tokenizer for fts3 based on the ICU library.
140208*/
140209#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
140210#ifdef SQLITE_ENABLE_ICU
140211
140212/* #include <assert.h> */
140213/* #include <string.h> */
140214
140215#include <unicode/ubrk.h>
140216/* #include <unicode/ucol.h> */
140217/* #include <unicode/ustring.h> */
140218#include <unicode/utf16.h>
140219
140220typedef struct IcuTokenizer IcuTokenizer;
140221typedef struct IcuCursor IcuCursor;
140222
140223struct IcuTokenizer {
140224  sqlite3_tokenizer base;
140225  char *zLocale;
140226};
140227
140228struct IcuCursor {
140229  sqlite3_tokenizer_cursor base;
140230
140231  UBreakIterator *pIter;      /* ICU break-iterator object */
140232  int nChar;                  /* Number of UChar elements in pInput */
140233  UChar *aChar;               /* Copy of input using utf-16 encoding */
140234  int *aOffset;               /* Offsets of each character in utf-8 input */
140235
140236  int nBuffer;
140237  char *zBuffer;
140238
140239  int iToken;
140240};
140241
140242/*
140243** Create a new tokenizer instance.
140244*/
140245static int icuCreate(
140246  int argc,                            /* Number of entries in argv[] */
140247  const char * const *argv,            /* Tokenizer creation arguments */
140248  sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
140249){
140250  IcuTokenizer *p;
140251  int n = 0;
140252
140253  if( argc>0 ){
140254    n = strlen(argv[0])+1;
140255  }
140256  p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
140257  if( !p ){
140258    return SQLITE_NOMEM;
140259  }
140260  memset(p, 0, sizeof(IcuTokenizer));
140261
140262  if( n ){
140263    p->zLocale = (char *)&p[1];
140264    memcpy(p->zLocale, argv[0], n);
140265  }
140266
140267  *ppTokenizer = (sqlite3_tokenizer *)p;
140268
140269  return SQLITE_OK;
140270}
140271
140272/*
140273** Destroy a tokenizer
140274*/
140275static int icuDestroy(sqlite3_tokenizer *pTokenizer){
140276  IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
140277  sqlite3_free(p);
140278  return SQLITE_OK;
140279}
140280
140281/*
140282** Prepare to begin tokenizing a particular string.  The input
140283** string to be tokenized is pInput[0..nBytes-1].  A cursor
140284** used to incrementally tokenize this string is returned in
140285** *ppCursor.
140286*/
140287static int icuOpen(
140288  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
140289  const char *zInput,                    /* Input string */
140290  int nInput,                            /* Length of zInput in bytes */
140291  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
140292){
140293  IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
140294  IcuCursor *pCsr;
140295
140296  const int32_t opt = U_FOLD_CASE_DEFAULT;
140297  UErrorCode status = U_ZERO_ERROR;
140298  int nChar;
140299
140300  UChar32 c;
140301  int iInput = 0;
140302  int iOut = 0;
140303
140304  *ppCursor = 0;
140305
140306  if( zInput==0 ){
140307    nInput = 0;
140308    zInput = "";
140309  }else if( nInput<0 ){
140310    nInput = strlen(zInput);
140311  }
140312  nChar = nInput+1;
140313  pCsr = (IcuCursor *)sqlite3_malloc(
140314      sizeof(IcuCursor) +                /* IcuCursor */
140315      ((nChar+3)&~3) * sizeof(UChar) +   /* IcuCursor.aChar[] */
140316      (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
140317  );
140318  if( !pCsr ){
140319    return SQLITE_NOMEM;
140320  }
140321  memset(pCsr, 0, sizeof(IcuCursor));
140322  pCsr->aChar = (UChar *)&pCsr[1];
140323  pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
140324
140325  pCsr->aOffset[iOut] = iInput;
140326  U8_NEXT(zInput, iInput, nInput, c);
140327  while( c>0 ){
140328    int isError = 0;
140329    c = u_foldCase(c, opt);
140330    U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
140331    if( isError ){
140332      sqlite3_free(pCsr);
140333      return SQLITE_ERROR;
140334    }
140335    pCsr->aOffset[iOut] = iInput;
140336
140337    if( iInput<nInput ){
140338      U8_NEXT(zInput, iInput, nInput, c);
140339    }else{
140340      c = 0;
140341    }
140342  }
140343
140344  pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
140345  if( !U_SUCCESS(status) ){
140346    sqlite3_free(pCsr);
140347    return SQLITE_ERROR;
140348  }
140349  pCsr->nChar = iOut;
140350
140351  ubrk_first(pCsr->pIter);
140352  *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
140353  return SQLITE_OK;
140354}
140355
140356/*
140357** Close a tokenization cursor previously opened by a call to icuOpen().
140358*/
140359static int icuClose(sqlite3_tokenizer_cursor *pCursor){
140360  IcuCursor *pCsr = (IcuCursor *)pCursor;
140361  ubrk_close(pCsr->pIter);
140362  sqlite3_free(pCsr->zBuffer);
140363  sqlite3_free(pCsr);
140364  return SQLITE_OK;
140365}
140366
140367/*
140368** Extract the next token from a tokenization cursor.
140369*/
140370static int icuNext(
140371  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
140372  const char **ppToken,               /* OUT: *ppToken is the token text */
140373  int *pnBytes,                       /* OUT: Number of bytes in token */
140374  int *piStartOffset,                 /* OUT: Starting offset of token */
140375  int *piEndOffset,                   /* OUT: Ending offset of token */
140376  int *piPosition                     /* OUT: Position integer of token */
140377){
140378  IcuCursor *pCsr = (IcuCursor *)pCursor;
140379
140380  int iStart = 0;
140381  int iEnd = 0;
140382  int nByte = 0;
140383
140384  while( iStart==iEnd ){
140385    UChar32 c;
140386
140387    iStart = ubrk_current(pCsr->pIter);
140388    iEnd = ubrk_next(pCsr->pIter);
140389    if( iEnd==UBRK_DONE ){
140390      return SQLITE_DONE;
140391    }
140392
140393    while( iStart<iEnd ){
140394      int iWhite = iStart;
140395      U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
140396      if( u_isspace(c) ){
140397        iStart = iWhite;
140398      }else{
140399        break;
140400      }
140401    }
140402    assert(iStart<=iEnd);
140403  }
140404
140405  do {
140406    UErrorCode status = U_ZERO_ERROR;
140407    if( nByte ){
140408      char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
140409      if( !zNew ){
140410        return SQLITE_NOMEM;
140411      }
140412      pCsr->zBuffer = zNew;
140413      pCsr->nBuffer = nByte;
140414    }
140415
140416    u_strToUTF8(
140417        pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
140418        &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
140419        &status                                  /* Output success/failure */
140420    );
140421  } while( nByte>pCsr->nBuffer );
140422
140423  *ppToken = pCsr->zBuffer;
140424  *pnBytes = nByte;
140425  *piStartOffset = pCsr->aOffset[iStart];
140426  *piEndOffset = pCsr->aOffset[iEnd];
140427  *piPosition = pCsr->iToken++;
140428
140429  return SQLITE_OK;
140430}
140431
140432/*
140433** The set of routines that implement the simple tokenizer
140434*/
140435static const sqlite3_tokenizer_module icuTokenizerModule = {
140436  0,                           /* iVersion */
140437  icuCreate,                   /* xCreate  */
140438  icuDestroy,                  /* xCreate  */
140439  icuOpen,                     /* xOpen    */
140440  icuClose,                    /* xClose   */
140441  icuNext,                     /* xNext    */
140442};
140443
140444/*
140445** Set *ppModule to point at the implementation of the ICU tokenizer.
140446*/
140447SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
140448  sqlite3_tokenizer_module const**ppModule
140449){
140450  *ppModule = &icuTokenizerModule;
140451}
140452
140453#endif /* defined(SQLITE_ENABLE_ICU) */
140454#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
140455
140456/************** End of fts3_icu.c ********************************************/
140457